-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathrpc.rs
More file actions
1759 lines (1583 loc) · 61.2 KB
/
Copy pathrpc.rs
File metadata and controls
1759 lines (1583 loc) · 61.2 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
//! [`ZoneRpcApi`] implementation backed by reth's EthApi.
//!
//! Re-exports the standalone `zone-rpc` crate so everything is accessible
//! via `zone_node::rpc::*`.
pub use zone_rpc::*;
use std::{
collections::{HashMap, HashSet},
sync::{Arc, Weak},
time::Duration,
};
use alloy_consensus::{BlockHeader, transaction::TxHashRef};
use alloy_eips::eip2935::{HISTORY_SERVE_WINDOW, HISTORY_STORAGE_ADDRESS};
use alloy_network::{ReceiptResponse, TransactionBuilder, TransactionResponse};
use alloy_primitives::{Address, B256, Bloom, Bytes, U64, U256, keccak256};
use alloy_provider::{DynProvider, Provider};
use alloy_rpc_types_eth::{
Block, BlockId, BlockNumberOrTag, BlockTransactions, FeeHistory, Filter, FilterChanges,
FilterId, TransactionRequest,
state::{EvmOverrides, StateOverride},
};
use alloy_sol_types::SolCall;
use eyre::WrapErr;
use futures::StreamExt;
use jsonrpsee::{RpcModule, core::RpcResult, proc_macros::rpc, types::ErrorObjectOwned};
use reth_evm::{ConfigureEvm as _, execute::Executor as _};
use reth_provider::{CanonStateSubscriptions, HeaderProvider};
use reth_revm::{db::State, witness::ExecutionWitnessRecord};
use reth_rpc::{EthFilter, eth::filter::EthFilterError};
use reth_rpc_api::Web3ApiServer;
use reth_rpc_builder::EthHandlers;
use reth_rpc_eth_api::{
EthApiTypes, EthFilterApiServer, RpcConvert,
helpers::{EthApiSpec, EthBlocks, EthCall, EthFees, EthState, EthTransactions, FullEthApi},
};
use reth_rpc_eth_types::{EthApiError, logs_utils};
use reth_storage_api::{BlockNumReader, StateProviderFactory};
use reth_trie_common::{ExecutionWitnessMode, HashedPostState};
use tempo_alloy::{
TempoNetwork,
provider::ext::TempoProviderExt as _,
rpc::{TempoCallBuilderExt as _, TempoHeaderResponse, TempoTransactionRequest},
};
use tempo_chainspec::spec::{TEMPO_T0_BASE_FEE, TEMPO_T1_BASE_FEE};
use tempo_contracts::precompiles::{
ACCOUNT_KEYCHAIN_ADDRESS,
account_keychain::IAccountKeychain::{self, KeyInfo, getKeyCall},
};
use tempo_primitives::{TempoPrimitives, TempoTxEnvelope};
use tokio::{
sync::Mutex,
time::{MissedTickBehavior, interval},
};
use zone_l1::{TempoStateExt as _, state::EnabledTokenRegistry};
use alloy_rpc_client::{ConnectionConfig, WebSocketConfig};
use tempo_zone_contracts::{ZONE_TOKEN_ADDRESS, ZonePortal};
use zone_evm::ZoneEvmConfig;
use zone_p2p::{LeadershipSchedule, PeerTip, ZoneManifest};
use zone_rpc::{
auth::AuthContext,
types::{
ActiveLeaderInfo, AuthorizationTokenInfoResponse, BoundDecryptionKey, BoxEyreFut, BoxFut,
DecryptionKeyCandidate, DecryptionKeyStatus, JsonRpcError, LocalSequencerInfo, PeerTipInfo,
SequencerInfoResponse, SequencerPeerInfo, SequencerProgress, SequencerReadiness,
SetLeaderResponse, TempoStorageRead as RpcTempoStorageRead, ZoneExecutionWitness,
ZoneInfoResponse, internal, raw_null, raw_zero, to_raw,
},
};
use crate::{replication::PeerTipRegistry, role::SharedRoleStatus};
/// Multi-sequencer handles for the sequencer RPC methods.
///
/// The RPC servers launch before the role controller, so the node installs this context
/// through an [`std::sync::OnceLock`] indirection once the leadership machinery exists.
#[derive(Debug)]
pub struct SequencerRpcContext {
/// Shared finalized leadership schedule.
pub schedule: LeadershipSchedule,
/// Live role and promotion-readiness snapshot from the role controller.
pub status: SharedRoleStatus,
/// Hash-carrying peer tip evidence.
pub(crate) peer_tips: PeerTipRegistry,
/// Validated static topology manifest.
pub manifest: Arc<ZoneManifest>,
/// Portal sequencer-set version validated against the manifest at startup.
pub pinned_sequencer_set_version: Option<u64>,
/// This node's individual secp256k1 address (the `setLeader` relayer identity).
///
/// `None` on an rpc-only member: it holds no individual key, so it cannot relay.
pub local_secp256k1_address: Option<Address>,
/// This node's Ed25519 public key.
pub local_ed25519_public_key: zone_p2p::P2pPeerId,
/// Wallet-backed L1 provider signing with the individual key, when this node holds one.
pub relayer: Option<DynProvider<TempoNetwork>>,
/// Publicly reportable view of locally loaded deposit-decryption keys.
pub encryption_keys: zone_l1::EncryptionKeyRing,
}
impl SequencerRpcContext {
/// Create the RPC context for a multi-sequencer node.
pub(crate) fn new(
schedule: LeadershipSchedule,
status: SharedRoleStatus,
peer_tips: PeerTipRegistry,
manifest: Arc<ZoneManifest>,
pinned_sequencer_set_version: Option<u64>,
local_secp256k1_address: Option<Address>,
local_ed25519_public_key: zone_p2p::P2pPeerId,
relayer: Option<DynProvider<TempoNetwork>>,
encryption_keys: zone_l1::EncryptionKeyRing,
) -> Self {
Self {
schedule,
status,
peer_tips,
manifest,
pinned_sequencer_set_version,
local_secp256k1_address,
local_ed25519_public_key,
relayer,
encryption_keys,
}
}
}
/// Public, authentication-independent Zone metadata methods.
#[rpc(server, namespace = "zone")]
pub(crate) trait ZoneApi {
/// Returns metadata for this Zone.
#[method(name = "getZoneInfo")]
async fn get_zone_info(&self) -> RpcResult<ZoneInfoResponse>;
/// Returns the encryption key active at the current Tempo L1 head.
#[method(name = "getEncryptionKey")]
async fn get_encryption_key(&self) -> RpcResult<ZonePortal::encryptionKeyAtBlockReturn>;
}
/// Public Zone API backed directly by the node and Tempo L1 providers.
#[derive(Clone)]
pub(crate) struct OperatorZoneApi<P> {
zone_id: u32,
chain_id: u64,
portal_address: Address,
l1_provider: DynProvider<TempoNetwork>,
zone_provider: P,
}
impl<P> OperatorZoneApi<P> {
pub(crate) const fn new(
zone_id: u32,
chain_id: u64,
portal_address: Address,
l1_provider: DynProvider<TempoNetwork>,
zone_provider: P,
) -> Self {
Self {
zone_id,
chain_id,
portal_address,
l1_provider,
zone_provider,
}
}
}
#[jsonrpsee::core::async_trait]
impl<P> ZoneApiServer for OperatorZoneApi<P>
where
P: StateProviderFactory + Clone + Send + Sync + 'static,
{
async fn get_zone_info(&self) -> RpcResult<ZoneInfoResponse> {
let tempo_block_number = self
.zone_provider
.latest()
.map_err(internal)
.and_then(|state| state.tempo_block_number().map_err(internal))
.map_err(operator_rpc_error)?;
zone_info(
self.zone_id,
self.chain_id,
self.portal_address,
tempo_block_number,
&self.l1_provider,
)
.await
.map_err(operator_rpc_error)
}
async fn get_encryption_key(&self) -> RpcResult<ZonePortal::encryptionKeyAtBlockReturn> {
encryption_key(self.portal_address, &self.l1_provider)
.await
.map_err(operator_rpc_error)
}
}
/// Build the unauthenticated Zone extension installed on the node's operator HTTP RPC.
pub(crate) fn operator_zone_rpc_module<P>(
zone_id: u32,
portal_address: Address,
sequencer: Arc<std::sync::OnceLock<SequencerRpcContext>>,
provider: P,
) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError>
where
P: BlockNumReader + HeaderProvider + StateProviderFactory + Clone + Send + Sync + 'static,
{
let mut module = RpcModule::new(());
let set_leader_sequencer = sequencer.clone();
module.register_async_method("zone_setLeader", move |params, _, _| {
let sequencer = set_leader_sequencer.clone();
async move {
let (target,) = params.parse::<(Address,)>()?;
set_leader(portal_address, sequencer.as_ref(), target)
.await
.map_err(operator_rpc_error)
}
})?;
module.register_async_method("zone_getSequencerInfo", move |_, _, _| {
let sequencer = sequencer.clone();
let provider = provider.clone();
async move {
get_sequencer_info(zone_id, portal_address, sequencer.as_ref(), &provider)
.map_err(operator_rpc_error)
}
})?;
Ok(module)
}
/// Operator Web3 API backed by the globally initialized Zone version metadata.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct OperatorWeb3Api;
#[jsonrpsee::core::async_trait]
impl Web3ApiServer for OperatorWeb3Api {
async fn client_version(&self) -> RpcResult<String> {
Ok(crate::version::client_version().to_owned())
}
fn sha3(&self, input: Bytes) -> RpcResult<B256> {
Ok(keccak256(input))
}
}
/// Zone-specific debug API.
#[derive(Clone)]
pub(crate) struct NodeZoneDebugApi<E> {
eth_api: E,
}
impl<E> NodeZoneDebugApi<E> {
pub(crate) const fn new(eth_api: E) -> Self {
Self { eth_api }
}
}
#[jsonrpsee::core::async_trait]
impl<E> ZoneDebugApi for NodeZoneDebugApi<E>
where
E: FullEthApi<Evm = ZoneEvmConfig, Primitives = TempoPrimitives>,
{
async fn zone_execution_witness(
&self,
block_id: BlockNumberOrTag,
) -> RpcResult<ZoneExecutionWitness> {
let _permit = self
.eth_api
.tracing_task_guard()
.clone()
.acquire_owned()
.await;
let block = self
.eth_api
.recovered_block(block_id.into())
.await
.map_err(|error| operator_rpc_error(internal(error)))?
.ok_or_else(|| operator_rpc_error(internal(format!("block {block_id} not found"))))?;
let block_number = block.header().number();
self.eth_api
.spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
let (evm_config, recorder) = eth_api.evm_config().with_l1_storage_recorder();
let block_executor = evm_config.executor(&mut db);
let mode = ExecutionWitnessMode::default();
let mut witness = None;
let _ = block_executor
.execute_with_state_closure(&block, |statedb: &State<_>| {
let mut additional_state = HashedPostState::default();
record_block_hash_storage_proofs(&mut additional_state, statedb);
witness = Some(
ExecutionWitnessRecord::new(statedb)
.with_additional_state(additional_state)
.into_execution_witness(
&statedb.database.database.0,
eth_api.provider(),
block_number,
mode,
),
);
})
.map_err(|error| EthApiError::Internal(error.into()))?;
let witness = witness
.expect("state closure is called after successful execution")
.map_err(EthApiError::from)?;
Ok(ZoneExecutionWitness {
execution_witness: witness,
tempo_reads: recorder
.take_reads()
.into_iter()
.map(|read| RpcTempoStorageRead {
account: read.account,
slot: read.slot,
})
.collect(),
})
})
.await
.map_err(|error| operator_rpc_error(internal(error)))
}
}
/// Add EIP-2935 history-contract storage paths for every BLOCKHASH value read during replay.
///
/// Reth records these reads in REVM's block-hash cache and normally proves them with ancestor
/// headers. Zones already commit the EIP-2935 history contract in state, so adding the matching
/// storage targets lets the SPF authenticate the same values against the parent state root.
fn record_block_hash_storage_proofs<DB>(additional_state: &mut HashedPostState, state: &State<DB>) {
let block_hashes = state.block_hashes.iter().collect::<Vec<_>>();
if block_hashes.is_empty() {
return;
}
let history_storage = additional_state
.storages
.entry(keccak256(HISTORY_STORAGE_ADDRESS))
.or_default();
for (number, hash) in block_hashes {
let slot = U256::from(number % HISTORY_SERVE_WINDOW as u64);
history_storage.storage.insert(
keccak256(slot.to_be_bytes::<32>()),
U256::from_be_bytes(hash.0),
);
}
}
fn operator_rpc_error(error: JsonRpcError) -> ErrorObjectOwned {
ErrorObjectOwned::owned(error.code as i32, error.message, error.data)
}
async fn zone_tokens(
portal_address: Address,
l1_provider: &DynProvider<TempoNetwork>,
) -> Result<Vec<Address>, JsonRpcError> {
if portal_address.is_zero() {
return Ok(vec![ZONE_TOKEN_ADDRESS]);
}
ZonePortal::new(portal_address, l1_provider)
.enabled_tokens()
.await
.map_err(internal)
}
async fn zone_sequencers(
portal_address: Address,
l1_provider: &DynProvider<TempoNetwork>,
) -> Result<Vec<Address>, JsonRpcError> {
ZonePortal::new(portal_address, l1_provider)
.sequencers()
.await
.map_err(internal)
}
/// Builds the Zone metadata shared by the operator and redacted RPC surfaces.
///
/// The caller supplies the local Zone's processed Tempo block number; the
/// remaining dynamic fields are read directly from the ZonePortal on Tempo L1.
async fn zone_info(
zone_id: u32,
chain_id: u64,
portal_address: Address,
tempo_block_number: u64,
l1_provider: &DynProvider<TempoNetwork>,
) -> Result<ZoneInfoResponse, JsonRpcError> {
let portal = ZonePortal::new(portal_address, l1_provider);
let (zone_tokens, sequencers, is_access_enforced, is_gateway_open) = tokio::try_join!(
zone_tokens(portal_address, l1_provider),
zone_sequencers(portal_address, l1_provider),
async {
if portal_address.is_zero() {
Ok(false)
} else {
portal.isAccessEnforced().call().await.map_err(internal)
}
},
async {
if portal_address.is_zero() {
Ok(true)
} else {
portal.isGatewayOpen().call().await.map_err(internal)
}
},
)?;
Ok(ZoneInfoResponse {
zone_id: U64::from(zone_id),
is_access_enforced,
is_gateway_open,
zone_tokens,
sequencers,
chain_id: U64::from(chain_id),
tempo_block_number: U64::from(tempo_block_number),
})
}
/// Reads the encryption key active at the current Tempo L1 head.
async fn encryption_key(
portal_address: Address,
l1_provider: &DynProvider<TempoNetwork>,
) -> Result<ZonePortal::encryptionKeyAtBlockReturn, JsonRpcError> {
let block_number = l1_provider.get_block_number().await.map_err(internal)?;
ZonePortal::new(portal_address, l1_provider)
.encryptionKeyAtBlock(block_number)
.block(BlockId::number(block_number))
.call()
.await
.map_err(internal)
}
fn get_sequencer_info<P>(
zone_id: u32,
portal_address: Address,
sequencer: &std::sync::OnceLock<SequencerRpcContext>,
provider: &P,
) -> Result<SequencerInfoResponse, JsonRpcError>
where
P: BlockNumReader + HeaderProvider + StateProviderFactory,
{
let Some(context) = sequencer.get() else {
// Single-sequencer (or not yet initialized) node: report the minimal view.
return Ok(SequencerInfoResponse {
mode: "single".to_owned(),
portal: portal_address,
manifest_zone_id: None,
manifest_sequencer_set_version: None,
manifest_membership_digest: None,
decryption_keys: None,
local: None,
active_leader: None,
local_tip: None,
peers: Vec::new(),
progress: None,
readiness: None,
});
};
let status = context.status.lock().expect("poisoned").clone();
let latest = context.schedule.latest();
let active_leader = latest.as_ref().map(|record| {
let node = context.manifest.node_by_ed25519_public_key(&record.leader);
ActiveLeaderInfo {
name: node.map(|node| node.name().to_owned()),
sequencer_address: node.and_then(|node| node.secp256k1_address()),
p2p_public_key: record.leader.to_string(),
epoch: U64::from(record.epoch),
activation_tempo_block: U64::from(record.activation_tempo_block),
}
});
let tips: HashMap<_, _> = context
.peer_tips
.snapshot()
.into_iter()
.map(|(peer, tip, _)| (peer, tip))
.collect();
let peers = context
.manifest
.nodes()
.iter()
.map(|node| SequencerPeerInfo {
name: node.name().to_owned(),
sequencer_address: node.secp256k1_address(),
rpc_only: node.is_rpc_only(),
is_local: node.ed25519_public_key() == &context.local_ed25519_public_key,
tip: tips.get(node.ed25519_public_key()).map(|tip| PeerTipInfo {
zone_height: U64::from(tip.zone_height),
zone_hash: tip.zone_hash,
tempo_block_number: U64::from(tip.tempo_block_number),
tempo_block_hash: tip.tempo_block_hash,
}),
})
.collect();
let local_tip = local_recovery_tip(provider)?;
let local_node = context
.manifest
.node_by_ed25519_public_key(&context.local_ed25519_public_key);
Ok(SequencerInfoResponse {
mode: "multi".to_owned(),
portal: portal_address,
manifest_zone_id: Some(U64::from(zone_id)),
manifest_sequencer_set_version: context.pinned_sequencer_set_version.map(U64::from),
manifest_membership_digest: Some(context.manifest.membership_digest()),
decryption_keys: Some({
let status = context.encryption_keys.public_status();
DecryptionKeyStatus {
candidates: status
.candidates
.into_iter()
.map(|key| DecryptionKeyCandidate {
x: key.x,
y_parity: key.y_parity,
})
.collect(),
bound: status
.bound
.into_iter()
.map(|key| BoundDecryptionKey {
key_index: key.key_index,
x: key.x,
y_parity: key.y_parity,
})
.collect(),
}
}),
local: Some(LocalSequencerInfo {
name: local_node
.map(|node| node.name().to_owned())
.unwrap_or_default(),
sequencer_address: context.local_secp256k1_address,
p2p_public_key: context.local_ed25519_public_key.to_string(),
role: status.role.to_owned(),
}),
active_leader,
local_tip: Some(PeerTipInfo {
zone_height: U64::from(local_tip.zone_height),
zone_hash: local_tip.zone_hash,
tempo_block_number: U64::from(local_tip.tempo_block_number),
tempo_block_hash: local_tip.tempo_block_hash,
}),
peers,
progress: Some(SequencerProgress {
zone_height: U64::from(local_tip.zone_height),
tempo_block_number: U64::from(local_tip.tempo_block_number),
latest_observed_leadership_epoch: context
.schedule
.latest_observed_epoch()
.map(U64::from),
locally_applied_leadership_epoch: context
.schedule
.locally_applied_epoch()
.map(U64::from),
pending_transitions: U64::from(context.schedule.pending_transitions() as u64),
}),
readiness: Some(SequencerReadiness {
ready_for_promotion: status.ready_for_promotion,
reasons: status.promotion_reasons,
}),
})
}
type RpcBlock = Block<alloy_rpc_types_eth::Transaction<TempoTxEnvelope>, TempoHeaderResponse>;
const FILTER_OWNER_PRUNE_INTERVAL: Duration = Duration::from_secs(60);
const MAX_WS_FRAME_AND_MESSAGE_SIZE: usize = 128 * 1024 * 1024;
fn filter_not_found_error() -> JsonRpcError {
JsonRpcError::invalid_params("filter not found")
}
fn map_eth_filter_error(err: EthFilterError) -> JsonRpcError {
match err {
EthFilterError::FilterNotFound(_) => filter_not_found_error(),
other => internal(other),
}
}
fn stale_filter_owner_ids(
owner_ids: impl IntoIterator<Item = FilterId>,
active_ids: &HashSet<FilterId>,
) -> Vec<FilterId> {
owner_ids
.into_iter()
.filter(|id| !active_ids.contains(id))
.collect()
}
async fn prune_filter_owners<Api: EthApiTypes + 'static>(
filter: &EthFilter<Api>,
owners: &Mutex<HashMap<FilterId, Address>>,
) {
let owner_ids = {
let owners = owners.lock().await;
owners.keys().cloned().collect::<Vec<_>>()
};
if owner_ids.is_empty() {
return;
}
let active_ids = filter
.active_filters()
.ids()
.await
.into_iter()
.collect::<HashSet<_>>();
let stale_ids = stale_filter_owner_ids(owner_ids, &active_ids);
if stale_ids.is_empty() {
return;
}
let mut owners = owners.lock().await;
for id in stale_ids {
owners.remove(&id);
}
}
/// [`ZoneRpcApi`] implementation backed by reth's [`EthHandlers`].
///
/// This is the privacy enforcement layer for the zone's JSON-RPC surface.
/// Only methods explicitly routed through [`ZoneRpcApi`] are reachable —
/// everything else is rejected by the dispatcher's typed method registry,
/// so this struct effectively acts as an **enforced allowlist**
/// of Ethereum JSON-RPC endpoints.
///
/// For every allowed endpoint it applies typed privacy checks *before*
/// serializing to JSON:
///
/// - **Block redaction** — zeroing `logsBloom` and clearing transaction
/// lists on the redacted RPC.
/// - **Sender-scoped access** — returning `null` for transactions and
/// receipts not owned by the authenticated caller.
/// - **`from`-enforcement** — `eth_call` / `eth_estimateGas` may only
/// simulate from the authenticated account (`-32004` on mismatch,
/// auto-set when omitted); state overrides are rejected (`-32602`).
/// - **Sender verification** — `eth_sendRawTransaction` checks that the
/// recovered transaction sender matches the authenticated account
/// (`-32003` on mismatch).
pub struct ZoneRpc<Api: EthApiTypes> {
eth: EthHandlers<Api>,
config: zone_rpc::RedactedRpcConfig,
enabled_tokens: EnabledTokenRegistry,
l1_provider: DynProvider<TempoNetwork>,
/// Maps filter IDs to the authenticated account that created them.
/// The reth filter registry remains the source of truth for filter liveness.
filter_owners: Arc<Mutex<HashMap<FilterId, Address>>>,
}
impl<Api: EthApiTypes + 'static> ZoneRpc<Api> {
/// Wrap reth's [`EthHandlers`] (api + filter + pubsub) and an L1 provider.
pub fn new(
eth: EthHandlers<Api>,
config: zone_rpc::RedactedRpcConfig,
enabled_tokens: EnabledTokenRegistry,
l1_provider: DynProvider<TempoNetwork>,
) -> Self {
let rpc = Self {
eth,
config,
enabled_tokens,
l1_provider,
filter_owners: Arc::new(Mutex::new(HashMap::new())),
};
rpc.spawn_filter_owner_pruner();
rpc
}
/// Returns a reference to the inner [`EthFilter`] handler.
pub fn filter(&self) -> &EthFilter<Api> {
&self.eth.filter
}
async fn filter_is_active(&self, id: &FilterId) -> bool {
self.filter().active_filters().contains(id).await
}
fn spawn_filter_owner_pruner(&self)
where
Api: Send + Sync + 'static,
{
let filter = self.filter().clone();
let owners: Weak<Mutex<HashMap<FilterId, Address>>> = Arc::downgrade(&self.filter_owners);
tokio::spawn(async move {
let mut prune_interval = interval(FILTER_OWNER_PRUNE_INTERVAL);
prune_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
prune_interval.tick().await;
let Some(owners) = owners.upgrade() else {
break;
};
prune_filter_owners(&filter, &owners).await;
}
});
}
/// Verify that the filter belongs to the authenticated caller.
///
/// Returns `Ok(())` if the caller owns the filter or is the sequencer.
/// Returns an error indistinguishable from "filter not found" to avoid
/// leaking filter existence to non-owners.
async fn ensure_filter_owner(
&self,
id: &FilterId,
auth: &AuthContext,
) -> Result<(), JsonRpcError> {
let owner_matches = {
let owners = self.filter_owners.lock().await;
matches!(owners.get(id), Some(owner) if *owner == auth.caller)
};
if !owner_matches {
return Err(filter_not_found_error());
}
if self.filter_is_active(id).await {
Ok(())
} else {
self.filter_owners.lock().await.remove(id);
Err(filter_not_found_error())
}
}
fn zone_tokens(&self) -> Vec<Address> {
// Preserve the default token when running without an L1 portal.
if self.config.zone_portal.is_zero() {
return vec![ZONE_TOKEN_ADDRESS];
}
self.enabled_tokens.read().iter().copied().collect()
}
fn enforce_authorized(
&self,
request: &mut TempoTransactionRequest,
auth: &AuthContext,
) -> Result<(), JsonRpcError> {
zone_rpc::policy::enforce_authorized(request, auth)
}
}
impl<Api> ZoneRpc<Api>
where
Api: FullEthApi + EthApiTypes<NetworkTypes = TempoNetwork> + Send + Sync + 'static,
{
fn block_by_id(&self, id: BlockId) -> BoxFut<'_> {
Box::pin(async move {
let block = EthBlocks::rpc_block(&self.eth.api, id, false)
.await
.map_err(internal)?;
let Some(mut block) = block else {
return Ok(raw_null());
};
redact_block(&mut block);
to_raw(&block)
})
}
}
impl<Api> zone_rpc::ZoneRpcApi for ZoneRpc<Api>
where
Api: FullEthApi + EthApiTypes<NetworkTypes = TempoNetwork> + Send + Sync + 'static,
{
fn get_keychain_key(&self, account: Address, key_id: Address) -> BoxEyreFut<'_, KeyInfo> {
Box::pin(async move {
let request = TempoTransactionRequest {
inner: TransactionRequest {
from: Some(account),
to: Some(ACCOUNT_KEYCHAIN_ADDRESS.into()),
input: getKeyCall {
account,
keyId: key_id,
}
.abi_encode()
.into(),
..Default::default()
},
..Default::default()
};
let output = EthCall::call(&self.eth.api, request, None, EvmOverrides::default())
.await
.wrap_err("AccountKeychain.getKey eth_call failed")?;
IAccountKeychain::getKeyCall::abi_decode_returns(output.as_ref()).map_err(Into::into)
})
}
fn block_number(&self) -> BoxFut<'_> {
Box::pin(async move {
let info = EthApiSpec::chain_info(&self.eth.api).map_err(internal)?;
to_raw(&U256::from(info.best_number))
})
}
fn chain_id(&self) -> BoxFut<'_> {
Box::pin(async move {
let chain_id = EthApiSpec::chain_id(&self.eth.api);
to_raw(&Some(chain_id))
})
}
fn net_version(&self) -> BoxFut<'_> {
Box::pin(async move {
let chain_id = EthApiSpec::chain_id(&self.eth.api);
to_raw(&chain_id.to_string())
})
}
fn client_version(&self) -> BoxFut<'_> {
Box::pin(async { to_raw(&crate::version::client_version()) })
}
fn syncing(&self) -> BoxFut<'_> {
Box::pin(async move {
let status = EthApiSpec::sync_status(&self.eth.api).map_err(internal)?;
to_raw(&status)
})
}
fn coinbase(&self) -> BoxFut<'_> {
Box::pin(async move {
let header = EthBlocks::rpc_block_header(&self.eth.api, BlockId::latest())
.await
.map_err(internal)?
.ok_or_else(|| JsonRpcError::internal("latest block not found"))?;
to_raw(&header.beneficiary())
})
}
fn gas_price(&self) -> BoxFut<'_> {
Box::pin(async move { to_raw(&U256::from(TEMPO_T1_BASE_FEE)) })
}
fn max_priority_fee_per_gas(&self) -> BoxFut<'_> {
Box::pin(async move { to_raw(&U256::ZERO) })
}
fn fee_history(
&self,
block_count: u64,
newest_block: BlockNumberOrTag,
reward_percentiles: Option<Vec<f64>>,
) -> BoxFut<'_> {
Box::pin(async move {
let mut history =
EthFees::fee_history(&self.eth.api, block_count, newest_block, reward_percentiles)
.await
.map_err(internal)?;
// Redact gas fields (like `gas_used_ratio`) that can be used to guess tx counts
redact_fee_history(&mut history);
to_raw(&history)
})
}
fn get_balance(
&self,
address: Address,
block: Option<BlockId>,
auth: AuthContext,
) -> BoxFut<'_> {
Box::pin(async move {
// Silent dummy: non-caller addresses get "0x0" to avoid leaking account existence.
if address != auth.caller {
return Ok(raw_zero());
}
let balance = EthState::balance(&self.eth.api, address, block)
.await
.map_err(internal)?;
to_raw(&balance)
})
}
fn get_transaction_count(
&self,
address: Address,
block: Option<BlockId>,
auth: AuthContext,
) -> BoxFut<'_> {
Box::pin(async move {
// Silent dummy: non-caller addresses get "0x0" to avoid leaking account existence.
if address != auth.caller {
return Ok(raw_zero());
}
let count = EthState::transaction_count(&self.eth.api, address, block)
.await
.map_err(internal)?;
to_raw(&count)
})
}
fn block_by_number(
&self,
number: BlockNumberOrTag,
_full: bool,
_auth: AuthContext,
) -> BoxFut<'_> {
self.block_by_id(number.into())
}
fn block_by_hash(&self, hash: B256, _full: bool, _auth: AuthContext) -> BoxFut<'_> {
self.block_by_id(hash.into())
}
fn transaction_by_hash(&self, hash: B256, auth: AuthContext) -> BoxFut<'_> {
Box::pin(async move {
let tx = EthTransactions::transaction_by_hash(&self.eth.api, hash)
.await
.map_err(internal)?
.map(|src| src.into_transaction(self.eth.api.converter()))
.transpose()
.map_err(internal)?;
let Some(mut tx) = tx else {
return Ok(raw_null());
};
if tx.from() != auth.caller {
return Ok(raw_null());
}
// transaction_index leaks how many txns were in this block, so redact
tx.transaction_index = Some(0);
to_raw(&tx)
})
}
fn transaction_receipt(&self, hash: B256, auth: AuthContext) -> BoxFut<'_> {
Box::pin(async move {
let receipt = EthTransactions::transaction_receipt(&self.eth.api, hash)
.await
.map_err(internal)?;
let Some(mut receipt) = receipt else {
return Ok(raw_null());
};
if receipt.from() != auth.caller {
return Ok(raw_null());
}
receipt = zone_rpc::filter::filter_receipt_logs(receipt);
to_raw(&receipt)
})
}
fn call(
&self,
mut request: TempoTransactionRequest,
block: Option<BlockId>,
state_override: Option<StateOverride>,
auth: AuthContext,
) -> BoxFut<'_> {
Box::pin(async move {
if state_override.is_some() {
return Err(JsonRpcError::invalid_params("state overrides not allowed"));
}
self.enforce_authorized(&mut request, &auth)?;
let result = EthCall::call(
&self.eth.api,
request,
block,
EvmOverrides::state(state_override),
)
.await
.map_err(internal)?;
to_raw(&result)
})
}
fn estimate_gas(
&self,
mut request: TempoTransactionRequest,
block: Option<BlockId>,
state_override: Option<StateOverride>,
auth: AuthContext,
) -> BoxFut<'_> {
Box::pin(async move {
if state_override.is_some() {
return Err(JsonRpcError::invalid_params("state overrides not allowed"));
}
self.enforce_authorized(&mut request, &auth)?;
let result = EthCall::estimate_gas_at(
&self.eth.api,
request,
block.unwrap_or_default(),