-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
lib.rs
1792 lines (1606 loc) · 60.1 KB
/
lib.rs
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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
issue_tracker_base_url = "https://github.com/paradigmxzy/reth/issues/"
)]
#![warn(missing_docs, unreachable_pub)]
#![deny(unused_must_use, rust_2018_idioms)]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
))]
//! Configure reth RPC
//!
//! This crate contains several builder and config types that allow to configure the selection of
//! [RethRpcModule] specific to transports (ws, http, ipc).
//!
//! The [RpcModuleBuilder] is the main entrypoint for configuring all reth modules. It takes
//! instances of components required to start the servers, such as provider impls, network and
//! transaction pool. [RpcModuleBuilder::build] returns a [TransportRpcModules] which contains the
//! transport specific config (what APIs are available via this transport).
//!
//! The [RpcServerConfig] is used to configure the [RpcServer] type which contains all transport
//! implementations (http server, ws server, ipc server). [RpcServer::start] requires the
//! [TransportRpcModules] so it can start the servers with the configured modules.
//!
//! # Examples
//!
//! Configure only an http server with a selection of [RethRpcModule]s
//!
//! ```
//! use reth_network_api::{NetworkInfo, Peers};
//! use reth_provider::{BlockReaderIdExt, ChainSpecProvider, CanonStateSubscriptions, StateProviderFactory, EvmEnvProvider};
//! use reth_rpc_builder::{RethRpcModule, RpcModuleBuilder, RpcServerConfig, ServerBuilder, TransportRpcModuleConfig};
//! use reth_tasks::TokioTaskExecutor;
//! use reth_transaction_pool::TransactionPool;
//! pub async fn launch<Provider, Pool, Network, Events>(provider: Provider, pool: Pool, network: Network, events: Events)
//! where
//! Provider: BlockReaderIdExt + ChainSpecProvider + StateProviderFactory + EvmEnvProvider + Clone + Unpin + 'static,
//! Pool: TransactionPool + Clone + 'static,
//! Network: NetworkInfo + Peers + Clone + 'static,
//! Events: CanonStateSubscriptions + Clone + 'static,
//! {
//! // configure the rpc module per transport
//! let transports = TransportRpcModuleConfig::default().with_http(vec![
//! RethRpcModule::Admin,
//! RethRpcModule::Debug,
//! RethRpcModule::Eth,
//! RethRpcModule::Web3,
//! ]);
//! let transport_modules = RpcModuleBuilder::new(provider, pool, network, TokioTaskExecutor::default(), events).build(transports);
//! let handle = RpcServerConfig::default()
//! .with_http(ServerBuilder::default())
//! .start(transport_modules)
//! .await
//! .unwrap();
//! }
//! ```
//!
//! Configure a http and ws server with a separate auth server that handles the `engine_` API
//!
//!
//! ```
//! use tokio::try_join;
//! use reth_network_api::{NetworkInfo, Peers};
//! use reth_provider::{BlockReaderIdExt, ChainSpecProvider, CanonStateSubscriptions, StateProviderFactory, EvmEnvProvider};
//! use reth_rpc::JwtSecret;
//! use reth_rpc_builder::{RethRpcModule, RpcModuleBuilder, RpcServerConfig, TransportRpcModuleConfig};
//! use reth_tasks::TokioTaskExecutor;
//! use reth_transaction_pool::TransactionPool;
//! use reth_rpc_api::EngineApiServer;
//! use reth_rpc_builder::auth::AuthServerConfig;
//! pub async fn launch<Provider, Pool, Network, Events, EngineApi>(provider: Provider, pool: Pool, network: Network, events: Events, engine_api: EngineApi)
//! where
//! Provider: BlockReaderIdExt + ChainSpecProvider + StateProviderFactory + EvmEnvProvider + Clone + Unpin + 'static,
//! Pool: TransactionPool + Clone + 'static,
//! Network: NetworkInfo + Peers + Clone + 'static,
//! Events: CanonStateSubscriptions + Clone + 'static,
//! EngineApi: EngineApiServer
//! {
//! // configure the rpc module per transport
//! let transports = TransportRpcModuleConfig::default().with_http(vec![
//! RethRpcModule::Admin,
//! RethRpcModule::Debug,
//! RethRpcModule::Eth,
//! RethRpcModule::Web3,
//! ]);
//! let builder = RpcModuleBuilder::new(provider, pool, network, TokioTaskExecutor::default(), events);
//!
//! // configure the server modules
//! let (modules, auth_module) = builder.build_with_auth_server(transports, engine_api);
//!
//! // start the servers
//! let auth_config = AuthServerConfig::builder(JwtSecret::random()).build();
//! let config = RpcServerConfig::default();
//!
//! let (_rpc_handle, _auth_handle) = try_join!(
//! modules.start_server(config),
//! auth_module.start_server(auth_config),
//! ).unwrap();
//!
//! }
//! ```
use crate::{auth::AuthRpcModule, error::WsHttpSamePortError};
use constants::*;
use error::{RpcError, ServerKind};
use jsonrpsee::{
server::{IdProvider, Server, ServerHandle},
Methods, RpcModule,
};
use reth_ipc::server::IpcServer;
use reth_network_api::{NetworkInfo, Peers};
use reth_provider::{
BlockReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider, EvmEnvProvider,
StateProviderFactory,
};
use reth_rpc::{
eth::{
cache::{cache_new_blocks_task, EthStateCache},
gas_oracle::GasPriceOracle,
},
AdminApi, DebugApi, EngineEthApi, EthApi, EthFilter, EthPubSub, EthSubscriptionIdProvider,
NetApi, RPCApi, TraceApi, TracingCallGuard, TxPoolApi, Web3Api,
};
use reth_rpc_api::{servers::*, EngineApiServer};
use reth_tasks::{TaskSpawner, TokioTaskExecutor};
use reth_transaction_pool::TransactionPool;
use serde::{Deserialize, Serialize, Serializer};
use std::{
collections::{HashMap, HashSet},
fmt,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
str::FromStr,
};
use strum::{AsRefStr, EnumString, EnumVariantNames, ParseError, VariantNames};
use tower::layer::util::{Identity, Stack};
use tower_http::cors::CorsLayer;
use tracing::{instrument, trace};
/// Auth server utilities.
pub mod auth;
/// Cors utilities.
mod cors;
/// Rpc error utilities.
pub mod error;
/// Eth utils
mod eth;
/// Common RPC constants.
pub mod constants;
// re-export for convenience
pub use crate::eth::{EthConfig, EthHandlers};
pub use jsonrpsee::server::ServerBuilder;
pub use reth_ipc::server::{Builder as IpcServerBuilder, Endpoint};
use reth_network_api::noop::NoopNetwork;
use reth_transaction_pool::noop::NoopTransactionPool;
/// Convenience function for starting a server in one step.
pub async fn launch<Provider, Pool, Network, Tasks, Events>(
provider: Provider,
pool: Pool,
network: Network,
module_config: impl Into<TransportRpcModuleConfig>,
server_config: impl Into<RpcServerConfig>,
executor: Tasks,
events: Events,
) -> Result<RpcServerHandle, RpcError>
where
Provider: BlockReaderIdExt
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
{
let module_config = module_config.into();
let server_config = server_config.into();
RpcModuleBuilder::new(provider, pool, network, executor, events)
.build(module_config)
.start_server(server_config)
.await
}
/// A builder type to configure the RPC module: See [RpcModule]
///
/// This is the main entrypoint and the easiest way to configure an RPC server.
#[derive(Debug, Clone)]
pub struct RpcModuleBuilder<Provider, Pool, Network, Tasks, Events> {
/// The Provider type to when creating all rpc handlers
provider: Provider,
/// The Pool type to when creating all rpc handlers
pool: Pool,
/// The Network type to when creating all rpc handlers
network: Network,
/// How additional tasks are spawned, for example in the eth pubsub namespace
executor: Tasks,
/// Provides access to chain events, such as new blocks, required by pubsub.
events: Events,
}
// === impl RpcBuilder ===
impl<Provider, Pool, Network, Tasks, Events>
RpcModuleBuilder<Provider, Pool, Network, Tasks, Events>
{
/// Create a new instance of the builder
pub fn new(
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
) -> Self {
Self { provider, pool, network, executor, events }
}
/// Configure the provider instance.
pub fn with_provider<P>(self, provider: P) -> RpcModuleBuilder<P, Pool, Network, Tasks, Events>
where
P: BlockReader + StateProviderFactory + EvmEnvProvider + 'static,
{
let Self { pool, network, executor, events, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events }
}
/// Configure the transaction pool instance.
pub fn with_pool<P>(self, pool: P) -> RpcModuleBuilder<Provider, P, Network, Tasks, Events>
where
P: TransactionPool + 'static,
{
let Self { provider, network, executor, events, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events }
}
/// Configure a [NoopTransactionPool] instance.
///
/// Caution: This will configure a pool API that does abosultely nothing.
/// This is only intended for allow easier setup of namespaces that depend on the [EthApi] which
/// requires a [TransactionPool] implementation.
pub fn with_noop_pool(
self,
) -> RpcModuleBuilder<Provider, NoopTransactionPool, Network, Tasks, Events> {
let Self { provider, executor, events, network, .. } = self;
RpcModuleBuilder {
provider,
executor,
events,
network,
pool: NoopTransactionPool::default(),
}
}
/// Configure the network instance.
pub fn with_network<N>(self, network: N) -> RpcModuleBuilder<Provider, Pool, N, Tasks, Events>
where
N: NetworkInfo + Peers + 'static,
{
let Self { provider, pool, executor, events, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events }
}
/// Configure a [NoopNetwork] instance.
///
/// Caution: This will configure a network API that does abosultely nothing.
/// This is only intended for allow easier setup of namespaces that depend on the [EthApi] which
/// requires a [NetworkInfo] implementation.
pub fn with_noop_network(self) -> RpcModuleBuilder<Provider, Pool, NoopNetwork, Tasks, Events> {
let Self { provider, pool, executor, events, .. } = self;
RpcModuleBuilder { provider, pool, executor, events, network: NoopNetwork::default() }
}
/// Configure the task executor to use for additional tasks.
pub fn with_executor<T>(
self,
executor: T,
) -> RpcModuleBuilder<Provider, Pool, Network, T, Events>
where
T: TaskSpawner + 'static,
{
let Self { pool, network, provider, events, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events }
}
/// Configure [TokioTaskExecutor] as the task executor to use for additional tasks.
///
/// This will spawn additional tasks directly via `tokio::task::spawn`, See
/// [TokioTaskExecutor].
pub fn with_tokio_executor(
self,
) -> RpcModuleBuilder<Provider, Pool, Network, TokioTaskExecutor, Events> {
let Self { pool, network, provider, events, .. } = self;
RpcModuleBuilder { provider, network, pool, events, executor: TokioTaskExecutor::default() }
}
/// Configure the event subscriber instance
pub fn with_events<E>(self, events: E) -> RpcModuleBuilder<Provider, Pool, Network, Tasks, E>
where
E: CanonStateSubscriptions + 'static,
{
let Self { provider, pool, executor, network, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events }
}
}
impl<Provider, Pool, Network, Tasks, Events>
RpcModuleBuilder<Provider, Pool, Network, Tasks, Events>
where
Provider: BlockReaderIdExt
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
{
/// Configures all [RpcModule]s specific to the given [TransportRpcModuleConfig] which can be
/// used to start the transport server(s).
///
/// This behaves exactly as [RpcModuleBuilder::build] for the [TransportRpcModules], but also
/// configures the auth (engine api) server, which exposes a subset of the `eth_` namespace.
pub fn build_with_auth_server<EngineApi>(
self,
module_config: TransportRpcModuleConfig,
engine: EngineApi,
) -> (TransportRpcModules<()>, AuthRpcModule)
where
EngineApi: EngineApiServer,
{
let mut modules = TransportRpcModules::default();
let Self { provider, pool, network, executor, events } = self;
let TransportRpcModuleConfig { http, ws, ipc, config } = module_config.clone();
let mut registry = RethModuleRegistry::new(
provider,
pool,
network,
executor,
events,
config.unwrap_or_default(),
);
modules.config = module_config;
modules.http = registry.maybe_module(http.as_ref());
modules.ws = registry.maybe_module(ws.as_ref());
modules.ipc = registry.maybe_module(ipc.as_ref());
let auth_module = registry.create_auth_module(engine);
(modules, auth_module)
}
/// Configures all [RpcModule]s specific to the given [TransportRpcModuleConfig] which can be
/// used to start the transport server(s).
///
/// See also [RpcServer::start]
pub fn build(self, module_config: TransportRpcModuleConfig) -> TransportRpcModules<()> {
let mut modules = TransportRpcModules::default();
let Self { provider, pool, network, executor, events } = self;
if !module_config.is_empty() {
let TransportRpcModuleConfig { http, ws, ipc, config } = module_config.clone();
let mut registry = RethModuleRegistry::new(
provider,
pool,
network,
executor,
events,
config.unwrap_or_default(),
);
modules.config = module_config;
modules.http = registry.maybe_module(http.as_ref());
modules.ws = registry.maybe_module(ws.as_ref());
modules.ipc = registry.maybe_module(ipc.as_ref());
}
modules
}
}
impl Default for RpcModuleBuilder<(), (), (), (), ()> {
fn default() -> Self {
RpcModuleBuilder::new((), (), (), (), ())
}
}
/// Bundles settings for modules
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct RpcModuleConfig {
/// `eth` namespace settings
eth: EthConfig,
}
// === impl RpcModuleConfig ===
impl RpcModuleConfig {
/// Convenience method to create a new [RpcModuleConfigBuilder]
pub fn builder() -> RpcModuleConfigBuilder {
RpcModuleConfigBuilder::default()
}
/// Returns a new RPC module config given the eth namespace config
pub fn new(eth: EthConfig) -> Self {
Self { eth }
}
}
/// Configures [RpcModuleConfig]
#[derive(Default)]
pub struct RpcModuleConfigBuilder {
eth: Option<EthConfig>,
}
// === impl RpcModuleConfigBuilder ===
impl RpcModuleConfigBuilder {
/// Configures a custom eth namespace config
pub fn eth(mut self, eth: EthConfig) -> Self {
self.eth = Some(eth);
self
}
/// Consumes the type and creates the [RpcModuleConfig]
pub fn build(self) -> RpcModuleConfig {
let RpcModuleConfigBuilder { eth } = self;
RpcModuleConfig { eth: eth.unwrap_or_default() }
}
}
/// Describes the modules that should be installed.
///
/// # Example
///
/// Create a [RpcModuleSelection] from a selection.
///
/// ```
/// use reth_rpc_builder::{RethRpcModule, RpcModuleSelection};
/// let config: RpcModuleSelection = vec![RethRpcModule::Eth].into();
/// ```
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub enum RpcModuleSelection {
/// Use _all_ available modules.
All,
/// The default modules `eth`, `net`, `web3`
#[default]
Standard,
/// Only use the configured modules.
Selection(Vec<RethRpcModule>),
}
// === impl RpcModuleSelection ===
impl RpcModuleSelection {
/// The standard modules to instantiate by default `eth`, `net`, `web3`
pub const STANDARD_MODULES: [RethRpcModule; 3] =
[RethRpcModule::Eth, RethRpcModule::Net, RethRpcModule::Web3];
/// Returns a selection of [RethRpcModule] with all [RethRpcModule::VARIANTS].
pub fn all_modules() -> Vec<RethRpcModule> {
RpcModuleSelection::try_from_selection(RethRpcModule::VARIANTS.iter().copied())
.expect("valid selection")
.into_selection()
}
/// Returns the [RpcModuleSelection::STANDARD_MODULES] as a selection.
pub fn standard_modules() -> Vec<RethRpcModule> {
RpcModuleSelection::try_from_selection(RpcModuleSelection::STANDARD_MODULES.iter().copied())
.expect("valid selection")
.into_selection()
}
/// All modules that are available by default on IPC.
///
/// By default all modules are available on IPC.
pub fn default_ipc_modules() -> Vec<RethRpcModule> {
Self::all_modules()
}
/// Creates a new [RpcModuleSelection::Selection] from the given items.
///
/// # Example
///
/// Create a selection from the [RethRpcModule] string identifiers
///
/// ```
/// use reth_rpc_builder::{RethRpcModule, RpcModuleSelection};
/// let selection = vec!["eth", "admin"];
/// let config = RpcModuleSelection::try_from_selection(selection).unwrap();
/// assert_eq!(config, RpcModuleSelection::Selection(vec![RethRpcModule::Eth, RethRpcModule::Admin]));
/// ```
pub fn try_from_selection<I, T>(selection: I) -> Result<Self, T::Error>
where
I: IntoIterator<Item = T>,
T: TryInto<RethRpcModule>,
{
let selection =
selection.into_iter().map(TryInto::try_into).collect::<Result<Vec<_>, _>>()?;
Ok(RpcModuleSelection::Selection(selection))
}
/// Returns true if no selection is configured
pub fn is_empty(&self) -> bool {
match self {
RpcModuleSelection::Selection(sel) => sel.is_empty(),
_ => false,
}
}
/// Creates a new [RpcModule] based on the configured reth modules.
///
/// Note: This will always create new instance of the module handlers and is therefor only
/// recommended for launching standalone transports. If multiple transports need to be
/// configured it's recommended to use the [RpcModuleBuilder].
pub fn standalone_module<Provider, Pool, Network, Tasks, Events>(
&self,
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
config: RpcModuleConfig,
) -> RpcModule<()>
where
Provider: BlockReaderIdExt
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
{
let mut registry =
RethModuleRegistry::new(provider, pool, network, executor, events, config);
registry.module_for(self)
}
/// Returns an iterator over all configured [RethRpcModule]
pub fn iter_selection(&self) -> Box<dyn Iterator<Item = RethRpcModule> + '_> {
match self {
RpcModuleSelection::All => Box::new(Self::all_modules().into_iter()),
RpcModuleSelection::Standard => Box::new(Self::STANDARD_MODULES.iter().copied()),
RpcModuleSelection::Selection(s) => Box::new(s.iter().copied()),
}
}
/// Returns the list of configured [RethRpcModule]
pub fn into_selection(self) -> Vec<RethRpcModule> {
match self {
RpcModuleSelection::All => Self::all_modules(),
RpcModuleSelection::Selection(s) => s,
RpcModuleSelection::Standard => Self::STANDARD_MODULES.to_vec(),
}
}
/// Returns true if both selections are identical.
fn are_identical(http: Option<&RpcModuleSelection>, ws: Option<&RpcModuleSelection>) -> bool {
match (http, ws) {
(Some(http), Some(ws)) => {
let http = http.clone().iter_selection().collect::<HashSet<_>>();
let ws = ws.clone().iter_selection().collect::<HashSet<_>>();
http == ws
}
(Some(http), None) => http.is_empty(),
(None, Some(ws)) => ws.is_empty(),
_ => true,
}
}
}
impl<I, T> From<I> for RpcModuleSelection
where
I: IntoIterator<Item = T>,
T: Into<RethRpcModule>,
{
fn from(value: I) -> Self {
RpcModuleSelection::Selection(value.into_iter().map(Into::into).collect())
}
}
impl FromStr for RpcModuleSelection {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut modules = s.split(',').peekable();
let first = modules.peek().copied().ok_or(ParseError::VariantNotFound)?;
match first {
"all" | "All" => Ok(RpcModuleSelection::All),
_ => RpcModuleSelection::try_from_selection(modules),
}
}
}
impl fmt::Display for RpcModuleSelection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[{}]",
self.iter_selection().map(|s| s.to_string()).collect::<Vec<_>>().join(", ")
)
}
}
/// Represents RPC modules that are supported by reth
#[derive(
Debug, Clone, Copy, Eq, PartialEq, Hash, AsRefStr, EnumVariantNames, EnumString, Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "kebab-case")]
pub enum RethRpcModule {
/// `admin_` module
Admin,
/// `debug_` module
Debug,
/// `eth_` module
Eth,
/// `net_` module
Net,
/// `trace_` module
Trace,
/// `txpool_` module
Txpool,
/// `web3_` module
Web3,
/// `rpc_` module
Rpc,
}
// === impl RethRpcModule ===
impl RethRpcModule {
/// Returns all variants of the enum
pub const fn all_variants() -> &'static [&'static str] {
Self::VARIANTS
}
}
impl fmt::Display for RethRpcModule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_ref())
}
}
impl Serialize for RethRpcModule {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_str(self.as_ref())
}
}
/// A Helper type the holds instances of the configured modules.
pub struct RethModuleRegistry<Provider, Pool, Network, Tasks, Events> {
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
/// Additional settings for handlers.
config: RpcModuleConfig,
/// Holds a clone of all the eth namespace handlers
eth: Option<EthHandlers<Provider, Pool, Network, Events>>,
/// to put trace calls behind semaphore
tracing_call_guard: TracingCallGuard,
/// Contains the [Methods] of a module
modules: HashMap<RethRpcModule, Methods>,
}
// === impl RethModuleRegistry ===
impl<Provider, Pool, Network, Tasks, Events>
RethModuleRegistry<Provider, Pool, Network, Tasks, Events>
{
/// Creates a new, empty instance.
pub fn new(
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
config: RpcModuleConfig,
) -> Self {
Self {
provider,
pool,
network,
eth: None,
executor,
modules: Default::default(),
tracing_call_guard: TracingCallGuard::new(config.eth.max_tracing_requests),
config,
events,
}
}
/// Returns all installed methods
pub fn methods(&self) -> Vec<Methods> {
self.modules.values().cloned().collect()
}
/// Returns a merged RpcModule
pub fn module(&self) -> RpcModule<()> {
let mut module = RpcModule::new(());
for methods in self.modules.values().cloned() {
module.merge(methods).expect("No conflicts");
}
module
}
}
impl<Provider, Pool, Network, Tasks, Events>
RethModuleRegistry<Provider, Pool, Network, Tasks, Events>
where
Network: NetworkInfo + Peers + Clone + 'static,
{
/// Register Admin Namespace
pub fn register_admin(&mut self) -> &mut Self {
self.modules
.insert(RethRpcModule::Admin, AdminApi::new(self.network.clone()).into_rpc().into());
self
}
/// Register Web3 Namespace
pub fn register_web3(&mut self) -> &mut Self {
self.modules
.insert(RethRpcModule::Web3, Web3Api::new(self.network.clone()).into_rpc().into());
self
}
}
impl<Provider, Pool, Network, Tasks, Events>
RethModuleRegistry<Provider, Pool, Network, Tasks, Events>
where
Provider: BlockReaderIdExt
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
{
/// Register Eth Namespace
pub fn register_eth(&mut self) -> &mut Self {
let eth_api = self.eth_api();
self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into());
self
}
/// Register Debug Namespace
pub fn register_debug(&mut self) -> &mut Self {
let eth_api = self.eth_api();
self.modules.insert(
RethRpcModule::Debug,
DebugApi::new(
self.provider.clone(),
eth_api,
Box::new(self.executor.clone()),
self.tracing_call_guard.clone(),
)
.into_rpc()
.into(),
);
self
}
/// Register Trace Namespace
pub fn register_trace(&mut self) -> &mut Self {
let eth = self.eth_handlers();
self.modules.insert(
RethRpcModule::Trace,
TraceApi::new(
self.provider.clone(),
eth.api.clone(),
eth.cache,
Box::new(self.executor.clone()),
self.tracing_call_guard.clone(),
)
.into_rpc()
.into(),
);
self
}
/// Configures the auth module that includes the
/// * `engine_` namespace
/// * `api_` namespace
///
/// Note: This does _not_ register the `engine_` in this registry.
pub fn create_auth_module<EngineApi>(&mut self, engine_api: EngineApi) -> AuthRpcModule
where
EngineApi: EngineApiServer,
{
let eth_handlers = self.eth_handlers();
let mut module = RpcModule::new(());
module.merge(engine_api.into_rpc()).expect("No conflicting methods");
// also merge a subset of `eth_` handlers
let engine_eth = EngineEthApi::new(eth_handlers.api.clone(), eth_handlers.filter);
module.merge(engine_eth.into_rpc()).expect("No conflicting methods");
AuthRpcModule { inner: module }
}
/// Register Net Namespace
pub fn register_net(&mut self) -> &mut Self {
let eth_api = self.eth_api();
self.modules.insert(
RethRpcModule::Net,
NetApi::new(self.network.clone(), eth_api).into_rpc().into(),
);
self
}
/// Helper function to create a [RpcModule] if it's not `None`
fn maybe_module(&mut self, config: Option<&RpcModuleSelection>) -> Option<RpcModule<()>> {
let config = config?;
let module = self.module_for(config);
Some(module)
}
/// Populates a new [RpcModule] based on the selected [RethRpcModule]s in the given
/// [RpcModuleSelection]
pub fn module_for(&mut self, config: &RpcModuleSelection) -> RpcModule<()> {
let mut module = RpcModule::new(());
let all_methods = self.reth_methods(config.iter_selection());
for methods in all_methods {
module.merge(methods).expect("No conflicts");
}
module
}
/// Returns the [Methods] for the given [RethRpcModule]
///
/// If this is the first time the namespace is requested, a new instance of API implementation
/// will be created.
pub fn reth_methods(
&mut self,
namespaces: impl Iterator<Item = RethRpcModule>,
) -> Vec<Methods> {
let EthHandlers { api: eth_api, cache: eth_cache, filter: eth_filter, pubsub: eth_pubsub } =
self.with_eth(|eth| eth.clone());
// Create a copy, so we can list out all the methods for rpc_ api
let namespaces: Vec<_> = namespaces.collect();
namespaces
.iter()
.copied()
.map(|namespace| {
self.modules
.entry(namespace)
.or_insert_with(|| match namespace {
RethRpcModule::Admin => {
AdminApi::new(self.network.clone()).into_rpc().into()
}
RethRpcModule::Debug => DebugApi::new(
self.provider.clone(),
eth_api.clone(),
Box::new(self.executor.clone()),
self.tracing_call_guard.clone(),
)
.into_rpc()
.into(),
RethRpcModule::Eth => {
// merge all eth handlers
let mut module = eth_api.clone().into_rpc();
module.merge(eth_filter.clone().into_rpc()).expect("No conflicts");
module.merge(eth_pubsub.clone().into_rpc()).expect("No conflicts");
module.into()
}
RethRpcModule::Net => {
NetApi::new(self.network.clone(), eth_api.clone()).into_rpc().into()
}
RethRpcModule::Trace => TraceApi::new(
self.provider.clone(),
eth_api.clone(),
eth_cache.clone(),
Box::new(self.executor.clone()),
self.tracing_call_guard.clone(),
)
.into_rpc()
.into(),
RethRpcModule::Web3 => Web3Api::new(self.network.clone()).into_rpc().into(),
RethRpcModule::Txpool => {
TxPoolApi::new(self.pool.clone()).into_rpc().into()
}
RethRpcModule::Rpc => RPCApi::new(
namespaces
.iter()
.map(|module| (module.to_string(), "1.0".to_string()))
.collect(),
)
.into_rpc()
.into(),
})
.clone()
})
.collect::<Vec<_>>()
}
/// Returns the [EthStateCache] frontend
///
/// This will spawn exactly one [EthStateCache] service if this is the first time the cache is
/// requested.
pub fn eth_cache(&mut self) -> EthStateCache {
self.with_eth(|handlers| handlers.cache.clone())
}
/// Creates the [EthHandlers] type the first time this is called.
fn with_eth<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&EthHandlers<Provider, Pool, Network, Events>) -> R,
{
if self.eth.is_none() {
let cache = EthStateCache::spawn_with(
self.provider.clone(),
self.config.eth.cache.clone(),
self.executor.clone(),
);
let gas_oracle = GasPriceOracle::new(
self.provider.clone(),
self.config.eth.gas_oracle.clone(),
cache.clone(),
);
let new_canonical_blocks = self.events.canonical_state_stream();
let c = cache.clone();
self.executor.spawn_critical(
"cache canonical blocks task",
Box::pin(async move {
cache_new_blocks_task(c, new_canonical_blocks).await;
}),
);
let executor = Box::new(self.executor.clone());
let api = EthApi::with_spawner(
self.provider.clone(),
self.pool.clone(),
self.network.clone(),
cache.clone(),
gas_oracle,
executor.clone(),
);
let filter = EthFilter::new(
self.provider.clone(),
self.pool.clone(),
cache.clone(),
self.config.eth.max_logs_per_response,
executor.clone(),
);
let pubsub = EthPubSub::with_spawner(
self.provider.clone(),
self.pool.clone(),
self.events.clone(),
self.network.clone(),
executor,
);
let eth = EthHandlers { api, cache, filter, pubsub };
self.eth = Some(eth);
}
f(self.eth.as_ref().expect("exists; qed"))
}
/// Returns the configured [EthHandlers] or creates it if it does not exist yet
fn eth_handlers(&mut self) -> EthHandlers<Provider, Pool, Network, Events> {
self.with_eth(|handlers| handlers.clone())
}
/// Returns the configured [EthApi] or creates it if it does not exist yet
fn eth_api(&mut self) -> EthApi<Provider, Pool, Network> {