-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathlib.rs
1825 lines (1673 loc) · 54.9 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
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Moonbeam is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Moonbeam. If not, see <http://www.gnu.org/licenses/>.
//! This module assembles the Moonbeam service components, executes them, and manages communication
//! between them. This is the backbone of the client-side node implementation.
//!
//! This module can assemble:
//! PartialComponents: For maintence tasks without a complete node (eg import/export blocks, purge)
//! Full Service: A complete parachain node including the pool, rpc, network, embedded relay chain
//! Dev Service: A leaner service without the relay chain backing.
pub mod rpc;
use cumulus_client_cli::CollatorOptions;
use cumulus_client_collator::service::CollatorService;
use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport;
use cumulus_client_consensus_proposer::Proposer;
use cumulus_client_parachain_inherent::{MockValidationDataInherentDataProvider, MockXcmConfig};
use cumulus_client_service::{
prepare_node_config, start_relay_chain_tasks, CollatorSybilResistance, DARecoveryProfile,
StartRelayChainTasksParams,
};
use cumulus_primitives_core::relay_chain::CollatorPair;
use cumulus_primitives_core::ParaId;
use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;
use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface, RelayChainResult};
use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node_with_rpc;
use fc_consensus::FrontierBlockImport as TFrontierBlockImport;
use fc_db::DatabaseSource;
use fc_rpc_core::types::{FeeHistoryCache, FilterPool};
use futures::{FutureExt, StreamExt};
use maplit::hashmap;
#[cfg(feature = "moonbase-native")]
pub use moonbase_runtime;
use moonbeam_cli_opt::{EthApi as EthApiCmd, FrontierBackendConfig, RpcConfig};
#[cfg(feature = "moonbeam-native")]
pub use moonbeam_runtime;
use moonbeam_vrf::VrfDigestsProvider;
#[cfg(feature = "moonriver-native")]
pub use moonriver_runtime;
use nimbus_consensus::NimbusManualSealConsensusDataProvider;
use nimbus_primitives::{DigestsProvider, NimbusId};
use sc_client_api::{
backend::{AuxStore, Backend, StateBackend, StorageProvider},
ExecutorProvider,
};
use sc_consensus::ImportQueue;
use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
use sc_network::{config::FullNetworkConfiguration, NetworkBlock};
use sc_service::config::PrometheusConfig;
use sc_service::{
error::Error as ServiceError, ChainSpec, Configuration, PartialComponents, TFullBackend,
TFullClient, TaskManager,
};
use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
use sp_api::{ConstructRuntimeApi, ProvideRuntimeApi};
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_consensus::SyncOracle;
use sp_core::{ByteArray, Encode, H256};
use sp_keystore::{Keystore, KeystorePtr};
use std::str::FromStr;
use std::sync::Arc;
use std::{collections::BTreeMap, path::Path, sync::Mutex, time::Duration};
use substrate_prometheus_endpoint::Registry;
pub use client::*;
pub mod chain_spec;
mod client;
type FullClient<RuntimeApi> = TFullClient<Block, RuntimeApi, WasmExecutor<HostFunctions>>;
type FullBackend = TFullBackend<Block>;
type MaybeSelectChain = Option<sc_consensus::LongestChain<FullBackend, Block>>;
type FrontierBlockImport<RuntimeApi> =
TFrontierBlockImport<Block, Arc<FullClient<RuntimeApi>>, FullClient<RuntimeApi>>;
type ParachainBlockImport<RuntimeApi> =
TParachainBlockImport<Block, FrontierBlockImport<RuntimeApi>, FullBackend>;
type PartialComponentsResult<RuntimeApi> = Result<
PartialComponents<
FullClient<RuntimeApi>,
FullBackend,
MaybeSelectChain,
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi>>,
(
BlockImportPipeline<FrontierBlockImport<RuntimeApi>, ParachainBlockImport<RuntimeApi>>,
Option<FilterPool>,
Option<Telemetry>,
Option<TelemetryWorkerHandle>,
fc_db::Backend<Block>,
FeeHistoryCache,
),
>,
ServiceError,
>;
#[cfg(feature = "runtime-benchmarks")]
pub type HostFunctions = (
frame_benchmarking::benchmarking::HostFunctions,
sp_io::SubstrateHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);
#[cfg(not(feature = "runtime-benchmarks"))]
pub type HostFunctions = (
sp_io::SubstrateHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);
/// Block Import Pipeline used.
pub enum BlockImportPipeline<T, E> {
/// Used in dev mode to import new blocks as best blocks.
Dev(T),
/// Used in parachain mode.
Parachain(E),
}
/// A trait that must be implemented by all moon* runtimes executors.
///
/// This feature allows, for instance, to customize the client extensions according to the type
/// of network.
/// For the moment, this feature is only used to specify the first block compatible with
/// ed25519-zebra, but it could be used for other things in the future.
pub trait ClientCustomizations {
/// The host function ed25519_verify has changed its behavior in the substrate history,
/// because of the change from lib ed25519-dalek to lib ed25519-zebra.
/// Some networks may have old blocks that are not compatible with ed25519-zebra,
/// for these networks this function should return the 1st block compatible with the new lib.
/// If this function returns None (default behavior), it implies that all blocks are compatible
/// with the new lib (ed25519-zebra).
fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
None
}
}
#[cfg(feature = "moonbeam-native")]
pub struct MoonbeamCustomizations;
#[cfg(feature = "moonbeam-native")]
impl ClientCustomizations for MoonbeamCustomizations {
fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
Some(2_000_000)
}
}
#[cfg(feature = "moonriver-native")]
pub struct MoonriverCustomizations;
#[cfg(feature = "moonriver-native")]
impl ClientCustomizations for MoonriverCustomizations {
fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
Some(3_000_000)
}
}
#[cfg(feature = "moonbase-native")]
pub struct MoonbaseCustomizations;
#[cfg(feature = "moonbase-native")]
impl ClientCustomizations for MoonbaseCustomizations {
fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
Some(3_000_000)
}
}
/// Trivial enum representing runtime variant
#[derive(Clone)]
pub enum RuntimeVariant {
#[cfg(feature = "moonbeam-native")]
Moonbeam,
#[cfg(feature = "moonriver-native")]
Moonriver,
#[cfg(feature = "moonbase-native")]
Moonbase,
Unrecognized,
}
impl RuntimeVariant {
pub fn from_chain_spec(chain_spec: &Box<dyn ChainSpec>) -> Self {
match chain_spec {
#[cfg(feature = "moonbeam-native")]
spec if spec.is_moonbeam() => Self::Moonbeam,
#[cfg(feature = "moonriver-native")]
spec if spec.is_moonriver() => Self::Moonriver,
#[cfg(feature = "moonbase-native")]
spec if spec.is_moonbase() => Self::Moonbase,
_ => Self::Unrecognized,
}
}
}
/// Can be called for a `Configuration` to check if it is a configuration for
/// the `Moonbeam` network.
pub trait IdentifyVariant {
/// Returns `true` if this is a configuration for the `Moonbase` network.
fn is_moonbase(&self) -> bool;
/// Returns `true` if this is a configuration for the `Moonbeam` network.
fn is_moonbeam(&self) -> bool;
/// Returns `true` if this is a configuration for the `Moonriver` network.
fn is_moonriver(&self) -> bool;
/// Returns `true` if this is a configuration for a dev network.
fn is_dev(&self) -> bool;
}
impl IdentifyVariant for Box<dyn ChainSpec> {
fn is_moonbase(&self) -> bool {
self.id().starts_with("moonbase")
}
fn is_moonbeam(&self) -> bool {
self.id().starts_with("moonbeam")
}
fn is_moonriver(&self) -> bool {
self.id().starts_with("moonriver")
}
fn is_dev(&self) -> bool {
self.chain_type() == sc_chain_spec::ChainType::Development
}
}
pub fn frontier_database_dir(config: &Configuration, path: &str) -> std::path::PathBuf {
config
.base_path
.config_dir(config.chain_spec.id())
.join("frontier")
.join(path)
}
// TODO This is copied from frontier. It should be imported instead after
// https://github.com/paritytech/frontier/issues/333 is solved
pub fn open_frontier_backend<C, BE>(
client: Arc<C>,
config: &Configuration,
rpc_config: &RpcConfig,
) -> Result<fc_db::Backend<Block>, String>
where
C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,
C: Send + Sync + 'static,
C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
BE: Backend<Block> + 'static,
BE::State: StateBackend<BlakeTwo256>,
{
let frontier_backend = match rpc_config.frontier_backend_config {
FrontierBackendConfig::KeyValue => {
fc_db::Backend::KeyValue(fc_db::kv::Backend::<Block>::new(
client,
&fc_db::kv::DatabaseSettings {
source: match config.database {
DatabaseSource::RocksDb { .. } => DatabaseSource::RocksDb {
path: frontier_database_dir(config, "db"),
cache_size: 0,
},
DatabaseSource::ParityDb { .. } => DatabaseSource::ParityDb {
path: frontier_database_dir(config, "paritydb"),
},
DatabaseSource::Auto { .. } => DatabaseSource::Auto {
rocksdb_path: frontier_database_dir(config, "db"),
paritydb_path: frontier_database_dir(config, "paritydb"),
cache_size: 0,
},
_ => {
return Err(
"Supported db sources: `rocksdb` | `paritydb` | `auto`".to_string()
)
}
},
},
)?)
}
FrontierBackendConfig::Sql {
pool_size,
num_ops_timeout,
thread_count,
cache_size,
} => {
let overrides = crate::rpc::overrides_handle(client.clone());
let sqlite_db_path = frontier_database_dir(config, "sql");
std::fs::create_dir_all(&sqlite_db_path).expect("failed creating sql db directory");
let backend = futures::executor::block_on(fc_db::sql::Backend::new(
fc_db::sql::BackendConfig::Sqlite(fc_db::sql::SqliteBackendConfig {
path: Path::new("sqlite:///")
.join(sqlite_db_path)
.join("frontier.db3")
.to_str()
.expect("frontier sql path error"),
create_if_missing: true,
thread_count: thread_count,
cache_size: cache_size,
}),
pool_size,
std::num::NonZeroU32::new(num_ops_timeout),
overrides.clone(),
))
.unwrap_or_else(|err| panic!("failed creating sql backend: {:?}", err));
fc_db::Backend::Sql(backend)
}
};
Ok(frontier_backend)
}
use sp_runtime::{traits::BlakeTwo256, DigestItem, Percent};
pub const SOFT_DEADLINE_PERCENT: Percent = Percent::from_percent(100);
/// Builds a new object suitable for chain operations.
#[allow(clippy::type_complexity)]
pub fn new_chain_ops(
config: &mut Configuration,
rpc_config: &RpcConfig,
) -> Result<
(
Arc<Client>,
Arc<FullBackend>,
sc_consensus::BasicQueue<Block>,
TaskManager,
),
ServiceError,
> {
match &config.chain_spec {
#[cfg(feature = "moonriver-native")]
spec if spec.is_moonriver() => new_chain_ops_inner::<
moonriver_runtime::RuntimeApi,
MoonriverCustomizations,
>(config, rpc_config),
#[cfg(feature = "moonbeam-native")]
spec if spec.is_moonbeam() => new_chain_ops_inner::<
moonbeam_runtime::RuntimeApi,
MoonbeamCustomizations,
>(config, rpc_config),
#[cfg(feature = "moonbase-native")]
_ => new_chain_ops_inner::<moonbase_runtime::RuntimeApi, MoonbaseCustomizations>(
config, rpc_config,
),
#[cfg(not(feature = "moonbase-native"))]
_ => panic!("invalid chain spec"),
}
}
#[allow(clippy::type_complexity)]
fn new_chain_ops_inner<RuntimeApi, Customizations>(
config: &mut Configuration,
rpc_config: &RpcConfig,
) -> Result<
(
Arc<Client>,
Arc<FullBackend>,
sc_consensus::BasicQueue<Block>,
TaskManager,
),
ServiceError,
>
where
Client: From<Arc<crate::FullClient<RuntimeApi>>>,
RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: RuntimeApiCollection,
Customizations: ClientCustomizations + 'static,
{
config.keystore = sc_service::config::KeystoreConfig::InMemory;
let PartialComponents {
client,
backend,
import_queue,
task_manager,
..
} = new_partial::<RuntimeApi, Customizations>(config, rpc_config, config.chain_spec.is_dev())?;
Ok((
Arc::new(Client::from(client)),
backend,
import_queue,
task_manager,
))
}
// If we're using prometheus, use a registry with a prefix of `moonbeam`.
fn set_prometheus_registry(
config: &mut Configuration,
skip_prefix: bool,
) -> Result<(), ServiceError> {
if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
let labels = hashmap! {
"chain".into() => config.chain_spec.id().into(),
};
let prefix = if skip_prefix {
None
} else {
Some("moonbeam".into())
};
*registry = Registry::new_custom(prefix, Some(labels))?;
}
Ok(())
}
/// Builds the PartialComponents for a parachain or development service
///
/// Use this function if you don't actually need the full service, but just the partial in order to
/// be able to perform chain operations.
#[allow(clippy::type_complexity)]
pub fn new_partial<RuntimeApi, Customizations>(
config: &mut Configuration,
rpc_config: &RpcConfig,
dev_service: bool,
) -> PartialComponentsResult<RuntimeApi>
where
RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: RuntimeApiCollection,
Customizations: ClientCustomizations + 'static,
{
set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
// Use ethereum style for subscription ids
config.rpc_id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let heap_pages = config
.default_heap_pages
.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
extra_pages: h as _,
});
let mut wasm_builder = WasmExecutor::builder()
.with_execution_method(config.wasm_method)
.with_onchain_heap_alloc_strategy(heap_pages)
.with_offchain_heap_alloc_strategy(heap_pages)
.with_ignore_onchain_heap_pages(true)
.with_max_runtime_instances(config.max_runtime_instances)
.with_runtime_cache_size(config.runtime_cache_size);
if let Some(ref wasmtime_precompiled_path) = config.wasmtime_precompiled {
wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
}
let executor = wasm_builder.build();
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
if let Some(block_number) = Customizations::first_block_number_compatible_with_ed25519_zebra() {
client
.execution_extensions()
.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
Block,
sp_io::UseDalekExt,
>::new(block_number));
}
let client = Arc::new(client);
let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager
.spawn_handle()
.spawn("telemetry", None, worker.run());
telemetry
});
let maybe_select_chain = if dev_service {
Some(sc_consensus::LongestChain::new(backend.clone()))
} else {
None
};
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
let frontier_backend = open_frontier_backend(client.clone(), config, rpc_config)?;
let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
let create_inherent_data_providers = move |_, _| async move {
let time = sp_timestamp::InherentDataProvider::from_system_time();
Ok((time,))
};
let (import_queue, block_import) = if dev_service {
(
nimbus_consensus::import_queue(
client.clone(),
frontier_block_import.clone(),
create_inherent_data_providers,
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
!dev_service,
)?,
BlockImportPipeline::Dev(frontier_block_import),
)
} else {
let parachain_block_import = ParachainBlockImport::new_with_delayed_best_block(
frontier_block_import,
backend.clone(),
);
(
nimbus_consensus::import_queue(
client.clone(),
parachain_block_import.clone(),
create_inherent_data_providers,
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
!dev_service,
)?,
BlockImportPipeline::Parachain(parachain_block_import),
)
};
Ok(PartialComponents {
backend,
client,
import_queue,
keystore_container,
task_manager,
transaction_pool,
select_chain: maybe_select_chain,
other: (
block_import,
filter_pool,
telemetry,
telemetry_worker_handle,
frontier_backend,
fee_history_cache,
),
})
}
async fn build_relay_chain_interface(
polkadot_config: Configuration,
parachain_config: &Configuration,
telemetry_worker_handle: Option<TelemetryWorkerHandle>,
task_manager: &mut TaskManager,
collator_options: CollatorOptions,
hwbench: Option<sc_sysinfo::HwBench>,
) -> RelayChainResult<(
Arc<(dyn RelayChainInterface + 'static)>,
Option<CollatorPair>,
)> {
if let cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) =
collator_options.relay_chain_mode
{
build_minimal_relay_chain_node_with_rpc(polkadot_config, task_manager, rpc_target_urls)
.await
} else {
build_inprocess_relay_chain(
polkadot_config,
parachain_config,
telemetry_worker_handle,
task_manager,
hwbench,
)
}
}
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[sc_tracing::logging::prefix_logs_with("🌗")]
async fn start_node_impl<RuntimeApi, Customizations>(
parachain_config: Configuration,
polkadot_config: Configuration,
collator_options: CollatorOptions,
para_id: ParaId,
rpc_config: RpcConfig,
async_backing: bool,
block_authoring_duration: Duration,
hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi>>)>
where
RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: RuntimeApiCollection,
Customizations: ClientCustomizations + 'static,
{
let mut parachain_config = prepare_node_config(parachain_config);
let params =
new_partial::<RuntimeApi, Customizations>(&mut parachain_config, &rpc_config, false)?;
let (
block_import,
filter_pool,
mut telemetry,
telemetry_worker_handle,
frontier_backend,
fee_history_cache,
) = params.other;
let client = params.client.clone();
let backend = params.backend.clone();
let mut task_manager = params.task_manager;
let (relay_chain_interface, collator_key) = build_relay_chain_interface(
polkadot_config,
¶chain_config,
telemetry_worker_handle,
&mut task_manager,
collator_options.clone(),
hwbench.clone(),
)
.await
.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
let force_authoring = parachain_config.force_authoring;
let collator = parachain_config.role.is_authority();
let prometheus_registry = parachain_config.prometheus_registry().cloned();
let transaction_pool = params.transaction_pool.clone();
let import_queue_service = params.import_queue.service();
let net_config = FullNetworkConfiguration::new(¶chain_config.network);
let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
cumulus_client_service::build_network(cumulus_client_service::BuildNetworkParams {
parachain_config: ¶chain_config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue: params.import_queue,
para_id,
relay_chain_interface: relay_chain_interface.clone(),
net_config,
sybil_resistance_level: CollatorSybilResistance::Resistant,
})
.await?;
let overrides = crate::rpc::overrides_handle(client.clone());
let fee_history_limit = rpc_config.fee_history_limit;
// Sinks for pubsub notifications.
// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
// The MappingSyncWorker sends through the channel on block import and the subscription emits a
// notification to the subscriber on receiving a message through this channel.
// This way we avoid race conditions when using native substrate block import notification
// stream.
let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
fc_mapping_sync::EthereumBlockNotification<Block>,
> = Default::default();
let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
rpc::spawn_essential_tasks(
rpc::SpawnTasksParams {
task_manager: &task_manager,
client: client.clone(),
substrate_backend: backend.clone(),
frontier_backend: frontier_backend.clone(),
filter_pool: filter_pool.clone(),
overrides: overrides.clone(),
fee_history_limit,
fee_history_cache: fee_history_cache.clone(),
},
sync_service.clone(),
pubsub_notification_sinks.clone(),
);
let ethapi_cmd = rpc_config.ethapi.clone();
let tracing_requesters =
if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
rpc::tracing::spawn_tracing_tasks(
&rpc_config,
prometheus_registry.clone(),
rpc::SpawnTasksParams {
task_manager: &task_manager,
client: client.clone(),
substrate_backend: backend.clone(),
frontier_backend: frontier_backend.clone(),
filter_pool: filter_pool.clone(),
overrides: overrides.clone(),
fee_history_limit,
fee_history_cache: fee_history_cache.clone(),
},
)
} else {
rpc::tracing::RpcRequesters {
debug: None,
trace: None,
}
};
let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
task_manager.spawn_handle(),
overrides.clone(),
rpc_config.eth_log_block_cache,
rpc_config.eth_statuses_cache,
prometheus_registry.clone(),
));
let rpc_builder = {
let client = client.clone();
let pool = transaction_pool.clone();
let network = network.clone();
let sync = sync_service.clone();
let filter_pool = filter_pool.clone();
let frontier_backend = frontier_backend.clone();
let backend = backend.clone();
let ethapi_cmd = ethapi_cmd.clone();
let max_past_logs = rpc_config.max_past_logs;
let overrides = overrides.clone();
let fee_history_cache = fee_history_cache.clone();
let block_data_cache = block_data_cache.clone();
let pubsub_notification_sinks = pubsub_notification_sinks.clone();
let keystore = params.keystore_container.keystore();
move |deny_unsafe, subscription_task_executor| {
#[cfg(feature = "moonbase-native")]
let forced_parent_hashes = {
let mut forced_parent_hashes = BTreeMap::new();
// Fixes for https://github.com/paritytech/frontier/pull/570
// #1648995
forced_parent_hashes.insert(
H256::from_str(
"0xa352fee3eef9c554a31ec0612af887796a920613358abf3353727760ea14207b",
)
.expect("must be valid hash"),
H256::from_str(
"0x0d0fd88778aec08b3a83ce36387dbf130f6f304fc91e9a44c9605eaf8a80ce5d",
)
.expect("must be valid hash"),
);
Some(forced_parent_hashes)
};
#[cfg(not(feature = "moonbase-native"))]
let forced_parent_hashes = None;
let deps = rpc::FullDeps {
backend: backend.clone(),
client: client.clone(),
command_sink: None,
deny_unsafe,
ethapi_cmd: ethapi_cmd.clone(),
filter_pool: filter_pool.clone(),
frontier_backend: match frontier_backend.clone() {
fc_db::Backend::KeyValue(b) => Arc::new(b),
fc_db::Backend::Sql(b) => Arc::new(b),
},
graph: pool.pool().clone(),
pool: pool.clone(),
is_authority: collator,
max_past_logs,
fee_history_limit,
fee_history_cache: fee_history_cache.clone(),
network: network.clone(),
sync: sync.clone(),
xcm_senders: None,
block_data_cache: block_data_cache.clone(),
overrides: overrides.clone(),
forced_parent_hashes,
};
let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
client.clone(),
keystore.clone(),
));
if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
rpc::create_full(
deps,
subscription_task_executor,
Some(crate::rpc::TracingConfig {
tracing_requesters: tracing_requesters.clone(),
trace_filter_max_count: rpc_config.ethapi_trace_max_count,
}),
pubsub_notification_sinks.clone(),
pending_consensus_data_provider,
)
.map_err(Into::into)
} else {
rpc::create_full(
deps,
subscription_task_executor,
None,
pubsub_notification_sinks.clone(),
pending_consensus_data_provider,
)
.map_err(Into::into)
}
}
};
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
rpc_builder: Box::new(rpc_builder),
client: client.clone(),
transaction_pool: transaction_pool.clone(),
task_manager: &mut task_manager,
config: parachain_config,
keystore: params.keystore_container.keystore(),
backend: backend.clone(),
network: network.clone(),
sync_service: sync_service.clone(),
system_rpc_tx,
tx_handler_controller,
telemetry: telemetry.as_mut(),
})?;
if let Some(hwbench) = hwbench {
sc_sysinfo::print_hwbench(&hwbench);
if let Some(ref mut telemetry) = telemetry {
let telemetry_handle = telemetry.handle();
task_manager.spawn_handle().spawn(
"telemetry_hwbench",
None,
sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
);
}
}
let announce_block = {
let sync_service = sync_service.clone();
Arc::new(move |hash, data| sync_service.announce_block(hash, data))
};
let relay_chain_slot_duration = Duration::from_secs(6);
let overseer_handle = relay_chain_interface
.overseer_handle()
.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
start_relay_chain_tasks(StartRelayChainTasksParams {
client: client.clone(),
announce_block: announce_block.clone(),
para_id,
relay_chain_interface: relay_chain_interface.clone(),
task_manager: &mut task_manager,
da_recovery_profile: if collator {
DARecoveryProfile::Collator
} else {
DARecoveryProfile::FullNode
},
import_queue: import_queue_service,
relay_chain_slot_duration,
recovery_handle: Box::new(overseer_handle.clone()),
sync_service: sync_service.clone(),
})?;
let BlockImportPipeline::Parachain(block_import) = block_import else {
return Err(sc_service::Error::Other(
"Block import pipeline is not for parachain".into(),
));
};
if collator {
start_consensus::<RuntimeApi, _>(
async_backing,
backend.clone(),
client.clone(),
block_import,
prometheus_registry.as_ref(),
telemetry.as_ref().map(|t| t.handle()),
&task_manager,
relay_chain_interface.clone(),
transaction_pool,
params.keystore_container.keystore(),
para_id,
collator_key.expect("Command line arguments do not allow this. qed"),
overseer_handle,
announce_block,
force_authoring,
relay_chain_slot_duration,
block_authoring_duration,
sync_service.clone(),
)?;
/*let parachain_consensus = build_consensus(
client.clone(),
backend,
block_import,
prometheus_registry.as_ref(),
telemetry.as_ref().map(|t| t.handle()),
&task_manager,
relay_chain_interface.clone(),
transaction_pool,
sync_service.clone(),
params.keystore_container.keystore(),
force_authoring,
)?;
let spawner = task_manager.spawn_handle();
let params = StartCollatorParams {
para_id,
block_status: client.clone(),
announce_block,
client: client.clone(),
task_manager: &mut task_manager,
relay_chain_interface,
spawner,
parachain_consensus,
import_queue: import_queue_service,
recovery_handle: Box::new(overseer_handle),
collator_key: collator_key.ok_or(sc_service::error::Error::Other(
"Collator Key is None".to_string(),
))?,
relay_chain_slot_duration,
sync_service,
};
#[allow(deprecated)]
start_collator(params).await?;*/
}
start_network.start_network();
Ok((task_manager, client))
}
fn start_consensus<RuntimeApi, SO>(
async_backing: bool,
backend: Arc<FullBackend>,
client: Arc<FullClient<RuntimeApi>>,
block_import: ParachainBlockImport<RuntimeApi>,
prometheus_registry: Option<&Registry>,
telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager,
relay_chain_interface: Arc<dyn RelayChainInterface>,
transaction_pool: Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi>>>,
keystore: KeystorePtr,
para_id: ParaId,
collator_key: CollatorPair,
overseer_handle: OverseerHandle,
announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
force_authoring: bool,
relay_chain_slot_duration: Duration,
block_authoring_duration: Duration,
sync_oracle: SO,
) -> Result<(), sc_service::Error>
where
RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
RuntimeApi::RuntimeApi: RuntimeApiCollection,
sc_client_api::StateBackendFor<TFullBackend<Block>, Block>:
sc_client_api::StateBackend<BlakeTwo256>,
SO: SyncOracle + Send + Sync + Clone + 'static,
{
let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
task_manager.spawn_handle(),
client.clone(),
transaction_pool,
prometheus_registry,
telemetry.clone(),
);
let proposer = Proposer::new(proposer_factory);
let collator_service = CollatorService::new(
client.clone(),
Arc::new(task_manager.spawn_handle()),
announce_block,
client.clone(),
);
let create_inherent_data_providers = |_, _| async move {
let time = sp_timestamp::InherentDataProvider::from_system_time();
let author = nimbus_primitives::InherentDataProvider;
let randomness = session_keys_primitives::InherentDataProvider;
Ok((time, author, randomness))
};
let client_clone = client.clone();
let keystore_clone = keystore.clone();
let maybe_provide_vrf_digest =
move |nimbus_id: NimbusId, parent: Hash| -> Option<sp_runtime::generic::DigestItem> {
moonbeam_vrf::vrf_pre_digest::<Block, FullClient<RuntimeApi>>(
&client_clone,
&keystore_clone,
nimbus_id,
parent,
)
};
if async_backing {