-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathnode.zig
More file actions
2419 lines (2165 loc) · 115 KB
/
Copy pathnode.zig
File metadata and controls
2419 lines (2165 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const enr_lib = @import("enr");
const ENR = enr_lib.ENR;
const utils_lib = @import("@zeam/utils");
const Yaml = @import("yaml").Yaml;
const configs = @import("@zeam/configs");
const api = @import("@zeam/api");
const api_server = @import("api_server.zig");
const metrics_server = @import("metrics_server.zig");
const event_broadcaster = api.event_broadcaster;
const ChainConfig = configs.ChainConfig;
const Chain = configs.Chain;
const ChainOptions = configs.ChainOptions;
const sft = @import("@zeam/state-transition");
const xev = @import("xev").Dynamic;
const networks = @import("@zeam/network");
const Multiaddr = @import("multiaddr").Multiaddr;
const node_lib = @import("@zeam/node");
const key_manager_lib = @import("@zeam/key-manager");
const Clock = node_lib.Clock;
const BeamNode = node_lib.BeamNode;
const SlotDriverWatchdog = node_lib.SlotDriverWatchdog;
const ThreadPool = @import("@zeam/thread-pool").ThreadPool;
const xmss = @import("@zeam/xmss");
const types = @import("@zeam/types");
const LoggerConfig = utils_lib.ZeamLoggerConfig;
const NodeCommand = @import("main.zig").NodeCommand;
const zeam_utils = @import("@zeam/utils");
const database = @import("@zeam/database");
const json = std.json;
const utils = @import("@zeam/utils");
const ssz = @import("ssz");
const zeam_metrics = @import("@zeam/metrics");
const build_options = @import("build_options");
// Structure to hold parsed ENR fields from validator-config.yaml
const EnrFields = struct {
ip: ?[]const u8 = null,
ip6: ?[]const u8 = null,
tcp: ?u16 = null,
udp: ?u16 = null,
quic: ?u16 = null,
seq: ?u64 = null,
// Allow for custom fields
custom_fields: std.StringHashMap([]const u8),
pub fn deinit(self: *EnrFields, allocator: std.mem.Allocator) void {
if (self.ip) |ip_str| allocator.free(ip_str);
if (self.ip6) |ip6_str| allocator.free(ip6_str);
var iterator = self.custom_fields.iterator();
while (iterator.next()) |entry| {
allocator.free(entry.key_ptr.*);
allocator.free(entry.value_ptr.*);
}
self.custom_fields.deinit();
}
};
/// Represents a validator assignment from annotated_validators.yaml
pub const ValidatorAssignment = struct {
index: usize,
pubkey_hex: []const u8,
privkey_file: []const u8,
pub fn deinit(self: *ValidatorAssignment, allocator: std.mem.Allocator) void {
allocator.free(self.pubkey_hex);
allocator.free(self.privkey_file);
}
};
/// Runtime toggle for the experimental ethp2p transport: truthy `ZEAM_ETHP2P`
/// env var. Only consulted when the binary was built with `-Dethp2p=true`
/// (see the comptime guard at the call site). Mirrors the `DEBUG_QUIC` /
/// `ZEAM_STRESS_*` env-var convention; a CLI flag would trip zigcli's
/// comptime branch quota.
fn ethp2pRuntimeEnabled() bool {
const raw = std.c.getenv("ZEAM_ETHP2P") orelse return false;
const v = std.mem.trim(u8, std.mem.span(raw), " \t\n\r");
return std.mem.eql(u8, v, "1") or
std.ascii.eqlIgnoreCase(v, "true") or
std.ascii.eqlIgnoreCase(v, "yes") or
std.ascii.eqlIgnoreCase(v, "on");
}
/// Read a trimmed, non-empty env var and dupe it from `allocator`, else null.
fn ethp2pEnvDup(allocator: std.mem.Allocator, name: [*:0]const u8) !?[]const u8 {
const raw = std.c.getenv(name) orelse return null;
const v = std.mem.trim(u8, std.mem.span(raw), " \t\n\r");
if (v.len == 0) return null;
return try allocator.dupe(u8, v);
}
/// Parse a comma-separated env var into an owned list of trimmed entries.
fn ethp2pEnvList(allocator: std.mem.Allocator, name: [*:0]const u8) ![]const []const u8 {
const joined = (try ethp2pEnvDup(allocator, name)) orelse return &.{};
defer allocator.free(joined);
var list: std.ArrayList([]const u8) = .empty;
errdefer list.deinit(allocator);
var it = std.mem.tokenizeScalar(u8, joined, ',');
while (it.next()) |tok| {
const t = std.mem.trim(u8, tok, " \t");
if (t.len > 0) try list.append(allocator, try allocator.dupe(u8, t));
}
return try list.toOwnedSlice(allocator);
}
/// Port shift applied to each libp2p QUIC port to derive its ethp2p port
/// (`ZEAM_ETHP2P_PORT_OFFSET`, default 1 — the ethlambda convention
/// "ethp2p = gossipsub port + 1"). Base QUIC ports must be spaced by more than
/// this offset so a node's ethp2p port never collides with another node's
/// libp2p port on a shared host network.
fn ethp2pPortOffset() u16 {
const raw = std.c.getenv("ZEAM_ETHP2P_PORT_OFFSET") orelse return 1;
const v = std.mem.trim(u8, std.mem.span(raw), " \t\n\r");
return std.fmt.parseInt(u16, v, 10) catch 1;
}
/// TLS SNI used on ethp2p dials. `ZEAM_ETHP2P_SERVER_NAME` or a static default;
/// env-span / static literal, not owned.
fn ethp2pServerName() []const u8 {
if (std.c.getenv("ZEAM_ETHP2P_SERVER_NAME")) |p| return std.mem.span(p);
return "127.0.0.1";
}
/// Write `bytes` to `<dir>/<name>` (creating `dir`) and return the allocated
/// path. Used to materialise the runtime-generated ethp2p TLS PEMs, which the
/// adapter consumes by path (it has no in-memory PEM entry point). The files
/// live under the node's private data dir and are overwritten each run.
///
/// When `enforce_mode` is non-null the file is forced to that mode — used to
/// make the private key owner-only (`0o600`) so a copy of it plus the cert
/// cannot be used to impersonate this node's ethp2p listener.
///
/// `createFile`'s `.permissions` only applies when the file is *created*; an
/// already-existing file (e.g. a `key.pem` a prior build wrote with the default
/// `0o666`) keeps its old, lax mode after truncation. So we also
/// `setPermissions` explicitly, and do it while the file is still empty — before
/// the key bytes are written — so the secret is never briefly present at a
/// looser mode. `0o600` carries no group/other bits, so umask cannot widen it.
/// The public cert passes `null` and keeps the create-time default (umask'd),
/// which must not be force-set to `0o666` (that would make it world-writable).
fn ethp2pWritePem(allocator: std.mem.Allocator, dir: []const u8, name: []const u8, bytes: []const u8, enforce_mode: ?std.Io.File.Permissions) ![]u8 {
const io = std.Io.Threaded.global_single_threaded.io();
std.Io.Dir.cwd().createDirPath(io, dir) catch |e| switch (e) {
error.PathAlreadyExists => {},
else => return e,
};
const path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir, name });
errdefer allocator.free(path);
const create_perms = enforce_mode orelse .default_file;
const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = true, .permissions = create_perms });
defer file.close(io);
// Tighten an already-existing file in place, before writing any bytes.
if (enforce_mode) |mode| try file.setPermissions(io, mode);
var wbuf: [4096]u8 = undefined;
var writer = file.writer(io, &wbuf);
try writer.interface.writeAll(bytes);
try writer.interface.flush();
return path;
}
/// The substring after `key` in `s`, up to the next `/` (or end). Used to pull
/// fields out of a QUIC multiaddr like `/ip4/127.0.0.1/udp/9001/quic-v1/...`.
fn multiaddrSegAfter(s: []const u8, key: []const u8) ?[]const u8 {
const idx = std.mem.indexOf(u8, s, key) orelse return null;
const rest = s[idx + key.len ..];
const end = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len;
return rest[0..end];
}
const QuicIpPort = struct { ip: []const u8, port: u16 };
fn parseQuicIpPort(ma: []const u8) ?QuicIpPort {
const ip = multiaddrSegAfter(ma, "/ip4/") orelse multiaddrSegAfter(ma, "/ip6/") orelse return null;
const port_s = multiaddrSegAfter(ma, "/udp/") orelse return null;
const port = std.fmt.parseInt(u16, port_s, 10) catch return null;
return .{ .ip = ip, .port = port };
}
/// Free the allocations owned by a config built via `Node.buildEthp2pConfig`:
/// the listen address, static-peer strings, and the cert/key file paths (all
/// heap-owned — env values are duped, derived/generated ones are freshly
/// allocated). `local_peer_id` (the long-lived `node_key`) and the static
/// `server_name` are NOT owned here. `listen_addr`, `static_peers` and the
/// PEM files are consumed synchronously by the adapter's `start` (endpoint bind
/// + dials), so freeing the path strings after `beam_node.init` returns is safe;
/// only `local_peer_id` is retained by the RS engine, and `node_key` outlives
/// the process.
fn freeEthp2pConfig(allocator: std.mem.Allocator, cfg: networks.Ethp2pConfig) void {
if (cfg.listen_addr) |la| allocator.free(la);
for (cfg.static_peers) |p| allocator.free(p);
allocator.free(cfg.static_peers);
if (cfg.server_certificate_pem_path) |p| allocator.free(p);
if (cfg.server_private_key_pem_path) |p| allocator.free(p);
}
pub const NodeOptions = struct {
network_id: u32,
node_key: []const u8,
node_key_index: usize,
/// Path to the lean-quickstart `<node>.key` file holding a 64-hex-char
/// ASCII representation of the 32-byte ECDSA-P-256 host-identity seed.
/// Threaded through to `EthLibp2pParams.host_identity_key_path` so the
/// libp2p PeerId derives from the SAME seed `eth-beacon-genesis` used to
/// populate `nodes.yaml`. Without this, every outbound dial fails
/// `PeerIdMismatch` against the dial-multiaddr's expected peer id.
/// `null` only when the legacy code path (no real networking) is in use.
host_identity_key_path: ?[]const u8 = null,
// 1. a special value of "genesis_bootnode" for validator config means its a genesis bootnode and so
// the configuration is to be picked from genesis
// 2. otherwise validator_config is dir path to this nodes's validator_config.yaml and annotated_validators.yaml
// and one must use all the nodes in genesis nodes.yaml as peers
validator_config: []const u8,
bootnodes: []const []const u8,
validator_assignments: []ValidatorAssignment,
genesis_spec: types.GenesisSpec,
metrics_enable: bool,
is_aggregator: bool,
/// If aggregator, additional subnet ids to import and aggregate
aggregation_subnet_ids: ?[]u32 = null,
api_port: u16,
metrics_port: u16,
local_priv_key: []const u8,
logger_config: *LoggerConfig,
database_path: []const u8,
hash_sig_key_dir: []const u8,
node_registry: *node_lib.NodeNameRegistry,
checkpoint_sync_url: ?[]const u8 = null,
attestation_committee_count: ?u64 = null,
max_attestations_data: ?u8 = null,
db_backend: database.Backend = .rocksdb,
chain_spec: ?[]const u8 = null,
/// Route producer-side gossip handlers through the chain-worker
/// queue. Defaults to `true`: the worker path is the supported prod
/// path; surfaced as `--chain-worker` on the `zeam node` CLI, with
/// `--chain-worker false` as the kill-switch for the legacy
/// synchronous path.
chain_worker_enabled: bool = true,
/// Override the rayon worker count for the multisig aggregate prover.
/// `null` keeps the existing automatic split (half of the post-system-
/// thread budget to Zig workers, half to rayon). Aggregators in
/// CPU-rich environments can set this higher to give the prover more
/// parallelism without rebuilding. Surfaced as `--rayon-threads`
/// on the `zeam node` CLI.
rayon_threads: ?u32 = null,
/// Minimum (children + gossip-sig) inputs required before the
/// aggregator pre-filter lets an `AttestationData` reach the FFI.
/// Threaded through to `ForkChoice.min_aggregation_inputs` and
/// applied by `pruneTrivialFromAggregateSnapshot` before
/// `computeAggregatedSignatures` runs (the FFI itself stays
/// free of this filtering). Surfaced as `--min-aggregation-inputs` on the
/// `zeam node` CLI; default is `default_min_aggregation_inputs`.
min_aggregation_inputs: u32 = types.default_min_aggregation_inputs,
/// Percentage of the proposal interval allocated to interval-4 Type-1
/// warm-up. Interval-0 proposal packaging does not run Type-1 aggregation.
type1_aggregation_deadline_pct: u32 = node_lib.default_type1_aggregation_deadline_pct,
/// Cap on the number of child STARK proofs merged with raw signatures
/// by the aggregator-worker path. Threaded through to
/// `ForkChoice.max_aggregation_children` and applied by
/// `prepareAggregateAttData` after greedy + subset-prune. Surfaced as
/// `--max-aggregation-children` on the `zeam node` CLI; default is
/// `pkgs/types/src/block.zig:default_max_aggregation_children` (0 —
/// flat-only worker path).
max_aggregation_children: u32 = types.default_max_aggregation_children,
/// Cap on the number of `AttestationData` the aggregator proves+publishes
/// per tick (greedy justification path). Threaded through to
/// `ForkChoice.max_aggregations_per_tick` and consumed by
/// `aggregateUnlocked`. Surfaced as `--max-aggregations-per-tick` on the
/// `zeam node` CLI; default is
/// `pkgs/types/src/block.zig:default_max_aggregations_per_tick` (1 —
/// single-aggregation behaviour).
max_aggregations_per_tick: u32 = types.default_max_aggregations_per_tick,
pub fn deinit(self: *NodeOptions, allocator: std.mem.Allocator) void {
for (self.bootnodes) |b| allocator.free(b);
allocator.free(self.bootnodes);
for (self.validator_assignments) |*assignment| {
@constCast(assignment).deinit(allocator);
}
allocator.free(self.validator_assignments);
allocator.free(self.local_priv_key);
allocator.free(self.hash_sig_key_dir);
if (self.aggregation_subnet_ids) |ids| allocator.free(ids);
self.node_registry.deinit();
allocator.destroy(self.node_registry);
}
pub fn getValidatorIndices(self: *const NodeOptions, allocator: std.mem.Allocator) ![]usize {
// Deduplicate: each validator index may appear multiple times in
// assignments (e.g. once for the attester key, once for the proposer
// key). The validator only needs to attest/propose once per slot.
var seen = std.AutoHashMap(usize, void).init(allocator);
defer seen.deinit();
var unique: std.ArrayList(usize) = .empty;
errdefer unique.deinit(allocator);
for (self.validator_assignments) |assignment| {
const result = try seen.getOrPut(assignment.index);
if (!result.found_existing) {
try unique.append(allocator, assignment.index);
}
}
return try unique.toOwnedSlice(allocator);
}
};
/// A Node that encapsulates the networking, blockchain, and validator functionalities.
/// It manages the event loop, network interface, clock, and beam node.
pub const Node = struct {
loop: xev.Loop,
/// `EthLibp2p.init` returns a heap-allocated `*Self`, so this is a
/// pointer (was a value field under the legacy `EthLibp2p` flow).
network: *networks.EthLibp2p,
/// String-form listen + connect multiaddrs handed to v2. Owned by
/// `Node`; freed at `deinit` so v2 (which stores slice refs, not
/// dupes) is safe across its lifetime.
listen_addresses_str: []u8,
connect_peers_str: []u8,
beam_node: BeamNode,
clock: Clock,
enr: ENR,
options: *const NodeOptions,
allocator: std.mem.Allocator,
logger: zeam_utils.ModuleLogger,
db: database.Db,
key_manager: key_manager_lib.KeyManager,
api_server_handle: ?*api_server.ApiServer,
metrics_server_handle: ?*metrics_server.MetricsServer,
anchor_state: *types.BeamState,
/// Shared worker pool for CPU-bound chain work (attestation signature verification).
thread_pool: *ThreadPool,
/// Background watchdog that monitors libxev slot-driver liveness.
/// `null` until `run()` spawns it; `stop()` joins it.
slot_driver_watchdog: ?SlotDriverWatchdog = null,
const Self = @This();
/// Thread roles configured at startup. Counts are logged once init
/// completes so operators can verify `--rayon-threads` / aggregator
/// auto-tune and compare against `cpu_count`.
const StartupThreadBudget = struct {
cpu_count: usize,
zig_worker_pool: usize,
rayon: usize,
aggregate_max_inflight: u32,
chain_worker: usize,
metrics_server: usize,
api_server: usize,
rayon_source: []const u8,
fn estimatedTotal(self: @This()) usize {
// main (xev slot-driver) + Io.Threaded + libp2p + zig pool + rayon
// + chain-worker + metrics + api + slot watchdog (run()).
return 1 + 1 + 1 + self.zig_worker_pool + self.rayon + self.chain_worker +
self.metrics_server + self.api_server + 1;
}
};
fn logStartupThreadBudget(self: *Self, budget: StartupThreadBudget) void {
self.logger.info(
"startup thread budget: cpu_count={d} estimated_os_threads≈{d}",
.{ budget.cpu_count, budget.estimatedTotal() },
);
self.logger.info(
" main/xev slot-driver: 1 (this thread runs xev.Loop via clock.run)",
.{},
);
self.logger.info(
" std.Io.Threaded: 1 (blocking I/O for Zig pool + disk)",
.{},
);
self.logger.info(
" libp2p rust bridge: 1 (spawned in network.run)",
.{},
);
self.logger.info(
" zig worker pool: {d} (aggregate_max_inflight={d})",
.{ budget.zig_worker_pool, budget.aggregate_max_inflight },
);
self.logger.info(
" rayon (XMSS prover): {d}{s}",
.{ budget.rayon, budget.rayon_source },
);
self.logger.info(
" chain-worker: {d}{s}",
.{ budget.chain_worker, if (budget.chain_worker == 0) " (disabled)" else "" },
);
self.logger.info(
" metrics HTTP server: {d}",
.{budget.metrics_server},
);
self.logger.info(
" api HTTP server: {d}",
.{budget.api_server},
);
self.logger.info(
" slot-driver watchdog: 1 (spawned at run() start)",
.{},
);
}
/// Closes the current database, wipes the on-disk rocksdb directory, and
/// reopens a fresh database at the same path.
///
/// If `ignore_not_found` is true, `error.FileNotFound` from the directory
/// deletion is silently swallowed (used for first-run installs where the
/// db directory has never been created). Set it to false when wiping a db
/// that is known to exist (genesis time mismatch case).
fn wipeAndReopenDb(
db: *database.Db,
allocator: std.mem.Allocator,
database_path: []const u8,
logger_config: *LoggerConfig,
logger: zeam_utils.ModuleLogger,
backend: database.Backend,
ignore_not_found: bool,
) !void {
db.deinit();
const io = std.Io.Threaded.global_single_threaded.io();
// Both backends store their working set under the same base
// directory; deleting it yields a clean slate for either engine.
const backend_dir = switch (backend) {
.rocksdb => "rocksdb",
.lmdb => "lmdb",
};
const db_path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ database_path, backend_dir });
defer allocator.free(db_path);
std.Io.Dir.cwd().deleteTree(io, db_path) catch |wipe_err| {
if (!ignore_not_found or wipe_err != error.FileNotFound) {
logger.err("failed to delete database directory '{s}': {any}", .{ db_path, wipe_err });
return wipe_err;
}
};
db.* = try database.Db.openBackend(allocator, logger_config.logger(.database), database_path, backend);
}
/// Build the experimental ethp2p adapter config. Every field follows the
/// precedence explicit-env → derived-from-libp2p → default, so an operator
/// can enable the transport with just `ZEAM_ETHP2P=1` (endpoints auto-derived
/// from the node's own libp2p QUIC ports with a `+offset` shift, cert/key from
/// the image's bundled devnet PEMs) while retaining full manual control.
///
/// - Identity: the node's `node_key` (unique per node; retained by the RS
/// engine, and outlives the process — never freed).
/// - Listen: `ZEAM_ETHP2P_LISTEN`, else `0.0.0.0:<own libp2p QUIC port + offset>`.
/// - Peers: `ZEAM_ETHP2P_STATIC_PEERS` (comma), else each libp2p connect-peer's
/// `ip:<port + offset>`.
/// - Cert/key: `ZEAM_ETHP2P_SERVER_CERT` / `_KEY` (paths), else a fresh
/// per-node self-signed TLS cert is generated at runtime from the node's
/// host identity (the same facility the libp2p QUIC transport uses) and
/// written under the data dir — matching how libp2p mints its cert.
/// Nothing is committed or shared. Only produced when we listen.
/// - SNI: `ZEAM_ETHP2P_SERVER_NAME`, else `127.0.0.1`.
///
/// Owned allocations (`listen_addr`, `static_peers`, cert/key paths) are
/// released by `freeEthp2pConfig` after `beam_node.init` — the adapter's
/// `start` binds the listener (reading the PEM files) and dials synchronously
/// and retains none of these.
fn buildEthp2pConfig(self: *Self, allocator: std.mem.Allocator) !networks.Ethp2pConfig {
const offset = ethp2pPortOffset();
// Listen: explicit env, else derive from our own libp2p QUIC listen port
// (bind on 0.0.0.0 so containerised nodes are reachable).
var listen_addr: ?[]const u8 = try ethp2pEnvDup(allocator, "ZEAM_ETHP2P_LISTEN");
errdefer if (listen_addr) |la| allocator.free(la);
if (listen_addr == null) {
if (parseQuicIpPort(self.listen_addresses_str)) |own| {
listen_addr = try std.fmt.allocPrint(allocator, "0.0.0.0:{d}", .{@as(u32, own.port) + offset});
}
}
// Our own libp2p QUIC port, used to skip the self-entry that the
// genesis peer list always contains (every node appears in
// `nodes.yaml`, including itself). A `connect()` to our own ethp2p
// listener blocks `start()` in its synchronous handshake-poll loop —
// the server-side accept only runs later in `tick()`, so the self-dial
// never completes and stalls dialing of the real peers behind it.
const own_port: ?u16 = if (parseQuicIpPort(self.listen_addresses_str)) |own| own.port else null;
// Static peers: explicit env, else derive from libp2p connect-peers.
const static_peers: []const []const u8 = blk: {
const env_peers = try ethp2pEnvList(allocator, "ZEAM_ETHP2P_STATIC_PEERS");
if (env_peers.len > 0) break :blk env_peers;
allocator.free(env_peers);
var peers: std.ArrayListUnmanaged([]const u8) = .empty;
errdefer {
for (peers.items) |p| allocator.free(p);
peers.deinit(allocator);
}
var it = std.mem.splitScalar(u8, self.connect_peers_str, ',');
while (it.next()) |ma| {
const trimmed = std.mem.trim(u8, ma, " \t");
if (trimmed.len == 0) continue;
const ipp = parseQuicIpPort(trimmed) orelse continue;
// Genesis peer lists include this node itself; never dial self.
if (own_port) |op| if (ipp.port == op) continue;
const peer_s = try std.fmt.allocPrint(allocator, "{s}:{d}", .{ ipp.ip, @as(u32, ipp.port) + offset });
try peers.append(allocator, peer_s);
}
break :blk try peers.toOwnedSlice(allocator);
};
errdefer {
for (static_peers) |p| allocator.free(p);
allocator.free(static_peers);
}
// TLS server identity — only needed when we actually listen. Prefer
// explicit env paths; otherwise mint a fresh per-node cert at runtime
// from the node's host identity (never shipped/shared) and write the
// PEMs under the data dir for the adapter to read by path.
var cert_path: ?[]const u8 = null;
errdefer if (cert_path) |p| allocator.free(p);
var key_path: ?[]const u8 = null;
errdefer if (key_path) |p| allocator.free(p);
if (listen_addr != null) {
if (try ethp2pEnvDup(allocator, "ZEAM_ETHP2P_SERVER_CERT")) |c| {
cert_path = c;
key_path = try ethp2pEnvDup(allocator, "ZEAM_ETHP2P_SERVER_KEY");
} else {
const pems = try self.network.generateAuxQuicCertPems(allocator);
defer allocator.free(pems.cert_pem);
defer allocator.free(pems.key_pem);
const dir = try std.fmt.allocPrint(allocator, "{s}/ethp2p", .{self.options.database_path});
defer allocator.free(dir);
cert_path = try ethp2pWritePem(allocator, dir, "cert.pem", pems.cert_pem, null);
// Private key: owner-only (0o600), enforced even if key.pem
// already exists with looser perms. A readable key + the cert is
// enough to impersonate this node's ethp2p listener.
key_path = try ethp2pWritePem(allocator, dir, "key.pem", pems.key_pem, std.Io.File.Permissions.fromMode(0o600));
self.logger.info("ethp2p: generated per-node TLS cert at {s}", .{dir});
}
}
self.logger.info(
"ethp2p: config peer_id={s} listen={?s} static_peers={d} (libp2p port offset +{d})",
.{ self.options.node_key, listen_addr, static_peers.len, offset },
);
return .{
.local_peer_id = self.options.node_key,
.listen_addr = listen_addr,
.server_certificate_pem_path = cert_path,
.server_private_key_pem_path = key_path,
.static_peers = static_peers,
.server_name = ethp2pServerName(),
};
}
pub fn init(
self: *Self,
allocator: std.mem.Allocator,
options: *const NodeOptions,
) !void {
self.allocator = allocator;
self.options = options;
self.api_server_handle = null;
self.metrics_server_handle = null;
self.logger = options.logger_config.logger(.node);
// If path is specified load from it, otherwise use default settings
const chain_spec_owned = self.options.chain_spec != null;
const chain_spec = if (self.options.chain_spec) |path|
std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, allocator, .limited(1024 * 1024)) catch |err| {
self.logger.err("failed to load chain spec at '{s}': {any}", .{ path, err });
return err;
}
else
\\{"preset": "mainnet", "name": "devnet0", "fork_digest": "12345678"}
;
defer if (chain_spec_owned) allocator.free(chain_spec);
const json_options = json.ParseOptions{
.ignore_unknown_fields = true,
.allocate = .alloc_if_needed,
};
// `parseFromSlice` allocates string fields inside the `Parsed` arena.
// The slice headers it returns alias arena memory; `chain_config` later
// owns these fields and `ChainSpec.deinit(allocator)` calls
// `allocator.free(self.name)` / `allocator.free(self.fork_digest)`. We
// must move both fields out of the arena onto the top-level allocator
// before dropping the arena, otherwise shutdown panics with
// "Invalid free" once `chain.deinit -> config.deinit` runs.
const parsed = try json.parseFromSlice(ChainOptions, allocator, chain_spec, json_options);
defer parsed.deinit();
var chain_options = parsed.value;
chain_options.name = try allocator.dupe(u8, chain_options.name.?);
errdefer if (chain_options.name) |n| allocator.free(n);
chain_options.fork_digest = try allocator.dupe(u8, chain_options.fork_digest.?);
errdefer if (chain_options.fork_digest) |d| allocator.free(d);
chain_options.genesis_time = options.genesis_spec.genesis_time;
if (chain_spec_owned) {
if (chain_options.preset == null) {
self.logger.err("chain spec: 'preset' field is required", .{});
return error.InvalidChainSpec;
}
if (chain_options.name == null or chain_options.name.?.len == 0) {
self.logger.err("chain spec: 'name' field is required", .{});
return error.InvalidChainSpec;
}
if (chain_options.fork_digest == null or chain_options.fork_digest.?.len != 8) {
self.logger.err("chain spec: 'fork_digest' field must be 4 bytes (8 hex characters)", .{});
return error.InvalidChainSpec;
}
}
// Set validator pubkeys from genesis_spec (read from config.yaml via genesisConfigFromYAML)
chain_options.validator_attestation_pubkeys = options.genesis_spec.validator_attestation_pubkeys;
chain_options.validator_proposal_pubkeys = options.genesis_spec.validator_proposal_pubkeys;
// Apply attestation_committee_count if provided via CLI flag or config.yaml.
// ChainConfig.init falls back to 1 when this field is null, so we only override when set.
if (options.attestation_committee_count) |count| {
chain_options.attestation_committee_count = @intCast(count);
}
// Apply max_attestations_data if provided via config.yaml.
// ChainConfig.init falls back to 16 (spec default) when this field is null.
if (options.max_attestations_data) |max| {
chain_options.max_attestations_data = max;
}
// transfer ownership of the chain_options to ChainConfig
const chain_config = try ChainConfig.init(Chain.custom, chain_options);
// TODO we seem to be needing one loop because then the events added to loop are not being fired
// in the order to which they have been added even with the an appropriate delay added
// behavior of this further needs to be investigated but for now we will share the same loop
self.loop = try xev.Loop.init(.{});
// v2 wants strings (one listen multiaddr; comma-separated connect
// multiaddrs). The legacy ENR plumbing returns `[]Multiaddr`; we
// convert here and own the resulting strings on `Node` so v2
// (which stores slice references, not dupes) is safe across its
// lifetime.
const addresses = try self.constructMultiaddrs();
defer {
for (addresses.listen_addresses) |addr| addr.deinit();
allocator.free(addresses.listen_addresses);
for (addresses.connect_peers) |addr| addr.deinit();
allocator.free(addresses.connect_peers);
}
self.listen_addresses_str = if (addresses.listen_addresses.len > 0)
try addresses.listen_addresses[0].toString(allocator)
else
try allocator.dupe(u8, "");
errdefer allocator.free(self.listen_addresses_str);
self.connect_peers_str = try joinMultiaddrsCsv(allocator, addresses.connect_peers);
errdefer allocator.free(self.connect_peers_str);
self.network = try networks.EthLibp2p.init(allocator, &self.loop, .{
.networkId = options.network_id,
.fork_digest = chain_config.spec.fork_digest,
.listen_addresses = self.listen_addresses_str,
.connect_peers = self.connect_peers_str,
.node_registry = options.node_registry,
.host_identity_key_path = options.host_identity_key_path,
}, options.logger_config.logger(.network));
errdefer self.network.deinit();
self.clock = try Clock.init(allocator, chain_config.genesis.genesis_time, &self.loop, options.logger_config);
errdefer self.clock.deinit(allocator);
var db = try database.Db.openBackend(
allocator,
options.logger_config.logger(.database),
options.database_path,
options.db_backend,
);
errdefer db.deinit();
const anchorState: *types.BeamState = try allocator.create(types.BeamState);
errdefer allocator.destroy(anchorState);
self.anchor_state = anchorState;
errdefer self.anchor_state.deinit();
// load a valid local state available in db else genesis
var local_finalized_state: types.BeamState = undefined;
if (db.loadLatestFinalizedState(&local_finalized_state)) {
if (local_finalized_state.config.genesis_time != chain_config.genesis.genesis_time) {
self.logger.warn("database genesis time mismatch (db={d}, config={d}), wiping stale database", .{
local_finalized_state.config.genesis_time,
chain_config.genesis.genesis_time,
});
try wipeAndReopenDb(&db, allocator, options.database_path, options.logger_config, self.logger, options.db_backend, false);
self.logger.info("stale database wiped, starting fresh & generating genesis", .{});
local_finalized_state.deinit();
try self.anchor_state.genGenesisState(allocator, chain_config.genesis);
} else {
self.anchor_state.* = local_finalized_state;
}
} else |_| {
self.logger.info("no finalized state found in db, wiping database for a clean slate", .{});
// ignore_not_found=true: db dir may not exist yet on a fresh install
try wipeAndReopenDb(&db, allocator, options.database_path, options.logger_config, self.logger, options.db_backend, true);
self.logger.info("starting fresh & generating genesis", .{});
try self.anchor_state.genGenesisState(allocator, chain_config.genesis);
}
// check if a valid and more recent checkpoint finalized state is available
if (options.checkpoint_sync_url) |checkpoint_url| {
self.logger.info("checkpoint sync enabled, downloading state from: {s}", .{checkpoint_url});
// Try checkpoint sync, fall back to database/genesis on failure
if (downloadCheckpointState(allocator, checkpoint_url, self.logger)) |downloaded_state_const| {
var downloaded_state = downloaded_state_const;
// Verify state against genesis config
if (verifyCheckpointState(allocator, &downloaded_state, &chain_config.genesis, self.logger)) {
if (downloaded_state.slot > self.anchor_state.slot) {
self.logger.info("checkpoint sync completed successfully with a recent state at slot={d} as anchor", .{downloaded_state.slot});
self.anchor_state.deinit();
self.anchor_state.* = downloaded_state;
// Fetch the real anchor block from the checkpoint provider and store
// it in the DB so blocks_by_root can serve it with the correct
// hash_tree_root. Compute the finalized anchor: derive
// anchor_block_root + expected_state_root, then fetch + verify both
// root and state_root pairing before persisting.
//
// Fail closed: if any hash computation fails we skip the block fetch
// rather than passing null to downloadAndStoreCheckpointBlock and
// silently skipping the pairing check.
anchor_block_fetch: {
var anchor_state_root: types.Root = undefined;
zeam_utils.hashTreeRoot(types.BeamState, self.anchor_state.*, &anchor_state_root, allocator) catch |err| {
self.logger.warn("checkpoint block fetch: hashTreeRoot(BeamState) failed: {} — skipping", .{err});
break :anchor_block_fetch;
};
const hdr = self.anchor_state.genStateBlockHeader(allocator) catch |err| {
self.logger.warn("checkpoint block fetch: genStateBlockHeader failed: {} — skipping", .{err});
break :anchor_block_fetch;
};
var anchor_block_root: types.Root = undefined;
zeam_utils.hashTreeRoot(types.BeamBlockHeader, hdr, &anchor_block_root, allocator) catch |err| {
self.logger.warn("checkpoint block fetch: hashTreeRoot(BeamBlockHeader) failed: {} — skipping", .{err});
break :anchor_block_fetch;
};
downloadAndStoreCheckpointBlock(allocator, checkpoint_url, anchor_block_root, anchor_state_root, &db, self.logger);
}
} else {
self.logger.warn("skipping checkpoint sync downloaded stale/same state at slot={d}, falling back to database", .{downloaded_state.slot});
downloaded_state.deinit();
}
} else |verify_err| {
self.logger.warn("checkpoint state verification failed: {}, falling back to database/genesis", .{verify_err});
downloaded_state.deinit();
}
} else |download_err| {
self.logger.warn("checkpoint sync failed: {}, falling back to database/genesis", .{download_err});
}
}
const num_validators: usize = @intCast(chain_config.genesis.numValidators());
self.key_manager = key_manager_lib.KeyManager.init(allocator);
errdefer self.key_manager.deinit();
try self.loadValidatorKeypairs(num_validators);
const validator_ids = try options.getValidatorIndices(allocator);
errdefer allocator.free(validator_ids);
// Initialize metrics BEFORE beam_node so that metrics set during
// initialization (like lean_validators_count) are captured on real
// metrics instead of being discarded by noop metrics.
if (options.metrics_enable) {
try api.init(allocator);
zeam_metrics.metrics.lean_node_start_time_seconds.set(@intCast(zeam_utils.unixTimestampSeconds()));
}
const cpu_count = std.Thread.getCpuCount() catch 2;
const reserved_system_threads: usize = 4; // main, p2p, api server, metrics server
const desired_workers = @max(@as(usize, 1), cpu_count -| reserved_system_threads);
// Aggregators: XMSS recursive prove (rayon) is the per-slot bottleneck. Keep a
// small Zig pool for capped in-flight aggregate workers.
const worker_count = if (options.is_aggregator) blk: {
const aggregator_zig_workers = @max(@as(usize, 2), desired_workers / 4);
break :blk @min(@as(usize, ThreadPool.max_thread_count), aggregator_zig_workers);
} else blk: {
const zig_worker_budget = @max(@as(usize, 1), (desired_workers + 1) / 2);
break :blk @min(zig_worker_budget, @as(usize, ThreadPool.max_thread_count));
};
// Coordinate the Zig worker pool and the rayon pool used by the XMSS
// aggregate prover from the same post-system-thread budget so they do
// not independently claim every remaining CPU. Prefer the Zig pool for
// the extra worker on odd counts since aggregate verification enters
// rayon from Zig workers. Both pools still keep a minimum of one worker
// so tiny/cgroup-limited systems remain functional.
//
// Operators can override the rayon worker count with `--rayon-threads`.
// The automatic split is conservative — it deliberately leaves
// half of the post-system-thread budget to the Zig pool because
// verification and gossip work also enter rayon. On a CPU-rich
// aggregator that bottleneck is the produce path instead, so giving
// rayon more cores measurably shortens the per-pass build time.
//
// Must be called before setupXmssAggregation since rayon’s global
// pool is initialized lazily on first use.
const rayon_threads = if (options.rayon_threads) |override| blk: {
const requested = @max(@as(usize, 1), @as(usize, override));
// Cap explicit overrides to the post-system budget so hosts
// with `--rayon-threads 12` on 8 vCPUs do not oversubscribe XMSS
// prove and inflate worker p50.
const effective = @min(requested, desired_workers);
if (effective < requested) {
self.logger.warn(
"--rayon-threads {d} exceeds post-system budget {d}; using {d} rayon threads",
.{ requested, desired_workers, effective },
);
}
break :blk effective;
} else if (options.is_aggregator)
desired_workers
else
@max(@as(usize, 1), desired_workers -| worker_count);
// One outer aggregate tick at a time on aggregators. A tick may prove
// multiple justification-path att_data in parallel (bounded by
// --max-aggregations-per-tick), so Rayon gets the full post-system CPU
// budget while we avoid stacking multiple concurrent aggregate ticks
// on top of ThreadPool × Rayon work (#925).
const aggregate_max_inflight: u32 = if (options.is_aggregator) 1 else 4;
const rayon_source: []const u8 = if (options.rayon_threads != null)
" (--rayon-threads override)"
else if (options.is_aggregator)
" (aggregator auto-tune: full post-system budget)"
else
" (non-aggregator auto-split)";
// Operator-typo guard for --rayon-threads.
// Rayon tolerates over-subscription, but values like `--rayon-threads 160`
// on a 4-vCPU box silently degrade throughput. Warn (don't reject) so the
// operator notices in startup logs without blocking deliberate edge cases
// (e.g. fractional cgroup quotas where `getCpuCount` reports more CPUs
// than the container can actually use).
if (options.rayon_threads) |override| {
if (@as(usize, override) > cpu_count) {
self.logger.warn(
"--rayon-threads {d} exceeds detected cpu_count={d}; rayon over-subscription typically reduces throughput. Verify this is intentional.",
.{ override, cpu_count },
);
}
}
xmss.setRayonThreads(rayon_threads);
// Single XMSS aggregation setup for both prover and verifier paths
try xmss.setupXmssAggregation();
self.thread_pool = try ThreadPool.init(.{
.allocator = allocator,
.io = std.Io.Threaded.global_single_threaded.io(),
.thread_count = @intCast(worker_count),
});
errdefer self.thread_pool.deinit();
// Log the aggregator threshold on startup so operators can see
// exactly how `--min-aggregation-inputs` was resolved (default vs
// override). The threshold is enforced by the aggregator-side
// pre-filter in `pruneTrivialFromAggregateSnapshot`,
// not inside the core `computeAggregatedSignatures` FFI.
self.logger.info(
"aggregator threshold: min_aggregation_inputs={d}{s}",
.{
options.min_aggregation_inputs,
if (options.min_aggregation_inputs != types.default_min_aggregation_inputs)
" (override via --min-aggregation-inputs)"
else
"",
},
);
self.logger.info(
"aggregator cap: max_aggregations_per_tick={d}{s}",
.{
options.max_aggregations_per_tick,
if (options.max_aggregations_per_tick != types.default_max_aggregations_per_tick)
" (override via --max-aggregations-per-tick)"
else
"",
},
);
// Experimental ethp2p RS-broadcast config: compiled in only under
// `-Dethp2p=true`, enabled at runtime only when `ZEAM_ETHP2P` is truthy
// (env-var toggle — a CLI flag would trip zigcli's comptime branch
// quota). Off by default on both axes. Endpoints default to the node's
// own libp2p QUIC addresses shifted by `ZEAM_ETHP2P_PORT_OFFSET` (default
// +1) and are fully overridable via env; identity is the per-node
// `node_key`. The owned strings (listen_addr, static_peers) are consumed
// synchronously by the adapter's `start`, so they are freed once
// `beam_node.init` returns.
const ethp2p_cfg: ?networks.Ethp2pConfig = if (comptime networks.ethp2p.enabled)
(if (ethp2pRuntimeEnabled()) try self.buildEthp2pConfig(allocator) else null)
else
null;
defer if (ethp2p_cfg) |c| freeEthp2pConfig(allocator, c);
try self.beam_node.init(allocator, .{
.nodeId = @intCast(options.node_key_index),
.config = chain_config,
.anchorState = self.anchor_state,
.backend = self.network.getNetworkInterface(),
.clock = &self.clock,
.validator_ids = validator_ids,
.key_manager = &self.key_manager,
.db = db,
.logger_config = options.logger_config,
.node_registry = options.node_registry,
.is_aggregator = options.is_aggregator,
.aggregation_subnet_ids = options.aggregation_subnet_ids,
.thread_pool = self.thread_pool,
.chain_worker_enabled = options.chain_worker_enabled,
.ethp2p = ethp2p_cfg,
.min_aggregation_inputs = options.min_aggregation_inputs,
.max_aggregation_children = options.max_aggregation_children,
.max_aggregations_per_tick = options.max_aggregations_per_tick,
.aggregate_max_inflight = aggregate_max_inflight,
.type1_aggregation_deadline_pct = options.type1_aggregation_deadline_pct,
});
errdefer self.beam_node.deinit();
// Start API and metrics servers
// Note: api.init() was already called above before beam_node.init()
if (options.metrics_enable) {
// Validate that API and metrics ports are different
if (options.api_port == options.metrics_port) {
std.log.err("API port and metrics port cannot be the same (both set to {d})", .{options.api_port});
return error.PortConflict;
}
// Start metrics server (doesn't need chain reference)
self.metrics_server_handle = try metrics_server.startMetricsServer(
allocator,
options.metrics_port,
options.logger_config,
);
// Clean up metrics server if subsequent init operations fail
errdefer if (self.metrics_server_handle) |handle| handle.stop();
// Set validator status gauges on node start
zeam_metrics.metrics.lean_is_aggregator.set(if (options.is_aggregator) 1 else 0);
// Set committee count from config
const committee_count = chain_config.spec.attestation_committee_count;
zeam_metrics.metrics.lean_attestation_committee_count.set(committee_count);
// Set subnet for the first validator (if any)
if (validator_ids.len > 0) {
const first_validator_id: types.ValidatorIndex = @intCast(validator_ids[0]);
const subnet_id = types.computeSubnetId(first_validator_id, committee_count) catch 0;
zeam_metrics.metrics.lean_attestation_committee_subnet.set(subnet_id);
} else {
zeam_metrics.metrics.lean_attestation_committee_subnet.set(0);
}
// Start API server (pass chain pointer for chain-dependent endpoints)
self.api_server_handle = try api_server.startAPIServer(
allocator,
options.api_port,
options.logger_config,
self.beam_node.chain,
);
// Set node lifecycle metrics
zeam_metrics.metrics.lean_node_info.set(.{ .name = "zeam", .version = build_options.version }, 1) catch {};
}
self.logStartupThreadBudget(.{
.cpu_count = cpu_count,
.zig_worker_pool = worker_count,
.rayon = rayon_threads,
.aggregate_max_inflight = aggregate_max_inflight,
.chain_worker = if (options.chain_worker_enabled) 1 else 0,
.metrics_server = if (options.metrics_enable) 1 else 0,
.api_server = if (options.metrics_enable) 1 else 0,
.rayon_source = rayon_source,
});
self.logger = options.logger_config.logger(.node);
}
pub fn deinit(self: *Self) void {
if (self.slot_driver_watchdog) |*wd| {
wd.stop();
}
if (self.api_server_handle) |handle| {
handle.stop();
}
if (self.metrics_server_handle) |handle| {
handle.stop();
}
self.clock.deinit(self.allocator);
self.beam_node.deinit();
self.thread_pool.deinit();
self.allocator.free(self.listen_addresses_str);
self.allocator.free(self.connect_peers_str);
self.key_manager.deinit();
self.network.deinit();
self.enr.deinit();
self.db.deinit();
self.loop.deinit();
event_broadcaster.deinitGlobalBroadcaster();
self.anchor_state.deinit();