astar_collator/local/
service.rs

1// This file is part of Astar.
2
3// Copyright (C) Stake Technologies Pte.Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later
5
6// Astar is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// Astar is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with Astar. If not, see <http://www.gnu.org/licenses/>.
18
19//! Local Service and ServiceFactory implementation. Specialized wrapper over substrate service.
20
21pub use crate::parachain::fake_runtime_api::RuntimeApi;
22use crate::{
23    evm_tracing_types::{EthApi as EthApiCmd, FrontierConfig},
24    rpc::tracing,
25};
26use cumulus_client_parachain_inherent::MockValidationDataInherentDataProvider;
27use cumulus_primitives_core::{
28    relay_chain::{well_known_keys, AsyncBackingParams, HeadData, UpgradeGoAhead},
29    AbridgedHostConfiguration, CollectCollationInfo, ParaId, RelayParentOffsetApi,
30};
31use fc_consensus::FrontierBlockImport;
32use fc_rpc_core::types::{FeeHistoryCache, FilterPool};
33use fc_storage::StorageOverrideHandler;
34use futures::{FutureExt, StreamExt};
35use parity_scale_codec::Encode;
36use sc_client_api::{Backend, BlockchainEvents};
37use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
38use sc_network::NetworkBackend;
39use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
40use sc_telemetry::{Telemetry, TelemetryWorker};
41use sc_transaction_pool_api::OffchainTransactionPoolFactory;
42use sp_api::ProvideRuntimeApi;
43use sp_blockchain::HeaderBackend;
44use sp_runtime::traits::{Block as BlockT, Header as HeaderT, UniqueSaturatedInto};
45use std::{collections::BTreeMap, marker::PhantomData, ops::Sub, sync::Arc, time::Duration};
46
47use astar_primitives::*;
48
49/// Local pending inherent provider for ETH pending RPC in dev mode.
50pub struct LocalPendingInherentDataProvider<B, C> {
51    client: Arc<C>,
52    para_id: ParaId,
53    phantom_data: PhantomData<B>,
54}
55
56const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6000;
57
58fn build_local_mock_inherent_data(
59    para_id: ParaId,
60    current_para_block: u32,
61    current_para_block_head: Option<HeadData>,
62    relay_blocks_per_para_block: u32,
63    relay_slot: u64,
64    relay_parent_offset: u32,
65    upgrade_go_ahead: Option<UpgradeGoAhead>,
66) -> (
67    sp_timestamp::InherentDataProvider,
68    MockValidationDataInherentDataProvider<()>,
69) {
70    let relay_offset = relay_parent_offset.saturating_add(
71        (relay_slot as u32)
72            .saturating_sub(relay_blocks_per_para_block.saturating_mul(current_para_block)),
73    );
74
75    let local_host_config = AbridgedHostConfiguration {
76        max_code_size: 16 * 1024 * 1024, // 16 MiB (local dev only)
77        max_head_data_size: 1024 * 1024,
78        max_upward_queue_count: 8,
79        max_upward_queue_size: 1024,
80        max_upward_message_size: 256,
81        max_upward_message_num_per_candidate: 5,
82        hrmp_max_message_num_per_candidate: 5,
83        validation_upgrade_cooldown: 6,
84        validation_upgrade_delay: 6,
85        async_backing_params: AsyncBackingParams {
86            allowed_ancestry_len: 0,
87            max_candidate_depth: 0,
88        },
89    };
90
91    let mocked_parachain = MockValidationDataInherentDataProvider::<()> {
92        current_para_block,
93        para_id,
94        current_para_block_head,
95        relay_blocks_per_para_block,
96        relay_offset,
97        relay_parent_offset,
98        para_blocks_per_relay_epoch: 10,
99        upgrade_go_ahead,
100        additional_key_values: Some(vec![(
101            well_known_keys::ACTIVE_CONFIG.to_vec(),
102            local_host_config.encode(),
103        )]),
104        ..Default::default()
105    };
106
107    let timestamp = relay_slot
108        .saturating_add(u64::from(relay_parent_offset))
109        .saturating_mul(RELAY_CHAIN_SLOT_DURATION_MILLIS);
110    let timestamp_provider = sp_timestamp::InherentDataProvider::new(timestamp.into());
111
112    (timestamp_provider, mocked_parachain)
113}
114
115impl<B, C> LocalPendingInherentDataProvider<B, C> {
116    /// Creates a new instance with the given client and parachain ID.
117    pub fn new(client: Arc<C>, para_id: ParaId) -> Self {
118        Self {
119            client,
120            para_id,
121            phantom_data: Default::default(),
122        }
123    }
124}
125
126#[async_trait::async_trait]
127impl<B, C> sp_inherents::CreateInherentDataProviders<B, ()>
128    for LocalPendingInherentDataProvider<B, C>
129where
130    B: BlockT,
131    C: ProvideRuntimeApi<B> + HeaderBackend<B> + Send + Sync,
132    C::Api: RelayParentOffsetApi<B>,
133{
134    type InherentDataProviders = (
135        sp_timestamp::InherentDataProvider,
136        MockValidationDataInherentDataProvider<()>,
137    );
138
139    async fn create_inherent_data_providers(
140        &self,
141        parent: B::Hash,
142        _extra_args: (),
143    ) -> Result<Self::InherentDataProviders, Box<dyn std::error::Error + Send + Sync>> {
144        let relay_slot = std::time::SystemTime::now()
145            .duration_since(std::time::UNIX_EPOCH)
146            .expect("Current time is always after UNIX_EPOCH; qed")
147            .as_millis() as u64
148            / RELAY_CHAIN_SLOT_DURATION_MILLIS;
149
150        let current_para_block = self
151            .client
152            .header(parent)?
153            .map(|header| {
154                UniqueSaturatedInto::<u32>::unique_saturated_into(*header.number())
155                    .saturating_add(1)
156            })
157            .unwrap_or(1);
158
159        let current_para_block_head = self
160            .client
161            .header(parent)?
162            .map(|header| header.encode().into());
163
164        let relay_parent_offset = self.client.runtime_api().relay_parent_offset(parent)?;
165
166        let (timestamp_provider, mocked_parachain) = build_local_mock_inherent_data(
167            self.para_id,
168            current_para_block,
169            current_para_block_head,
170            1,
171            relay_slot,
172            relay_parent_offset,
173            None,
174        );
175
176        Ok((timestamp_provider, mocked_parachain))
177    }
178}
179
180/// Parachain host functions
181#[cfg(feature = "runtime-benchmarks")]
182pub type HostFunctions = (
183    frame_benchmarking::benchmarking::HostFunctions,
184    cumulus_client_service::ParachainHostFunctions,
185    moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
186);
187
188/// Parachain host functions
189#[cfg(not(feature = "runtime-benchmarks"))]
190pub type HostFunctions = (
191    cumulus_client_service::ParachainHostFunctions,
192    moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
193);
194
195type ParachainExecutor = WasmExecutor<HostFunctions>;
196
197type FullClient = sc_service::TFullClient<Block, RuntimeApi, ParachainExecutor>;
198type FullBackend = sc_service::TFullBackend<Block>;
199type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
200
201/// Build a partial chain component config
202pub fn new_partial(
203    config: &Configuration,
204    evm_tracing_config: &FrontierConfig,
205) -> Result<
206    sc_service::PartialComponents<
207        FullClient,
208        FullBackend,
209        FullSelectChain,
210        sc_consensus::DefaultImportQueue<Block>,
211        sc_transaction_pool::TransactionPoolHandle<Block, FullClient>,
212        (
213            FrontierBlockImport<Block, Arc<FullClient>, FullClient>,
214            Option<Telemetry>,
215            Arc<fc_db::Backend<Block, FullClient>>,
216        ),
217    >,
218    ServiceError,
219> {
220    let telemetry = config
221        .telemetry_endpoints
222        .clone()
223        .filter(|x| !x.is_empty())
224        .map(|endpoints| -> Result<_, sc_telemetry::Error> {
225            let worker = TelemetryWorker::new(16)?;
226            let telemetry = worker.handle().new_telemetry(endpoints);
227            Ok((worker, telemetry))
228        })
229        .transpose()?;
230
231    let heap_pages = config
232        .executor
233        .default_heap_pages
234        .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
235            extra_pages: h as _,
236        });
237
238    let executor = ParachainExecutor::builder()
239        .with_execution_method(config.executor.wasm_method)
240        .with_onchain_heap_alloc_strategy(heap_pages)
241        .with_offchain_heap_alloc_strategy(heap_pages)
242        .with_max_runtime_instances(config.executor.max_runtime_instances)
243        .with_runtime_cache_size(config.executor.runtime_cache_size)
244        .build();
245
246    let (client, backend, keystore_container, task_manager) =
247        sc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
248            config,
249            telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
250            executor,
251            true,
252            Default::default(),
253        )?;
254    let client = Arc::new(client);
255    let telemetry = telemetry.map(|(worker, telemetry)| {
256        task_manager
257            .spawn_handle()
258            .spawn("telemetry", None, worker.run());
259        telemetry
260    });
261    let select_chain = sc_consensus::LongestChain::new(backend.clone());
262    let transaction_pool = sc_transaction_pool::Builder::new(
263        task_manager.spawn_essential_handle(),
264        client.clone(),
265        config.role.is_authority().into(),
266    )
267    .with_options(config.transaction_pool.clone())
268    .with_prometheus(config.prometheus_registry())
269    .build();
270    let frontier_backend = Arc::new(crate::rpc::open_frontier_backend(
271        client.clone(),
272        config,
273        evm_tracing_config,
274    )?);
275    let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
276
277    let import_queue = sc_consensus_manual_seal::import_queue(
278        Box::new(client.clone()),
279        &task_manager.spawn_essential_handle(),
280        config.prometheus_registry(),
281    );
282
283    Ok(sc_service::PartialComponents {
284        client,
285        backend,
286        task_manager,
287        import_queue,
288        keystore_container,
289        select_chain,
290        transaction_pool: transaction_pool.into(),
291        other: (frontier_block_import, telemetry, frontier_backend),
292    })
293}
294
295/// Builds a new local development service (parachain-oriented).
296pub fn start_node<N>(
297    mut config: Configuration,
298    evm_tracing_config: FrontierConfig,
299) -> Result<TaskManager, ServiceError>
300where
301    N: NetworkBackend<Block, <Block as BlockT>::Hash>,
302{
303    let sc_service::PartialComponents {
304        client,
305        backend,
306        mut task_manager,
307        import_queue,
308        keystore_container,
309        select_chain,
310        transaction_pool,
311        other: (block_import, mut telemetry, frontier_backend),
312    } = new_partial(&config, &evm_tracing_config)?;
313
314    // Dev node: no peers
315    config.network.default_peers_set.in_peers = 0;
316    config.network.default_peers_set.out_peers = 0;
317
318    let net_config = sc_network::config::FullNetworkConfiguration::<_, _, N>::new(
319        &config.network,
320        config.prometheus_registry().cloned(),
321    );
322
323    let metrics = N::register_notification_metrics(
324        config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
325    );
326    let (network, system_rpc_tx, tx_handler_controller, sync_service) =
327        sc_service::build_network(sc_service::BuildNetworkParams {
328            config: &config,
329            net_config,
330            client: client.clone(),
331            transaction_pool: transaction_pool.clone(),
332            spawn_handle: task_manager.spawn_handle(),
333            spawn_essential_handle: task_manager.spawn_essential_handle(),
334            import_queue,
335            block_announce_validator_builder: None,
336            warp_sync_config: None,
337            block_relay: None,
338            metrics,
339        })?;
340
341    if config.offchain_worker.enabled {
342        task_manager.spawn_handle().spawn(
343            "offchain-workers-runner",
344            "offchain-work",
345            sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
346                runtime_api_provider: client.clone(),
347                keystore: Some(keystore_container.keystore()),
348                offchain_db: backend.offchain_storage(),
349                transaction_pool: Some(OffchainTransactionPoolFactory::new(
350                    transaction_pool.clone(),
351                )),
352                network_provider: Arc::new(network.clone()),
353                is_validator: config.role.is_authority(),
354                enable_http_requests: true,
355                custom_extensions: move |_| vec![],
356            })?
357            .run(client.clone(), task_manager.spawn_handle())
358            .boxed(),
359        );
360    }
361
362    let filter_pool: FilterPool = Arc::new(std::sync::Mutex::new(BTreeMap::new()));
363    let fee_history_cache: FeeHistoryCache = Arc::new(std::sync::Mutex::new(BTreeMap::new()));
364    let storage_override = Arc::new(StorageOverrideHandler::new(client.clone()));
365
366    // Sinks for pubsub notifications.
367    // Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
368    // 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.
369    // This way we avoid race conditions when using native substrate block import notification stream.
370    let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
371        fc_mapping_sync::EthereumBlockNotification<Block>,
372    > = Default::default();
373    let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
374
375    let ethapi_cmd = evm_tracing_config.ethapi.clone();
376
377    let tracing_requesters =
378        if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
379            tracing::spawn_tracing_tasks(
380                &evm_tracing_config,
381                config.prometheus_registry().cloned(),
382                tracing::SpawnTasksParams {
383                    task_manager: &task_manager,
384                    client: client.clone(),
385                    substrate_backend: backend.clone(),
386                    frontier_backend: frontier_backend.clone(),
387                    storage_override: storage_override.clone(),
388                },
389            )
390        } else {
391            tracing::RpcRequesters {
392                debug: None,
393                trace: None,
394            }
395        };
396
397    // Frontier offchain DB task. Essential.
398    // Maps emulated ethereum data to substrate native data.
399    match frontier_backend.as_ref() {
400        fc_db::Backend::KeyValue(ref b) => {
401            task_manager.spawn_essential_handle().spawn(
402                "frontier-mapping-sync-worker",
403                Some("frontier"),
404                fc_mapping_sync::kv::MappingSyncWorker::new(
405                    client.import_notification_stream(),
406                    Duration::new(6, 0),
407                    client.clone(),
408                    backend.clone(),
409                    storage_override.clone(),
410                    b.clone(),
411                    3,
412                    0,
413                    None,
414                    fc_mapping_sync::SyncStrategy::Parachain,
415                    sync_service.clone(),
416                    pubsub_notification_sinks.clone(),
417                )
418                .for_each(|()| futures::future::ready(())),
419            );
420        }
421        fc_db::Backend::Sql(ref b) => {
422            task_manager.spawn_essential_handle().spawn_blocking(
423                "frontier-mapping-sync-worker",
424                Some("frontier"),
425                fc_mapping_sync::sql::SyncWorker::run(
426                    client.clone(),
427                    backend.clone(),
428                    b.clone(),
429                    client.import_notification_stream(),
430                    fc_mapping_sync::sql::SyncWorkerConfig {
431                        read_notification_timeout: Duration::from_secs(10),
432                        check_indexed_blocks_interval: Duration::from_secs(60),
433                    },
434                    fc_mapping_sync::SyncStrategy::Parachain,
435                    sync_service.clone(),
436                    pubsub_notification_sinks.clone(),
437                ),
438            );
439        }
440    }
441
442    // Frontier `EthFilterApi` maintenance. Manages the pool of user-created Filters.
443    // Each filter is allowed to stay in the pool for 100 blocks.
444    const FILTER_RETAIN_THRESHOLD: u64 = 100;
445    task_manager.spawn_essential_handle().spawn(
446        "frontier-filter-pool",
447        Some("frontier"),
448        fc_rpc::EthTask::filter_pool_task(
449            client.clone(),
450            filter_pool.clone(),
451            FILTER_RETAIN_THRESHOLD,
452        ),
453    );
454
455    const FEE_HISTORY_LIMIT: u64 = 2048;
456    task_manager.spawn_essential_handle().spawn(
457        "frontier-fee-history",
458        Some("frontier"),
459        fc_rpc::EthTask::fee_history_task(
460            client.clone(),
461            storage_override.clone(),
462            fee_history_cache.clone(),
463            FEE_HISTORY_LIMIT,
464        ),
465    );
466
467    let role = config.role.clone();
468    let prometheus_registry = config.prometheus_registry().cloned();
469    let is_authority = config.role.is_authority();
470
471    let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
472        task_manager.spawn_handle(),
473        storage_override.clone(),
474        50,
475        50,
476        prometheus_registry.clone(),
477    ));
478
479    // Channel for the rpc handler to communicate with the authorship task.
480    let (command_sink, commands_stream) = futures::channel::mpsc::channel(1024);
481    let local_para_id = ParaId::from(
482        crate::parachain::chain_spec::Extensions::try_get(&*config.chain_spec)
483            .map(|e| e.para_id)
484            .unwrap_or(2000),
485    );
486
487    let rpc_extensions_builder = {
488        let client = client.clone();
489        let network = network.clone();
490        let transaction_pool = transaction_pool.clone();
491        let sync = sync_service.clone();
492        let pubsub_notification_sinks = pubsub_notification_sinks.clone();
493
494        Box::new(move |subscription| {
495            let deps = crate::rpc::FullDeps {
496                client: client.clone(),
497                pool: transaction_pool.clone(),
498                graph: transaction_pool.clone(),
499                network: network.clone(),
500                sync: sync.clone(),
501                is_authority,
502                frontier_backend: match *frontier_backend {
503                    fc_db::Backend::KeyValue(ref b) => b.clone(),
504                    fc_db::Backend::Sql(ref b) => b.clone(),
505                },
506                filter_pool: filter_pool.clone(),
507                fee_history_limit: FEE_HISTORY_LIMIT,
508                fee_history_cache: fee_history_cache.clone(),
509                block_data_cache: block_data_cache.clone(),
510                storage_override: storage_override.clone(),
511                enable_evm_rpc: true, // enable EVM RPC for dev node by default
512                command_sink: Some(command_sink.clone()),
513            };
514
515            crate::rpc::create_full_local_dev(
516                deps,
517                subscription,
518                pubsub_notification_sinks.clone(),
519                local_para_id,
520                crate::rpc::EvmTracingConfig {
521                    tracing_requesters: tracing_requesters.clone(),
522                    trace_filter_max_count: evm_tracing_config.ethapi_trace_max_count,
523                    trace_filter_max_block_range: evm_tracing_config.trace_filter_max_block_range,
524                    enable_txpool: ethapi_cmd.contains(&EthApiCmd::TxPool),
525                },
526            )
527            .map_err::<ServiceError, _>(Into::into)
528        })
529    };
530
531    let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
532        network: network.clone(),
533        client: client.clone(),
534        keystore: keystore_container.keystore(),
535        task_manager: &mut task_manager,
536        transaction_pool: transaction_pool.clone(),
537        rpc_builder: rpc_extensions_builder,
538        backend,
539        system_rpc_tx,
540        tx_handler_controller,
541        sync_service: sync_service.clone(),
542        config,
543        telemetry: telemetry.as_mut(),
544        tracing_execute_block: None,
545    })?;
546
547    if role.is_authority() {
548        let proposer_factory = sc_basic_authorship::ProposerFactory::new(
549            task_manager.spawn_handle(),
550            client.clone(),
551            transaction_pool.clone(),
552            prometheus_registry.as_ref(),
553            telemetry.as_ref().map(|x| x.handle()),
554        );
555
556        let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
557
558        let para_id = local_para_id;
559        let initial_relay_slot = std::time::SystemTime::now()
560            .duration_since(std::time::UNIX_EPOCH)
561            .expect("Current time is always after UNIX_EPOCH; qed")
562            .sub(Duration::from_secs(2 * 60 * 60))
563            .as_millis() as u64
564            / RELAY_CHAIN_SLOT_DURATION_MILLIS;
565
566        let aura =
567            sc_consensus_manual_seal::run_manual_seal(sc_consensus_manual_seal::ManualSealParams {
568                block_import,
569                env: proposer_factory,
570                client: client.clone(),
571                pool: transaction_pool.clone(),
572                commands_stream,
573                select_chain,
574                consensus_data_provider: Some(Box::new(
575                    sc_consensus_manual_seal::consensus::aura::AuraConsensusDataProvider::new(
576                        client.clone(),
577                    ),
578                )),
579                create_inherent_data_providers: move |parent_hash, ()| {
580                    let client = client.clone();
581                    async move {
582                        let current_para_head = client
583                            .header(parent_hash)
584                            .expect("Header lookup should succeed")
585                            .expect("Header passed in as parent should be present in backend.");
586
587                        let should_send_go_ahead = client
588                            .runtime_api()
589                            .collect_collation_info(parent_hash, &current_para_head)
590                            .map(|info| info.new_validation_code.is_some())
591                            .unwrap_or_default();
592
593                        let current_para_block = UniqueSaturatedInto::<u32>::unique_saturated_into(
594                            *current_para_head.number(),
595                        ) + 1;
596
597                        let relay_blocks_per_para_block =
598                            (slot_duration.as_millis() / RELAY_CHAIN_SLOT_DURATION_MILLIS).max(1)
599                                as u32;
600                        let current_para_block_u64 = u64::from(current_para_block);
601                        let relay_blocks_per_para_block_u64 =
602                            u64::from(relay_blocks_per_para_block);
603                        let target_relay_slot = initial_relay_slot.saturating_add(
604                            current_para_block_u64.saturating_mul(relay_blocks_per_para_block_u64),
605                        );
606
607                        let current_para_block_head = Some(current_para_head.encode().into());
608                        let relay_parent_offset =
609                            client.runtime_api().relay_parent_offset(parent_hash)?;
610
611                        let (timestamp_provider, mocked_parachain) = build_local_mock_inherent_data(
612                            para_id,
613                            current_para_block,
614                            current_para_block_head,
615                            relay_blocks_per_para_block,
616                            target_relay_slot,
617                            relay_parent_offset,
618                            should_send_go_ahead.then_some(UpgradeGoAhead::GoAhead),
619                        );
620
621                        Ok((timestamp_provider, mocked_parachain))
622                    }
623                },
624            });
625
626        task_manager
627            .spawn_essential_handle()
628            .spawn_blocking("aura", Some("block-authoring"), aura);
629    }
630
631    Ok(task_manager)
632}