-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathnode.rs
More file actions
2108 lines (1965 loc) · 79 KB
/
Copy pathnode.rs
File metadata and controls
2108 lines (1965 loc) · 79 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
//! Tempo Zone Node configuration.
//!
//! This is a lightweight L2 node built on reth's node builder infrastructure.
//! It reuses Tempo's EVM, primitives, and pool, but with noop consensus/network/payload.
use crate::{
ZoneEngine,
replication::{
AttestationContext, BACKFILL_SERVE_QUEUE_CAPACITY, PeerTipRegistry, serve_backfill_requests,
},
role::{
EventSinks, LeaderSequencerDeps, RoleControllerContext, SharedRoleStatus,
canonical_recovery_height, route_backfill_requests, route_backfill_responses,
route_events_to_generations, run_role_controller,
},
rpc::{
NodeZoneDebugApi, OperatorWeb3Api, OperatorZoneApi, SequencerRpcContext,
ZoneApiServer as _, ZoneRpc, ZoneRpcApi, operator_zone_rpc_module, rpc_connection_config,
start_redacted_rpc,
},
};
use alloy_chains::Chain;
use alloy_consensus::BlockHeader as _;
use alloy_eips::BlockNumberOrTag;
use alloy_primitives::{Address, U256};
use alloy_provider::{DynProvider, Provider as _};
use alloy_signer_local::PrivateKeySigner;
use k256::SecretKey;
use reth_chainspec::EthChainSpec;
use reth_eth_wire_types::primitives::BasicNetworkPrimitives;
use reth_node_api::{
AddOnsContext, FullNodeComponents, FullNodeTypes, NodeAddOns, NodeTypes,
PayloadAttributesBuilder, PayloadTypes,
};
use reth_node_builder::{
BuilderContext, DebugNode, Node, NodeAdapter,
components::{
BasicPayloadServiceBuilder, ComponentsBuilder, ConsensusBuilder, ExecutorBuilder,
NoopNetworkBuilder, PoolBuilder, spawn_maintenance_tasks,
},
rpc::{
BasicEngineValidatorBuilder, EngineValidatorAddOn, EthApiBuilder, NoopEngineApiBuilder,
PayloadValidatorBuilder, RethRpcAddOns, RpcAddOns,
},
};
use reth_primitives_traits::SealedHeader;
use reth_provider::ChainSpecProvider;
use reth_rpc_api::Web3ApiServer as _;
use reth_rpc_builder::Identity;
use reth_rpc_eth_api::EthApiTypes;
use reth_storage_api::{
BlockNumReader, EmptyBodyStorage, HeaderProvider, StateProvider, StateProviderFactory,
};
use reth_tasks::TaskExecutor;
use reth_transaction_pool::{
Pool, PoolTransaction, TransactionValidationTaskExecutor, blobstore::InMemoryBlobStore,
error::InvalidPoolTransactionError,
};
use std::{
num::NonZeroU32,
sync::{Arc, OnceLock},
time::Duration,
};
use tempo_alloy::TempoNetwork;
use tempo_evm::{TempoInvalidTransaction, consensus::TempoConsensus};
use tempo_node::{
DEFAULT_AA_VALID_AFTER_MAX_SECS, engine::TempoEngineValidator, rpc::TempoEthApiBuilder,
};
use tempo_precompiles::tip20::TIP20Token;
use tempo_primitives::{
self as primitives, TempoHeader, TempoPrimitives, TempoTxEnvelope, TempoTxType,
};
use tempo_transaction_pool::{
AA2dPool, AA2dPoolConfig, TempoTransactionPool,
amm::AmmLiquidityCache,
ordering::TempoTipOrdering,
transaction::{TempoPoolTransactionError, TempoPooledTransaction},
validator::{DEFAULT_MAX_TEMPO_AUTHORIZATIONS, TempoTransactionValidator},
};
use tempo_zone_contracts::{ZONE_INBOX_ADDRESS, ZONE_OUTBOX_ADDRESS, ZonePortal};
use tokio::sync::mpsc::{Receiver, Sender};
use tracing::{debug, info, warn};
use zone_chainspec::ZoneChainSpec;
use zone_evm::ZoneEvmConfig;
use zone_l1::{
DepositQueue, EncryptionKeyRing, EncryptionKeyRotation, L1BlockTracker, L1Subscriber,
L1SubscriberConfig, LeaderTransition, LeadershipSink, TempoStateExt, encryption_key_address,
state::{EnabledTokenRegistry, L1StateCache, L1StateProvider, L1StateProviderConfig},
};
use zone_p2p::{
BackfillCommand, BackfillRequest, LeadershipSchedule, LeadershipState, P2pCommand, P2pConfig,
P2pNetworkId, P2pPeerId, ZoneManifest, spawn_p2p,
};
use zone_payload::{
DEFAULT_WITHDRAWAL_BATCH_INTERVAL_BLOCKS, WithdrawalRevealEncryptor, ZonePayloadAttributes,
ZonePayloadFactory, ZonePayloadTypes,
};
use zone_primitives::constants::{decode_l1_chain_id, zone_chain_id};
use zone_rpc::ZoneDebugApiRpcServer;
use zone_sequencer::{
AttestationStore, BatchAnchorConfig, ShadowProverConfig, WithdrawalBatchLimits,
ZoneSequencerConfig, attestation::AttestationDomain, spawn_zone_sequencer,
};
fn validate_zone_chain_id(parent_chain_id: u64, zone_id: u32, chain_id: u64) -> eyre::Result<()> {
let expected = zone_chain_id(parent_chain_id, zone_id)?;
eyre::ensure!(
chain_id == expected,
"chain ID mismatch: portal zone ID {zone_id} on parent chain {parent_chain_id} requires chain_id={expected}, but genesis has {chain_id}"
);
Ok(())
}
fn validate_configured_zone_id(
source: &str,
configured_zone_id: u32,
portal_zone_id: u32,
) -> eyre::Result<()> {
eyre::ensure!(
configured_zone_id == portal_zone_id,
"zone ID mismatch: {source} has {configured_zone_id}, but portal has {portal_zone_id}"
);
Ok(())
}
/// Network primitives for Zone Nodes
type ZoneNetworkPrimitives = BasicNetworkPrimitives<TempoPrimitives, TempoTxEnvelope>;
/// Sequencer-side sender reveal encryptor used while building
/// `finalizeWithdrawalBatch` system transactions.
///
/// The encrypted sender payload is hashed into withdrawal data, so ECIES must
/// not use fresh randomness here. This implementation derives reproducible
/// encryption material from the sequencer encryption key, zone id, reveal key,
/// sender, withdrawal transaction hash, and fallback nonce, which keeps identical
/// withdrawal batches byte-for-byte stable across sequencers.
struct SequencerWithdrawalRevealEncryptor {
encryption_key: Arc<SecretKey>,
zone_id: u32,
}
impl SequencerWithdrawalRevealEncryptor {
fn new(encryption_key: SecretKey, zone_id: u32) -> Self {
Self {
encryption_key: Arc::new(encryption_key),
zone_id,
}
}
}
impl std::fmt::Debug for SequencerWithdrawalRevealEncryptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SequencerWithdrawalRevealEncryptor")
.field("zone_id", &self.zone_id)
.finish_non_exhaustive()
}
}
impl WithdrawalRevealEncryptor for SequencerWithdrawalRevealEncryptor {
fn encrypt_sender(
&self,
reveal_to: &[u8],
sender: Address,
tx_hash: alloy_primitives::B256,
fallback_nonce: u64,
) -> Option<Vec<u8>> {
zone_precompiles::ecies::encrypt_authenticated_withdrawal_deterministic(
&self.encryption_key,
self.zone_id,
reveal_to,
sender,
tx_hash,
fallback_nonce,
)
}
}
/// Configuration for the sequencer background tasks
#[derive(Debug, Clone)]
pub struct ZoneSequencerAddOnsConfig {
/// Shared sequencer signer used for block production and encryption.
pub sequencer_signer: PrivateKeySigner,
/// Individual manifest-node signer used for L1 settlement transactions.
pub l1_transaction_signer: Option<PrivateKeySigner>,
/// Zone ID used by sequencer encryption.
pub zone_id: u32,
/// Fallback interval for reconciling the canonical Zone head.
pub zone_poll_interval: Duration,
/// EIP-2935 history and safety-margin limits used by the batch submitter.
pub batch_anchor_config: BatchAnchorConfig,
/// How often the withdrawal processor polls the L1 queue.
pub withdrawal_poll_interval: Duration,
/// Gas and concurrency limits for withdrawal processing transactions.
pub withdrawal_batch_limits: WithdrawalBatchLimits,
/// Run the SPF over finalized candidates in detached, observational mode.
pub enable_prover: bool,
/// Remote prover TCP address. When absent, execute the SPF in-process.
pub prover_address: Option<String>,
}
/// Configuration for the Zone redacted RPC server extension.
#[derive(Debug, Clone, Default)]
pub struct ZoneRedactedRpcConfig {
/// Port for RPC traffic.
pub redacted_rpc_port: u16,
/// Zone ID used by redacted RPC authentication.
pub zone_id: u32,
/// Max duration for redacted RPC auth.
pub max_auth_token_validity: Duration,
}
/// Tempo Zone node type configuration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ZoneNode {
/// Queue of L1 deposit messages to be included in the next zone block.
deposit_queue: DepositQueue,
/// Configuration for the L1 event subscriber (RPC endpoint, retries, etc.).
l1_config: L1SubscriberConfig,
/// Configuration for the L1 state provider (contract addresses, query parameters).
l1_state_provider_config: L1StateProviderConfig,
/// Shared L1 state cache (enabled tokens, zone metadata, etc.).
l1_state_cache: L1StateCache,
/// Shared registry of tokens enabled for this zone.
enabled_tokens: EnabledTokenRegistry,
/// L1 anchors independently observed and applied by the subscriber.
l1_block_tracker: L1BlockTracker,
/// Private encryption keys bound by finalized Portal rotation events.
encryption_keys: Option<EncryptionKeyRing>,
/// Address of the L1 deposit portal contract.
portal_address: Address,
/// Number of zone blocks between withdrawal batch boundaries.
withdrawal_batch_interval_blocks: u64,
/// Encrypts authenticated-withdrawal sender reveal data during payload construction.
withdrawal_reveal_encryptor: Option<Arc<dyn WithdrawalRevealEncryptor>>,
/// Redacted RPC config.
redacted_rpc_config: ZoneRedactedRpcConfig,
/// Optional sequencer config. When set, sequencer tasks are spawned.
sequencer_config: Option<ZoneSequencerAddOnsConfig>,
/// Optional static Zone P2P networking config.
p2p_config: Option<P2pConfig>,
/// Whether a consumer outside this builder drains the deposit queue.
external_deposit_consumer: bool,
}
impl ZoneNode {
// Creates a new ZoneNode
pub fn new(
l1_rpc_url: String,
portal_address: Address,
l1_fetch_concurrency: usize,
retry_connection_interval: Duration,
) -> Self {
let deposit_queue = DepositQueue::default();
let l1_state_cache = L1StateCache::new();
let enabled_tokens = EnabledTokenRegistry::default();
let l1_block_tracker = L1BlockTracker::default();
let l1_config = L1SubscriberConfig {
l1_rpc_url: l1_rpc_url.clone(),
portal_address,
l1_fetch_concurrency,
retry_connection_interval,
retain_portal_evidence: false,
};
let l1_state_provider_config = L1StateProviderConfig {
l1_rpc_url,
portal_address,
retry_connection_interval,
..Default::default()
};
Self {
deposit_queue,
l1_config,
l1_state_provider_config,
l1_state_cache,
enabled_tokens,
l1_block_tracker,
encryption_keys: None,
portal_address,
withdrawal_batch_interval_blocks: DEFAULT_WITHDRAWAL_BATCH_INTERVAL_BLOCKS,
withdrawal_reveal_encryptor: None,
redacted_rpc_config: ZoneRedactedRpcConfig::default(),
sequencer_config: None,
p2p_config: None,
external_deposit_consumer: false,
}
}
/// Set the redacted RPC configuration.
pub fn with_redacted_rpc(mut self, config: ZoneRedactedRpcConfig) -> Self {
self.redacted_rpc_config = config;
self
}
/// Retain authenticated Portal logs for an external observer.
pub fn with_portal_evidence_retention(mut self) -> Self {
self.l1_config.retain_portal_evidence = true;
self
}
/// Set the sequencer configuration. When set, batch submission and
/// withdrawal processing tasks are spawned during node launch.
pub fn with_sequencer(mut self, config: ZoneSequencerAddOnsConfig) -> Self {
let encryption_key = SecretKey::from(config.sequencer_signer.credential());
self.withdrawal_reveal_encryptor = Some(Arc::new(SequencerWithdrawalRevealEncryptor::new(
encryption_key.clone(),
config.zone_id,
)));
self = self.with_deposit_decryption_keys([encryption_key]);
self.sequencer_config = Some(config);
self
}
/// Add private keys that may be referenced by finalized encrypted deposits.
pub fn with_deposit_decryption_keys(
mut self,
keys: impl IntoIterator<Item = SecretKey>,
) -> Self {
let ring = self
.encryption_keys
.get_or_insert_with(EncryptionKeyRing::default);
for key in keys {
ring.add_candidate(key);
}
self
}
/// Declare that a consumer outside this builder drains [`Self::deposit_queue`].
///
/// Callers that drive their own [`crate::ZoneEngine`] against the shared queue — such as test
/// harnesses — must opt in so node startup knows the Zone chain can advance.
pub fn with_external_deposit_consumer(mut self) -> Self {
self.external_deposit_consumer = true;
self
}
/// Enable static Zone P2P networking for this node.
pub fn with_p2p(mut self, config: P2pConfig) -> Self {
self.p2p_config = Some(config);
self
}
/// Set the encryptor used for authenticated-withdrawal sender reveal data.
pub fn with_withdrawal_reveal_encryptor(
mut self,
encryptor: Arc<dyn WithdrawalRevealEncryptor>,
) -> Self {
self.withdrawal_reveal_encryptor = Some(encryptor);
self
}
/// Set the parent L1 chain ID, avoiding a startup RPC lookup.
pub fn with_l1_chain_id(mut self, chain_id: u64) -> Self {
self.l1_state_provider_config.chain_id = Some(chain_id);
self
}
/// Bound L1 state-provider retries for callers that must fail finitely on cache misses.
pub fn with_l1_state_provider_retry_limits(
mut self,
transport_retries: u32,
sync_attempts: NonZeroU32,
) -> Self {
self.l1_state_provider_config.max_retries = transport_retries;
self.l1_state_provider_config.max_sync_attempts = Some(sync_attempts);
self
}
/// Set the number of zone blocks between empty withdrawal batch
/// finalization.
pub fn with_withdrawal_batch_interval_blocks(mut self, interval_blocks: u64) -> Self {
self.withdrawal_batch_interval_blocks = interval_blocks.max(1);
self
}
/// Returns the current deposit queue
pub fn deposit_queue(&self) -> DepositQueue {
self.deposit_queue.clone()
}
/// Returns the current l1 state cache
pub fn l1_state_cache(&self) -> L1StateCache {
self.l1_state_cache.clone()
}
/// Returns the shared enabled-token registry.
pub fn enabled_tokens(&self) -> EnabledTokenRegistry {
self.enabled_tokens.clone()
}
/// Returns the L1 block observation tracker.
pub fn l1_block_tracker(&self) -> L1BlockTracker {
self.l1_block_tracker.clone()
}
/// Returns the shared encrypted-deposit key ring, when configured.
pub fn deposit_decryption_keys(&self) -> Option<EncryptionKeyRing> {
self.encryption_keys.clone()
}
}
impl NodeTypes for ZoneNode {
type Primitives = TempoPrimitives;
type ChainSpec = ZoneChainSpec;
type Storage = EmptyBodyStorage<TempoTxEnvelope, TempoHeader>;
type Payload = ZonePayloadTypes;
}
/// Addons for Tempo Zone nodes.
pub struct ZoneAddOns<N>
where
N: FullNodeComponents<Types = ZoneNode, Evm = ZoneEvmConfig>,
N::Pool: reth_transaction_pool::TransactionPool<Transaction = TempoPooledTransaction>,
{
inner: RpcAddOns<
N,
TempoEthApiBuilder<N>,
ZoneEngineValidatorBuilder,
NoopEngineApiBuilder,
BasicEngineValidatorBuilder<ZoneEngineValidatorBuilder>,
Identity,
>,
/// Queue of L1 deposit messages to be included in the next zone block.
deposit_queue: DepositQueue,
/// Configuration for the L1 event subscriber
l1_config: L1SubscriberConfig,
/// Shared L1 state cache updated by the subscriber.
l1_state_cache: L1StateCache,
/// Shared registry of tokens enabled for this zone.
enabled_tokens: EnabledTokenRegistry,
/// L1 anchors independently observed and applied by the subscriber.
l1_block_tracker: L1BlockTracker,
/// Private encryption keys bound by finalized Portal rotation events.
encryption_keys: Option<EncryptionKeyRing>,
/// ZonePortal address on L1.
portal_address: Address,
/// Redacted RPC configuration.
redacted_rpc_config: ZoneRedactedRpcConfig,
/// Sequencer configuration.
sequencer_config: Option<ZoneSequencerAddOnsConfig>,
/// Static Zone P2P networking configuration.
p2p_config: Option<P2pConfig>,
/// Whether a consumer outside this builder drains the deposit queue.
external_deposit_consumer: bool,
}
impl<N> std::fmt::Debug for ZoneAddOns<N>
where
N: FullNodeComponents<Types = ZoneNode, Evm = ZoneEvmConfig>,
N::Pool: reth_transaction_pool::TransactionPool<Transaction = TempoPooledTransaction>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZoneAddOns").finish_non_exhaustive()
}
}
impl<N> ZoneAddOns<NodeAdapter<N>>
where
N: FullNodeTypes<Types = ZoneNode>,
{
/// Creates a new ZoneAddOns instance.
pub fn new(
deposit_queue: DepositQueue,
l1_config: L1SubscriberConfig,
l1_state_cache: L1StateCache,
enabled_tokens: EnabledTokenRegistry,
l1_block_tracker: L1BlockTracker,
encryption_keys: Option<EncryptionKeyRing>,
portal_address: Address,
redacted_rpc_config: ZoneRedactedRpcConfig,
sequencer_config: Option<ZoneSequencerAddOnsConfig>,
p2p_config: Option<P2pConfig>,
external_deposit_consumer: bool,
) -> Self {
Self {
inner: RpcAddOns::new(
TempoEthApiBuilder::default(),
ZoneEngineValidatorBuilder,
NoopEngineApiBuilder::default(),
BasicEngineValidatorBuilder::default(),
Identity::default(),
Default::default(),
),
deposit_queue,
l1_config,
l1_state_cache,
enabled_tokens,
l1_block_tracker,
encryption_keys,
portal_address,
redacted_rpc_config,
sequencer_config,
p2p_config,
external_deposit_consumer,
}
}
}
/// P2P services that continue running after the network is initialized.
struct P2PRuntime {
sinks: EventSinks,
commands: Sender<P2pCommand>,
backfill_commands: Sender<BackfillCommand>,
attestation: AttestationContext,
schedule: LeadershipSchedule,
local_ed25519_public_key: P2pPeerId,
role_status: SharedRoleStatus,
peer_tips: PeerTipRegistry,
backfill_requests_rx: Receiver<BackfillRequest>,
}
impl<N> NodeAddOns<N> for ZoneAddOns<N>
where
N: FullNodeComponents<Types = ZoneNode, Evm = ZoneEvmConfig>,
N::Pool: reth_transaction_pool::TransactionPool<
Transaction = tempo_transaction_pool::transaction::TempoPooledTransaction,
>,
TempoEthApiBuilder<N>: EthApiBuilder<
N,
EthApi: reth_rpc_eth_api::helpers::FullEthApi<
Evm = ZoneEvmConfig,
Primitives = TempoPrimitives,
NetworkTypes = TempoNetwork,
>,
>,
{
type Handle = <RpcAddOns<
N,
TempoEthApiBuilder<N>,
ZoneEngineValidatorBuilder,
NoopEngineApiBuilder,
BasicEngineValidatorBuilder<ZoneEngineValidatorBuilder>,
Identity,
> as NodeAddOns<N>>::Handle;
async fn launch_add_ons(mut self, ctx: AddOnsContext<'_, N>) -> eyre::Result<Self::Handle> {
eyre::ensure!(
self.sequencer_config.is_some()
|| self.p2p_config.is_some()
|| self.external_deposit_consumer,
"no Zone chain advancement mechanism configured: enable a sequencer, configure P2P, or register an external deposit consumer"
);
let tempo_block_number = ctx.node.provider().latest()?.tempo_block_number()?;
let l1_provider = alloy_provider::ProviderBuilder::new_with_network::<TempoNetwork>()
.connect_with_config(
&self.l1_config.l1_rpc_url,
rpc_connection_config(self.l1_config.retry_connection_interval),
)
.await?
.erased();
let l1_chain_id = l1_provider.get_chain_id().await?;
let chain_spec = ctx.node.provider().chain_spec();
let chain_id = chain_spec.genesis().config.chain_id;
let genesis_zone_id = chain_spec.zone_id();
// The CLI rejects a zero portal address. Programmatic test/dev nodes use it as an
// explicit sentinel because they have no on-chain portal to bind against.
if self.portal_address.is_zero() {
warn!(
target: "reth::cli",
"Skipping portal-bound zone identity validation for a zero-address test/dev portal"
);
} else {
let portal_zone_id = ZonePortal::new(self.portal_address, &l1_provider)
.zoneId()
.call()
.await
.map_err(|err| {
eyre::eyre!(
"failed to read zone ID from portal {}: {err}",
self.portal_address
)
})?;
validate_configured_zone_id("genesis", genesis_zone_id, portal_zone_id)?;
validate_configured_zone_id(
"redacted RPC configuration",
self.redacted_rpc_config.zone_id,
portal_zone_id,
)?;
if let Some(config) = self.sequencer_config.as_ref() {
validate_configured_zone_id(
"sequencer configuration",
config.zone_id,
portal_zone_id,
)?;
}
if let Some(config) = self.p2p_config.as_ref() {
validate_configured_zone_id("P2P configuration", config.zone_id(), portal_zone_id)?;
}
validate_zone_chain_id(l1_chain_id, portal_zone_id, chain_id)?;
}
self.resolve_and_seed_tokens(&l1_provider, tempo_block_number)
.await?;
if let Some(keys) = self.encryption_keys.clone() {
self.resolve_and_seed_encryption_keys(&l1_provider, tempo_block_number, &keys)
.await?;
}
// Multi-sequencer mode: bootstrap the leadership schedule from the portal
// snapshot at the local Tempo anchor, and install the transition sink before
// the subscriber starts so no block is ever consumed ahead of its
// leadership transition.
let mut leadership_sink: Option<Arc<dyn LeadershipSink>> = None;
if let Some(p2p) = self.p2p_config.as_ref() {
let schedule = p2p.leadership();
let snapshot_anchor = tempo_block_number;
// Freeze the replay/live boundary before the subscriber starts. Historical identities
// may authenticate transitions that were already finalized when this process began,
// but must never authorize a leader selected later.
let finalized_replay_boundary = async {
l1_provider
.get_header_by_number(BlockNumberOrTag::Finalized)
.await
.map_err(|err| {
eyre::eyre!("failed reading finalized L1 replay boundary: {err}")
})?
.map(|header| header.number())
.ok_or_else(|| eyre::eyre!("L1 finalized block is not available"))
};
let (historical_replay_through, ()) = tokio::try_join!(
finalized_replay_boundary,
seed_leadership_schedule(
&l1_provider,
self.portal_address,
snapshot_anchor,
p2p.manifest(),
&schedule,
),
)?;
// Seed the applied anchor from the persisted checkpoint so it targets the leader
// of the next anchor from the very start (and not after the first post-restart block)
schedule.record_applied_anchor(snapshot_anchor);
install_manifest_forced_recovery(
ctx.node.provider(),
&l1_provider,
self.portal_address,
snapshot_anchor,
p2p.manifest(),
&schedule,
)
.await?;
leadership_sink = Some(Arc::new(ScheduleLeadershipSink {
schedule,
manifest: p2p.manifest().clone(),
historical_replay_through,
}));
}
let l1_subscriber = L1Subscriber::new(
self.l1_config.clone(),
ctx.node.provider().clone(),
self.deposit_queue.clone(),
self.enabled_tokens.clone(),
self.l1_state_cache.clone(),
self.l1_block_tracker.clone(),
leadership_sink,
self.encryption_keys.clone(),
);
let task_executor = ctx.node.task_executor().clone();
task_executor.spawn_critical_task(
"l1-block-subscriber",
Box::pin(async move {
l1_subscriber
.run()
.await
.unwrap_or_else(|error| panic!("{error}"));
}),
);
info!(target: "reth::cli", "L1 subscriber started with deposit enqueueing");
// Start the Commonware network and the long-lived event router
let sequencer_rpc_slot = Arc::new(std::sync::OnceLock::new());
let p2p_runtime = if let Some(config) = self.p2p_config.take() {
Some(
Self::start_p2p(
config,
&l1_provider,
l1_chain_id,
genesis_zone_id,
self.portal_address,
self.sequencer_config
.as_ref()
.map(|config| config.batch_anchor_config)
.unwrap_or_default(),
self.l1_config.l1_rpc_url.clone(),
self.l1_config.retry_connection_interval,
self.encryption_keys.clone().unwrap_or_default(),
&task_executor,
&sequencer_rpc_slot,
)
.await?,
)
} else {
if let Some(ref config) = self.sequencer_config {
// Legacy single-sequencer mode keeps the static engine.
let sequencer_addr = config.sequencer_signer.address();
self.spawn_zone_engine(&ctx, sequencer_addr)?;
}
None
};
let chain_id = ctx.node.provider().chain_spec().genesis().config.chain_id;
let max_response_size = ctx
.config
.rpc
.rpc_max_response_size
.get()
.saturating_mul(1024 * 1024) as usize;
let provider = ctx.node.provider().clone();
let zone_provider = provider.clone();
let pool = ctx.node.pool().clone();
let engine_handle = ctx.beacon_engine_handle.clone();
let payload_builder = ctx.node.payload_builder_handle().clone();
let operator_rpc_slot = sequencer_rpc_slot.clone();
let operator_rpc_provider = provider.clone();
let operator_zone_api = OperatorZoneApi::new(
self.redacted_rpc_config.zone_id,
chain_id,
self.portal_address,
l1_provider.clone(),
provider.clone(),
);
let portal_address = self.portal_address;
let evm_chain_spec = ctx.node.evm_config().chain_spec().clone();
let handle = self
.inner
.launch_add_ons_with(ctx, move |container| {
container.modules.add_or_replace_if_module_configured(
reth_rpc_builder::RethRpcModule::Web3,
OperatorWeb3Api.into_rpc(),
)?;
container
.modules
.merge_configured(operator_zone_api.into_rpc())?;
container.modules.merge_configured(
NodeZoneDebugApi::new(container.registry.eth_api().clone()).into_rpc(),
)?;
container.modules.merge_http(operator_zone_rpc_module(
genesis_zone_id,
portal_address,
operator_rpc_slot,
operator_rpc_provider,
)?)?;
Ok(())
})
.await?;
let prover_config = self
.sequencer_config
.as_ref()
.filter(|config| config.enable_prover)
.map(|config| ShadowProverConfig {
parent_chain_id: l1_chain_id,
zone_id: config.zone_id,
chain_spec: evm_chain_spec,
debug_api: Arc::new(NodeZoneDebugApi::new(handle.eth_handlers().api.clone())),
prover_address: config.prover_address.clone(),
});
Self::launch_redacted_rpc(
self.redacted_rpc_config,
&handle,
self.l1_config.l1_rpc_url.clone(),
self.l1_config.retry_connection_interval,
self.l1_config.portal_address,
self.enabled_tokens.clone(),
chain_id,
max_response_size,
)
.await?;
if let Some(P2PRuntime {
sinks,
commands,
backfill_commands,
attestation,
schedule,
local_ed25519_public_key,
role_status,
peer_tips,
backfill_requests_rx,
}) = p2p_runtime
{
// Backfill serving is role-neutral: every role serves the same canonical
// provider, so the server outlives role generations and a leadership handoff
// can never drop an accepted request.
task_executor.spawn_critical_task(
"zone-backfill-server",
serve_backfill_requests(
provider.clone(),
backfill_commands.clone(),
backfill_requests_rx,
),
);
let sequencer = match self.sequencer_config.take() {
Some(config) => Some(Self::build_leader_sequencer_deps(
config,
self.l1_config.l1_rpc_url.clone(),
self.l1_config.portal_address,
self.l1_config.retry_connection_interval,
attestation.store.clone(),
prover_config.clone(),
)?),
None => None,
};
let context = RoleControllerContext {
local_ed25519_public_key,
schedule,
provider: provider.clone(),
pool,
engine_handle,
payload_builder,
chain_spec: provider.chain_spec(),
deposit_queue: self.deposit_queue.clone(),
l1_block_tracker: self.l1_block_tracker.clone(),
// Follower-only nodes have no private keys and never construct an engine.
encryption_keys: self.encryption_keys.clone().unwrap_or_default(),
commands,
backfill_commands,
attestation,
portal_address: self.portal_address,
sequencer,
peer_tips,
status: role_status,
};
task_executor
.spawn_critical_task("zone-role-controller", run_role_controller(context, sinks));
// Flush unpersisted blocks on shutdown.
let engine_shutdown = handle.engine_shutdown.clone();
task_executor.spawn_critical_with_graceful_shutdown_signal(
"zone-engine-shutdown",
|shutdown| async move {
let _guard = shutdown.await;
info!(target: "reth::cli", "Shutdown signal received — flushing engine state");
if let Some(done) = engine_shutdown.shutdown() {
let _ = done.await;
}
},
);
} else if let Some(config) = self.sequencer_config.take() {
let sequencer_addr = config.sequencer_signer.address();
Self::launch_sequencer_tasks(
config,
&handle,
zone_provider,
&task_executor,
self.l1_config.l1_rpc_url,
self.l1_config.portal_address,
self.l1_config.retry_connection_interval,
sequencer_addr,
None,
prover_config,
)
.await?;
}
Ok(handle)
}
}
/// Applies finalized leadership transitions to the shared schedule, resolving the portal's
/// secp256k1 leader address to exactly one manifest Ed25519 peer (invariant I3).
#[derive(Debug)]
struct ScheduleLeadershipSink {
schedule: LeadershipSchedule,
manifest: Arc<ZoneManifest>,
/// Finalized L1 height captured before subscriber startup. Historical identities are valid
/// only while replaying transitions at or below this boundary.
historical_replay_through: u64,
}
impl LeadershipSink for ScheduleLeadershipSink {
fn apply_leader_transition(&self, transition: &LeaderTransition) -> eyre::Result<()> {
let replaying_history = transition.activation_tempo_block <= self.historical_replay_through;
let leader = if replaying_history {
self.manifest
.leader_ed25519_by_secp256k1_address(transition.new_leader)
} else {
self.manifest
.node_by_secp256k1_address(transition.new_leader)
.map(|node| node.ed25519_public_key())
}
.ok_or_else(|| {
let allowed = if replaying_history {
"active or historical"
} else {
"active"
};
eyre::eyre!(
"finalized portal leader {} (epoch {}) does not map to any {allowed} manifest identity",
transition.new_leader,
transition.epoch,
)
})?;
self.schedule.publish(LeadershipState::new(
transition.epoch,
leader.clone(),
transition.activation_tempo_block,
))?;
info!(
target: "reth::cli",
epoch = transition.epoch,
leader = %transition.new_leader,
peer = %leader,
activation_tempo_block = transition.activation_tempo_block,
"Observed finalized leadership transition"
);
Ok(())
}
}
/// Install the manifest's temporary runtime authority before any role-dependent task starts.
///
/// The selected block must remain in the persisted canonical chain. Its historical state restores
/// the original Tempo anchor and portal epoch, while the current portal snapshot distinguishes an
/// in-progress recovery from a completed directive left in the manifest after restart.
///
/// Canonical ancestry is intentionally a local restart check. Cross-node convergence still relies
/// on the operational invariant that every descendant was produced on the same chain by the
/// selected, non-equivocating recovery leader.
async fn install_manifest_forced_recovery<P>(
provider: &P,
l1_provider: &alloy_provider::DynProvider<TempoNetwork>,
portal_address: Address,
snapshot_anchor: u64,
manifest: &ZoneManifest,
schedule: &LeadershipSchedule,
) -> eyre::Result<()>
where
P: BlockNumReader + HeaderProvider<Header = TempoHeader> + StateProviderFactory,
{
let Some(recovery) = manifest.forced_recovery() else {
return Ok(());
};
let portal_leadership = schedule.latest().ok_or_else(|| {
eyre::eyre!(
"forced recovery requires a portal leadership snapshot at the local Tempo checkpoint"
)
})?;
let recovery_zone_height = canonical_recovery_height(provider, recovery.recovery_block_hash())?;
let recovery_anchor = provider
.history_by_block_number(recovery_zone_height)?
.tempo_block_number()?;
let recovery_start_tempo_block = recovery_anchor
.checked_add(1)
.ok_or_else(|| eyre::eyre!("forced recovery Tempo anchor overflow"))?;
let recovery_portal_epoch = if recovery_anchor == snapshot_anchor {
portal_leadership.epoch
} else {
ZonePortal::new(portal_address, l1_provider)
.leaderEpoch()
.block(alloy_rpc_types_eth::BlockId::number(recovery_anchor))
.call()
.await
.map_err(|err| {
eyre::eyre!(
"failed to read portal epoch at recovery Tempo block {recovery_anchor}: {err}"
)
})?
};
let recovery_epoch = recovery_portal_epoch
.checked_add(1)
.ok_or_else(|| eyre::eyre!("forced recovery epoch overflow"))?;
if portal_leadership.epoch >= recovery_epoch {
warn!(
target: "reth::cli",
leader = %recovery.leader(),
recovery_epoch,
recovery_zone_height,
recovery_zone_hash = %recovery.recovery_block_hash(),
snapshot_anchor,
portal_epoch = portal_leadership.epoch,
portal_activation_tempo_block = portal_leadership.activation_tempo_block,
"Skipping completed manifest forced recovery; remove the stale directive"
);
metrics::counter!("zone_forced_recovery_directives_total", "result" => "completed")
.increment(1);
return Ok(());
}
schedule.install_forced_recovery(
recovery_epoch,
recovery.leader().clone(),
recovery.recovery_block_hash(),
recovery_start_tempo_block,
)?;
info!(
target: "reth::cli",
leader = %recovery.leader(),
recovery_portal_epoch,
recovery_zone_height,
recovery_zone_hash = %recovery.recovery_block_hash(),
recovery_start_tempo_block,