-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathlib.rs
2459 lines (2229 loc) · 82.4 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
//! 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_evm::ConfigureEvm;
//! use reth_network_api::{NetworkInfo, Peers};
//! use reth_provider::{
//! AccountReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider,
//! ChangeSetReader, EvmEnvProvider, StateProviderFactory,
//! };
//! 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, EvmConfig>(
//! provider: Provider,
//! pool: Pool,
//! network: Network,
//! events: Events,
//! evm_config: EvmConfig,
//! ) where
//! Provider: AccountReader
//! + BlockReaderIdExt
//! + ChainSpecProvider
//! + ChangeSetReader
//! + StateProviderFactory
//! + EvmEnvProvider
//! + Clone
//! + Unpin
//! + 'static,
//! Pool: TransactionPool + Clone + 'static,
//! Network: NetworkInfo + Peers + Clone + 'static,
//! Events: CanonStateSubscriptions + Clone + 'static,
//! EvmConfig: ConfigureEvm + '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,
//! evm_config,
//! )
//! .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 reth_engine_primitives::EngineTypes;
//! use reth_evm::ConfigureEvm;
//! use reth_network_api::{NetworkInfo, Peers};
//! use reth_provider::{
//! AccountReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider,
//! ChangeSetReader, EvmEnvProvider, StateProviderFactory,
//! };
//! use reth_rpc::JwtSecret;
//! use reth_rpc_api::EngineApiServer;
//! use reth_rpc_builder::{
//! auth::AuthServerConfig, RethRpcModule, RpcModuleBuilder, RpcServerConfig,
//! TransportRpcModuleConfig,
//! };
//! use reth_tasks::TokioTaskExecutor;
//! use reth_transaction_pool::TransactionPool;
//! use tokio::try_join;
//! pub async fn launch<Provider, Pool, Network, Events, EngineApi, EngineT, EvmConfig>(
//! provider: Provider,
//! pool: Pool,
//! network: Network,
//! events: Events,
//! engine_api: EngineApi,
//! evm_config: EvmConfig,
//! ) where
//! Provider: AccountReader
//! + BlockReaderIdExt
//! + ChainSpecProvider
//! + ChangeSetReader
//! + StateProviderFactory
//! + EvmEnvProvider
//! + Clone
//! + Unpin
//! + 'static,
//! Pool: TransactionPool + Clone + 'static,
//! Network: NetworkInfo + Peers + Clone + 'static,
//! Events: CanonStateSubscriptions + Clone + 'static,
//! EngineApi: EngineApiServer<EngineT>,
//! EngineT: EngineTypes + 'static,
//! EvmConfig: ConfigureEvm + 'static,
//! {
//! // 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,
//! evm_config,
//! );
//!
//! // configure the server modules
//! let (modules, auth_module, _registry) =
//! 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();
//! }
//! ```
#![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/paradigmxyz/reth/issues/"
)]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
use crate::{
auth::AuthRpcModule, error::WsHttpSamePortError, metrics::RpcRequestMetrics,
RpcModuleSelection::Selection,
};
use constants::*;
use error::{RpcError, ServerKind};
use hyper::{header::AUTHORIZATION, HeaderMap};
pub use jsonrpsee::server::ServerBuilder;
use jsonrpsee::{
core::RegisterMethodError,
server::{AlreadyStoppedError, IdProvider, RpcServiceBuilder, Server, ServerHandle},
Methods, RpcModule,
};
use reth_engine_primitives::EngineTypes;
use reth_evm::ConfigureEvm;
use reth_ipc::server::IpcServer;
pub use reth_ipc::server::{
Builder as IpcServerBuilder, Endpoint, RpcServiceBuilder as IpcRpcServiceBuilder,
};
use reth_network_api::{noop::NoopNetwork, NetworkInfo, Peers};
use reth_provider::{
AccountReader, BlockReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider,
ChangeSetReader, EvmEnvProvider, StateProviderFactory,
};
use reth_rpc::{
eth::{
cache::{cache_new_blocks_task, EthStateCache},
fee_history_cache_new_blocks_task,
gas_oracle::GasPriceOracle,
traits::RawTransactionForwarder,
EthBundle, FeeHistoryCache,
},
AdminApi, AuthLayer, Claims, DebugApi, EngineEthApi, EthApi, EthFilter, EthPubSub,
EthSubscriptionIdProvider, JwtAuthValidator, JwtSecret, NetApi, OtterscanApi, RPCApi, RethApi,
TraceApi, TxPoolApi, Web3Api,
};
use reth_rpc_api::servers::*;
use reth_tasks::{
pool::{BlockingTaskGuard, BlockingTaskPool},
TaskSpawner, TokioTaskExecutor,
};
use reth_transaction_pool::{noop::NoopTransactionPool, TransactionPool};
use serde::{Deserialize, Serialize, Serializer};
use std::{
collections::{HashMap, HashSet},
fmt,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
str::FromStr,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use strum::{AsRefStr, EnumIter, IntoStaticStr, ParseError, VariantArray, VariantNames};
pub use tower::layer::util::{Identity, Stack};
use tower_http::cors::CorsLayer;
use tracing::{instrument, trace};
// re-export for convenience
pub use crate::eth::{EthConfig, EthHandlers};
/// 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;
// Rpc server metrics
mod metrics;
/// Convenience function for starting a server in one step.
#[allow(clippy::too_many_arguments)]
pub async fn launch<Provider, Pool, Network, Tasks, Events, EvmConfig>(
provider: Provider,
pool: Pool,
network: Network,
module_config: impl Into<TransportRpcModuleConfig>,
server_config: impl Into<RpcServerConfig>,
executor: Tasks,
events: Events,
evm_config: EvmConfig,
) -> Result<RpcServerHandle, RpcError>
where
Provider: BlockReaderIdExt
+ AccountReader
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ ChangeSetReader
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
EvmConfig: ConfigureEvm + 'static,
{
let module_config = module_config.into();
let server_config = server_config.into();
RpcModuleBuilder::new(provider, pool, network, executor, events, evm_config)
.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, EvmConfig> {
/// 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,
/// Defines how the EVM should be configured before execution.
evm_config: EvmConfig,
}
// === impl RpcBuilder ===
impl<Provider, Pool, Network, Tasks, Events, EvmConfig>
RpcModuleBuilder<Provider, Pool, Network, Tasks, Events, EvmConfig>
{
/// Create a new instance of the builder
pub fn new(
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
evm_config: EvmConfig,
) -> Self {
Self { provider, pool, network, executor, events, evm_config }
}
/// Configure the provider instance.
pub fn with_provider<P>(
self,
provider: P,
) -> RpcModuleBuilder<P, Pool, Network, Tasks, Events, EvmConfig>
where
P: BlockReader + StateProviderFactory + EvmEnvProvider + 'static,
{
let Self { pool, network, executor, events, evm_config, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
/// Configure the transaction pool instance.
pub fn with_pool<P>(
self,
pool: P,
) -> RpcModuleBuilder<Provider, P, Network, Tasks, Events, EvmConfig>
where
P: TransactionPool + 'static,
{
let Self { provider, network, executor, events, evm_config, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
/// Configure a [NoopTransactionPool] instance.
///
/// Caution: This will configure a pool API that does absolutely 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, EvmConfig> {
let Self { provider, executor, events, network, evm_config, .. } = self;
RpcModuleBuilder {
provider,
executor,
events,
network,
evm_config,
pool: NoopTransactionPool::default(),
}
}
/// Configure the network instance.
pub fn with_network<N>(
self,
network: N,
) -> RpcModuleBuilder<Provider, Pool, N, Tasks, Events, EvmConfig>
where
N: NetworkInfo + Peers + 'static,
{
let Self { provider, pool, executor, events, evm_config, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
/// Configure a [NoopNetwork] instance.
///
/// Caution: This will configure a network API that does absolutely 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, EvmConfig> {
let Self { provider, pool, executor, events, evm_config, .. } = self;
RpcModuleBuilder {
provider,
pool,
executor,
events,
network: NoopNetwork::default(),
evm_config,
}
}
/// Configure the task executor to use for additional tasks.
pub fn with_executor<T>(
self,
executor: T,
) -> RpcModuleBuilder<Provider, Pool, Network, T, Events, EvmConfig>
where
T: TaskSpawner + 'static,
{
let Self { pool, network, provider, events, evm_config, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
/// 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, EvmConfig> {
let Self { pool, network, provider, events, evm_config, .. } = self;
RpcModuleBuilder {
provider,
network,
pool,
events,
executor: TokioTaskExecutor::default(),
evm_config,
}
}
/// Configure the event subscriber instance
pub fn with_events<E>(
self,
events: E,
) -> RpcModuleBuilder<Provider, Pool, Network, Tasks, E, EvmConfig>
where
E: CanonStateSubscriptions + 'static,
{
let Self { provider, pool, executor, network, evm_config, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
/// Configure the evm configuration type
pub fn with_evm_config<E>(
self,
evm_config: E,
) -> RpcModuleBuilder<Provider, Pool, Network, Tasks, Events, E>
where
E: ConfigureEvm + 'static,
{
let Self { provider, pool, executor, network, events, .. } = self;
RpcModuleBuilder { provider, network, pool, executor, events, evm_config }
}
}
impl<Provider, Pool, Network, Tasks, Events, EvmConfig>
RpcModuleBuilder<Provider, Pool, Network, Tasks, Events, EvmConfig>
where
Provider: BlockReaderIdExt
+ AccountReader
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ ChangeSetReader
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
EvmConfig: ConfigureEvm + '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, EngineT>(
self,
module_config: TransportRpcModuleConfig,
engine: EngineApi,
) -> (
TransportRpcModules,
AuthRpcModule,
RethModuleRegistry<Provider, Pool, Network, Tasks, Events, EvmConfig>,
)
where
EngineT: EngineTypes + 'static,
EngineApi: EngineApiServer<EngineT>,
{
let mut modules = TransportRpcModules::default();
let Self { provider, pool, network, executor, events, evm_config } = self;
let TransportRpcModuleConfig { http, ws, ipc, config } = module_config.clone();
let mut registry = RethModuleRegistry::new(
provider,
pool,
network,
executor,
events,
config.unwrap_or_default(),
evm_config,
);
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, registry)
}
/// Converts the builder into a [RethModuleRegistry] which can be used to create all components.
///
/// This is useful for getting access to API handlers directly:
///
/// # Example
///
/// ```no_run
/// use reth_evm::ConfigureEvm;
/// use reth_network_api::noop::NoopNetwork;
/// use reth_provider::test_utils::{NoopProvider, TestCanonStateSubscriptions};
/// use reth_rpc_builder::RpcModuleBuilder;
/// use reth_tasks::TokioTaskExecutor;
/// use reth_transaction_pool::noop::NoopTransactionPool;
///
/// fn init<Evm: ConfigureEvm + 'static>(evm: Evm) {
/// let mut registry = RpcModuleBuilder::default()
/// .with_provider(NoopProvider::default())
/// .with_pool(NoopTransactionPool::default())
/// .with_network(NoopNetwork::default())
/// .with_executor(TokioTaskExecutor::default())
/// .with_events(TestCanonStateSubscriptions::default())
/// .with_evm_config(evm)
/// .into_registry(Default::default());
///
/// let eth_api = registry.eth_api();
/// }
/// ```
pub fn into_registry(
self,
config: RpcModuleConfig,
) -> RethModuleRegistry<Provider, Pool, Network, Tasks, Events, EvmConfig> {
let Self { provider, pool, network, executor, events, evm_config } = self;
RethModuleRegistry::new(provider, pool, network, executor, events, config, evm_config)
}
/// 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, evm_config } = 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(),
evm_config,
);
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(Clone, Debug, 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::all_variants].
pub fn all_modules() -> Vec<RethRpcModule> {
RpcModuleSelection::try_from_selection(RethRpcModule::all_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 _unique_ [RpcModuleSelection::Selection] from the given items.
///
/// # Note
///
/// This will dedupe the selection and remove duplicates while preserving the order.
///
/// # 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])
/// );
/// ```
///
/// Create a unique selection from the [RethRpcModule] string identifiers
///
/// ```
/// use reth_rpc_builder::{RethRpcModule, RpcModuleSelection};
/// let selection = vec!["eth", "admin", "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 mut unique = HashSet::new();
let mut s = Vec::new();
for item in selection.into_iter() {
let item = item.try_into()?;
if unique.insert(item) {
s.push(item);
}
}
Ok(RpcModuleSelection::Selection(s))
}
/// 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 therefore only
/// recommended for launching standalone transports. If multiple transports need to be
/// configured it's recommended to use the [RpcModuleBuilder].
#[allow(clippy::too_many_arguments)]
pub fn standalone_module<Provider, Pool, Network, Tasks, Events, EvmConfig>(
&self,
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
config: RpcModuleConfig,
evm_config: EvmConfig,
) -> RpcModule<()>
where
Provider: BlockReaderIdExt
+ AccountReader
+ StateProviderFactory
+ EvmEnvProvider
+ ChainSpecProvider
+ ChangeSetReader
+ Clone
+ Unpin
+ 'static,
Pool: TransactionPool + Clone + 'static,
Network: NetworkInfo + Peers + Clone + 'static,
Tasks: TaskSpawner + Clone + 'static,
Events: CanonStateSubscriptions + Clone + 'static,
EvmConfig: ConfigureEvm + 'static,
{
let mut registry =
RethModuleRegistry::new(provider, pool, network, executor, events, config, evm_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> {
if s.is_empty() {
return Ok(Selection(vec![]))
}
let mut modules = s.split(',').map(str::trim).peekable();
let first = modules.peek().copied().ok_or(ParseError::VariantNotFound)?;
match first {
"all" | "All" => Ok(RpcModuleSelection::All),
"none" | "None" => Ok(Selection(vec![])),
_ => 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,
IntoStaticStr,
VariantNames,
VariantArray,
EnumIter,
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,
/// `reth_` module
Reth,
/// `ots_` module
Ots,
/// For single non-standard `eth_` namespace call `eth_callBundle`
///
/// This is separate from [RethRpcModule::Eth] because it is a non standardized call that
/// should be opt-in.
EthCallBundle,
}
// === impl RethRpcModule ===
impl RethRpcModule {
/// Returns all variant names of the enum
pub const fn all_variant_names() -> &'static [&'static str] {
<Self as VariantNames>::VARIANTS
}
/// Returns all variants of the enum
pub const fn all_variants() -> &'static [Self] {
<Self as VariantArray>::VARIANTS
}
/// Returns all variants of the enum
pub fn modules() -> impl IntoIterator<Item = RethRpcModule> {
use strum::IntoEnumIterator;
Self::iter()
}
/// Returns the string representation of the module.
#[inline]
pub fn as_str(&self) -> &'static str {
self.into()
}
}
impl FromStr for RethRpcModule {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"admin" => RethRpcModule::Admin,
"debug" => RethRpcModule::Debug,
"eth" => RethRpcModule::Eth,
"net" => RethRpcModule::Net,
"trace" => RethRpcModule::Trace,
"txpool" => RethRpcModule::Txpool,
"web3" => RethRpcModule::Web3,
"rpc" => RethRpcModule::Rpc,
"reth" => RethRpcModule::Reth,
"ots" => RethRpcModule::Ots,
"eth-call-bundle" | "eth_callBundle" => RethRpcModule::EthCallBundle,
_ => return Err(ParseError::VariantNotFound),
})
}
}
impl TryFrom<&str> for RethRpcModule {
type Error = ParseError;
fn try_from(s: &str) -> Result<RethRpcModule, <Self as TryFrom<&str>>::Error> {
FromStr::from_str(s)
}
}
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.
#[derive(Debug, Clone)]
pub struct RethModuleRegistry<Provider, Pool, Network, Tasks, Events, EvmConfig> {
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
/// Defines how to configure the EVM before execution.
evm_config: EvmConfig,
/// Additional settings for handlers.
config: RpcModuleConfig,
/// Holds a clone of all the eth namespace handlers
eth: Option<EthHandlers<Provider, Pool, Network, Events, EvmConfig>>,
/// to put trace calls behind semaphore
blocking_pool_guard: BlockingTaskGuard,
/// Contains the [Methods] of a module
modules: HashMap<RethRpcModule, Methods>,
/// Optional forwarder for `eth_sendRawTransaction`
// TODO(mattsse): find a more ergonomic way to configure eth/rpc customizations
eth_raw_transaction_forwarder: Option<Arc<dyn RawTransactionForwarder>>,
}
// === impl RethModuleRegistry ===
impl<Provider, Pool, Network, Tasks, Events, EvmConfig>
RethModuleRegistry<Provider, Pool, Network, Tasks, Events, EvmConfig>
{
/// Creates a new, empty instance.
pub fn new(
provider: Provider,
pool: Pool,
network: Network,
executor: Tasks,
events: Events,
config: RpcModuleConfig,
evm_config: EvmConfig,
) -> Self {
Self {
provider,
pool,
network,
evm_config,
eth: None,
executor,
modules: Default::default(),
blocking_pool_guard: BlockingTaskGuard::new(config.eth.max_tracing_requests),
config,
events,
eth_raw_transaction_forwarder: None,
}
}
/// Sets a forwarder for `eth_sendRawTransaction`
///
/// Note: this might be removed in the future in favor of a more generic approach.
pub fn set_eth_raw_transaction_forwarder(
&mut self,
forwarder: Arc<dyn RawTransactionForwarder>,
) {
self.eth_raw_transaction_forwarder = Some(forwarder);