-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathnode.zig
More file actions
2165 lines (1929 loc) · 101 KB
/
Copy pathnode.zig
File metadata and controls
2165 lines (1929 loc) · 101 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);
}
};
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);
}
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
"",
},
);
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,
.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();
self.allocator.destroy(self.anchor_state);
}
pub fn run(self: *Node) !void {
// Start the Rust libp2p network before BeamNode:
// `BeamNode.run()` calls `gossip.subscribe(...)`, which enqueues
// `SwarmCommand::SubscribeGossip` on the per-network command channel.
// That channel only exists after `EthLibp2p.run()` returns from
// `wait_for_network_ready`. Reversing the order drops every subscribe
// with `error.GossipMeshSubscribeFailed`. The dev `beam`
// command already does network-first; this is the matching swap for
// the production node path.
//
// Peer + req-resp handlers are subscribed before the network starts so
// the one-shot peer-connect event and early STATUS requests are not
// lost to a handler-not-yet-registered race; only gossip mesh subscribe
// needs the running channel and stays inside `BeamNode.run()`.
try self.beam_node.subscribeNetworkEventHandlers();
try self.network.run();
try self.beam_node.run();
const ascii_art =
\\ ███████████████████████████████████████████████████████
\\ ██████████████ ████ ██████████
\\ ███████████ ████████████████ █████████████
\\ █████████ ████████████████████████ ███████████
\\ ██████ █████████████████████████████████ ███████
\\ █████ █████████████████████ █████████████ ██████
\\ ███ ██████████ █ █████ █████████ █████
\\ ███ ███████████ █████ █ █ █ ███████████████ ███
\\ ██ ██████████ ██ ██ ████ ███ ██ ██████████ ████
\\ ██ ██████████ ███ ████ █████████ ███
\\ ██ ███████████ █ ██████ ████ █████████ ███
\\ █ █████████ ████ █████ █████ █████████████ ███
\\ █ ██████████ █ ████ ██ █████ ███████ ███
\\ ██ ██████████ ████████ ██ █ ██████ ███
\\ ██ █████████ ███████ █ ██████████ ███
\\ ███ ██████████ ███ ███ █████████ █ ██
\\ ███ ████████████ ███ ██ ███ █ █ ███████ █████
\\ ███ ████████████ ████ █████ █████████ ██████
\\ █████ █████████ ███ █████ ████████ ███████
\\ ████████ ██████████████████████████ ██████████
\\ ████████ █ ████████████████████ ████████████
\\ █████ ██████ ██████████ ██████████████
\\ █████████████████ ██████████████████
\\ ███████████████████████████████████████████████████████
\\
\\ ███████╗███████╗ █████╗ ███╗ ███╗
\\ ╚══███╔╝██╔════╝██╔══██╗████╗ ████║
\\ ███╔╝ █████╗ ███████║██╔████╔██║
\\ ███╔╝ ██╔══╝ ██╔══██║██║╚██╔╝██║
\\ ███████╗███████╗██║ ██║██║ ╚═╝ ██║
\\ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝
\\
\\ A blazing fast lean consensus client
;
var encoded_txt_buf: [1000]u8 = undefined;
const encoded_txt = try self.enr.encodeToTxt(&encoded_txt_buf);
const quic_port = try self.enr.getQUIC();
// Use logger.info instead of std.debug.print
self.logger.info("\n{s}", .{ascii_art});
self.logger.info("════════════════════════════════════════════════════════", .{});
self.logger.info(" 🚀 Zeam Lean Node Started Successfully!", .{});
self.logger.info("════════════════════════════════════════════════════════", .{});
self.logger.info(" Node ID: {d}", .{self.options.node_key_index});
self.logger.info(" Listening on QUIC port: {?d}", .{quic_port});
self.logger.info(" ENR: {s}", .{encoded_txt});
self.logger.info("────────────────────────────────────────────────────────", .{});
// Spawn the slot-driver stall watchdog so multi-second
// libxev stalls surface in the log + metrics even if the main
// loop is stuck inside one completion or syscall. Failure to
// spawn is non-fatal — log and continue without it.
//
// The stall callback flips an atomic flag on `BeamNode` that the
// next libxev tick observes and acts on, forcing a peer status
// refresh outside the normal 8-slot cadence. This bootstraps
// catch-up as soon as the slot driver resumes.
self.slot_driver_watchdog = SlotDriverWatchdog.init(
&self.clock,
self.options.logger_config.logger(.clock),
.{
.on_stall = .{
.ptr = &self.beam_node,
.onStall = BeamNode.onSlotDriverStall,
},
},
);
if (self.slot_driver_watchdog) |*wd| {
wd.start() catch |err| {
self.logger.warn("failed to start slot-driver watchdog: {any}", .{err});
self.slot_driver_watchdog = null;
};
}
try self.clock.run();
}
fn constructMultiaddrs(self: *Self) !struct { listen_addresses: []const Multiaddr, connect_peers: []const Multiaddr } {
if (std.mem.eql(u8, self.options.validator_config, "genesis_bootnode")) {
try ENR.decodeTxtInto(&self.enr, self.options.bootnodes[self.options.node_key_index]);
} else {
// Parse validator config to get ENR fields
const validator_config_filepath = try std.mem.concat(self.allocator, u8, &[_][]const u8{
self.options.validator_config,
"/validator-config.yaml",
});
defer self.allocator.free(validator_config_filepath);
var parsed_validator_config = try utils_lib.loadFromYAMLFile(self.allocator, validator_config_filepath);
defer parsed_validator_config.deinit(self.allocator);
// Get ENR fields from validator config
var enr_fields = try getEnrFieldsFromValidatorConfig(self.allocator, self.options.node_key, parsed_validator_config);
defer enr_fields.deinit(self.allocator);
// Construct ENR from fields and private key
self.enr = try constructENRFromFields(
self.allocator,
self.options.local_priv_key,
enr_fields,
self.options.is_aggregator,
);
}
// Overriding the IP to 0.0.0.0 to listen on all interfaces
try self.enr.kvs.put("ip", "\x00\x00\x00\x00");
var node_multiaddrs = try self.enr.multiaddrP2PQUIC(self.allocator);
defer node_multiaddrs.deinit(self.allocator);
// move the ownership to the `EthLibp2p`, will be freed in its deinit
const listen_addresses = try node_multiaddrs.toOwnedSlice(self.allocator);
errdefer {
for (listen_addresses) |addr| addr.deinit();
self.allocator.free(listen_addresses);
}
var connect_peer_list: std.ArrayList(Multiaddr) = .empty;
defer connect_peer_list.deinit(self.allocator);
for (self.options.bootnodes, 0..) |n, i| {
// don't exclude any entry from nodes.yaml if this is not a genesis bootnode
if (i != self.options.node_key_index or !std.mem.eql(u8, self.options.validator_config, "genesis_bootnode")) {
var n_enr: ENR = undefined;
try ENR.decodeTxtInto(&n_enr, n);
var peer_multiaddr_list = try n_enr.multiaddrP2PQUIC(self.allocator);
defer peer_multiaddr_list.deinit(self.allocator);
const peer_multiaddrs = try peer_multiaddr_list.toOwnedSlice(self.allocator);
defer self.allocator.free(peer_multiaddrs);
try connect_peer_list.appendSlice(self.allocator, peer_multiaddrs);
}
}
// move the ownership to the `EthLibp2p`, will be freed in its deinit
const connect_peers = try connect_peer_list.toOwnedSlice(self.allocator);
errdefer {
for (connect_peers) |addr| addr.deinit();
self.allocator.free(connect_peers);
}
return .{ .listen_addresses = listen_addresses, .connect_peers = connect_peers };
}
fn loadValidatorKeypairs(
self: *Self,
num_validators: usize,
) !void {
if (self.options.validator_assignments.len == 0) {
return error.NoValidatorAssignments;
}
const hash_sig_key_dir = self.options.hash_sig_key_dir;
// First pass: group assignments by validator index, routing by filename.
// If the filename contains "attester" it goes to att_base; "proposer" to prop_base.
// A filename with neither is rejected with error.InvalidPrivkeyFileFormat.
// Slices point into validator_assignments memory which outlives this function.
const FileSlots = struct {
att_base: ?[]const u8 = null,
prop_base: ?[]const u8 = null,
};
var file_map = std.AutoHashMap(usize, FileSlots).init(self.allocator);
defer file_map.deinit();
for (self.options.validator_assignments) |assignment| {
if (assignment.index >= num_validators) {
return error.HashSigValidatorIndexOutOfRange;
}
const privkey_file = assignment.privkey_file;
if (!std.mem.endsWith(u8, privkey_file, "_sk.ssz")) {
return error.InvalidPrivkeyFileFormat;
}
const base = privkey_file[0 .. privkey_file.len - 7]; // Remove "_sk.ssz"
const slots = try file_map.getOrPutValue(assignment.index, .{});
if (std.mem.indexOf(u8, privkey_file, "attester") != null) {
slots.value_ptr.att_base = base;
} else if (std.mem.indexOf(u8, privkey_file, "proposer") != null) {
slots.value_ptr.prop_base = base;
} else {
// Filename must contain "attester" or "proposer" to unambiguously
// assign the key to a role. A file with neither is an error.
return error.InvalidPrivkeyFileFormat;
}
}
// Second pass: load each keypair from disk and register with the key manager.
// If only one role's file was provided, fall back to using it for both roles.
var map_it = file_map.iterator();
while (map_it.next()) |entry| {
const index = entry.key_ptr.*;
const slots = entry.value_ptr.*;
const att_base = slots.att_base orelse slots.prop_base orelse return error.HashSigSecretKeyMissing;
const prop_base = slots.prop_base orelse slots.att_base orelse return error.HashSigSecretKeyMissing;
const att_sk = try std.fmt.allocPrint(self.allocator, "{s}/{s}_sk.ssz", .{ hash_sig_key_dir, att_base });
defer self.allocator.free(att_sk);
const att_pk = try std.fmt.allocPrint(self.allocator, "{s}/{s}_pk.ssz", .{ hash_sig_key_dir, att_base });
defer self.allocator.free(att_pk);
var att_keypair = key_manager_lib.loadKeypairFromFiles(self.allocator, att_sk, att_pk) catch |err| switch (err) {
error.SecretKeyFileNotFound => return error.HashSigSecretKeyMissing,
error.PublicKeyFileNotFound => return error.HashSigPublicKeyMissing,
else => return err,
};
errdefer att_keypair.deinit();
const prop_sk = try std.fmt.allocPrint(self.allocator, "{s}/{s}_sk.ssz", .{ hash_sig_key_dir, prop_base });
defer self.allocator.free(prop_sk);
const prop_pk = try std.fmt.allocPrint(self.allocator, "{s}/{s}_pk.ssz", .{ hash_sig_key_dir, prop_base });
defer self.allocator.free(prop_pk);
var prop_keypair = key_manager_lib.loadKeypairFromFiles(self.allocator, prop_sk, prop_pk) catch |err| switch (err) {
error.SecretKeyFileNotFound => return error.HashSigSecretKeyMissing,
error.PublicKeyFileNotFound => return error.HashSigPublicKeyMissing,
else => return err,
};
errdefer prop_keypair.deinit();
const validator_keys = key_manager_lib.ValidatorKeys{
.attestation_keypair = att_keypair,
.proposal_keypair = prop_keypair,
};
try self.key_manager.addKeypair(index, validator_keys);
}
}
};
/// Reads ATTESTATION_COMMITTEE_COUNT from a parsed config.yaml Yaml document.
/// Returns null if the field is absent or cannot be parsed.
/// Comma-separated multiaddr string for `EthLibp2pParams.connect_peers`.
/// Returns an allocator-owned slice (empty string for the no-bootnodes case).