1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
//! Development Polkadot service. Adapted from `polkadot_service` crate
18
//! and removed un-necessary components which are not required in dev node.
19
//!
20
//! Following major changes are made:
21
//! 1. Removed beefy and grandpa notification service and request response protocols
22
//! 2. Removed support for parachains which also eliminated the need to start overseer and all other subsystems associated with collation + network request/response protocols for the same
23
//! 3. Removed support for hardware benchmarking
24
//! 4. Removed authority discovery service
25
//! 5. Removed spawning of beefy, grandpa and MMR worker
26
//! 6. Removed rpc extensions for beefy, grandpa and babe and added support for manual seal
27
//! 7. Removed beefy and grandpa block import from block import pipeline (Babe remains)
28
//! 8. Using manual seal import queue instead of babe import queue
29
//! 9. Started manual seal worker
30
//! 10. If amount of time passed between two block is less than slot duration, we emulate passing of time babe block import and runtime
31
//!     by incrementing timestamp by slot duration.
32

            
33
use {
34
    async_io::Timer,
35
    babe::{BabeBlockImport, BabeLink},
36
    codec::{Decode, Encode},
37
    consensus_common::SelectChain,
38
    dancelight_runtime::RuntimeApi,
39
    futures::{Stream, StreamExt},
40
    jsonrpsee::RpcModule,
41
    node_common::service::Sealing,
42
    polkadot_core_primitives::{AccountId, Balance, Block, Hash, Nonce},
43
    polkadot_node_core_parachains_inherent::Error as InherentError,
44
    polkadot_overseer::Handle,
45
    polkadot_primitives::InherentData as ParachainsInherentData,
46
    polkadot_rpc::{DenyUnsafe, RpcExtension},
47
    polkadot_service::{
48
        BlockT, Error, IdentifyVariant, NewFullParams, OverseerGen, SelectRelayChain,
49
    },
50
    sc_client_api::{AuxStore, Backend},
51
    sc_consensus_manual_seal::{
52
        consensus::babe::BabeConsensusDataProvider,
53
        rpc::{ManualSeal, ManualSealApiServer},
54
        run_manual_seal, EngineCommand, ManualSealParams,
55
    },
56
    sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY},
57
    sc_transaction_pool_api::{OffchainTransactionPoolFactory, TransactionPool},
58
    service::{Configuration, KeystoreContainer, RpcHandlers, TaskManager},
59
    sp_api::ProvideRuntimeApi,
60
    sp_block_builder::BlockBuilder,
61
    sp_blockchain::{HeaderBackend, HeaderMetadata},
62
    sp_consensus_babe::SlotDuration,
63
    std::{cmp::max, ops::Add, sync::Arc, time::Duration},
64
    telemetry::{Telemetry, TelemetryWorker, TelemetryWorkerHandle},
65
};
66

            
67
pub type FullBackend = service::TFullBackend<Block>;
68

            
69
pub type FullClient = service::TFullClient<
70
    Block,
71
    RuntimeApi,
72
    WasmExecutor<(
73
        sp_io::SubstrateHostFunctions,
74
        frame_benchmarking::benchmarking::HostFunctions,
75
    )>,
76
>;
77

            
78
pub struct NewFull {
79
    pub task_manager: TaskManager,
80
    pub client: Arc<FullClient>,
81
    pub overseer_handle: Option<Handle>,
82
    pub network: Arc<dyn sc_network::service::traits::NetworkService>,
83
    pub sync_service: Arc<sc_network_sync::SyncingService<Block>>,
84
    pub rpc_handlers: RpcHandlers,
85
    pub backend: Arc<FullBackend>,
86
}
87

            
88
/// Custom Deps for dev Rpc extension
89
struct DevDeps<C, P> {
90
    /// The client instance to use.
91
    pub client: Arc<C>,
92
    /// Transaction pool instance.
93
    pub pool: Arc<P>,
94
    /// A copy of the chain spec.
95
    pub chain_spec: Box<dyn sc_chain_spec::ChainSpec>,
96
    /// Whether to deny unsafe calls
97
    pub deny_unsafe: DenyUnsafe,
98
    /// Manual seal command sink
99
    pub command_sink: Option<futures::channel::mpsc::Sender<EngineCommand<Hash>>>,
100
}
101

            
102
476
fn create_dev_rpc_extension<C, P>(
103
476
    DevDeps {
104
476
        client,
105
476
        pool,
106
476
        chain_spec,
107
476
        deny_unsafe,
108
476
        command_sink: maybe_command_sink,
109
476
    }: DevDeps<C, P>,
110
476
) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>>
111
476
where
112
476
    C: ProvideRuntimeApi<Block>
113
476
        + HeaderBackend<Block>
114
476
        + AuxStore
115
476
        + HeaderMetadata<Block, Error = sp_blockchain::Error>
116
476
        + Send
117
476
        + Sync
118
476
        + 'static,
119
476
    C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
120
476
    C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
121
476
    C::Api: BlockBuilder<Block>,
122
476
    P: TransactionPool + Sync + Send + 'static,
123
476
{
124
    use {
125
        pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer},
126
        sc_rpc_spec_v2::chain_spec::{ChainSpec, ChainSpecApiServer},
127
        substrate_frame_rpc_system::{System, SystemApiServer},
128
    };
129

            
130
476
    let mut io = RpcModule::new(());
131
476

            
132
476
    let chain_name = chain_spec.name().to_string();
133
476
    let genesis_hash = client
134
476
        .hash(0)
135
476
        .ok()
136
476
        .flatten()
137
476
        .expect("Genesis block exists; qed");
138
476
    let properties = chain_spec.properties();
139
476

            
140
476
    io.merge(ChainSpec::new(chain_name, genesis_hash, properties).into_rpc())?;
141
476
    io.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
142
476
    io.merge(TransactionPayment::new(client.clone()).into_rpc())?;
143

            
144
476
    if let Some(command_sink) = maybe_command_sink {
145
476
        io.merge(ManualSeal::new(command_sink).into_rpc())?;
146
    }
147

            
148
476
    Ok(io)
149
476
}
150

            
151
/// We use EmptyParachainsInherentDataProvider to insert an empty parachain inherent in the block
152
/// to satisfy runtime
153
struct EmptyParachainsInherentDataProvider<C: HeaderBackend<Block>> {
154
    pub client: Arc<C>,
155
    pub parent: Hash,
156
}
157

            
158
/// Copied from polkadot service just so that this code retains same structure as
159
/// polkadot_service crate.
160
struct Basics {
161
    task_manager: TaskManager,
162
    client: Arc<FullClient>,
163
    backend: Arc<FullBackend>,
164
    keystore_container: KeystoreContainer,
165
    telemetry: Option<Telemetry>,
166
}
167

            
168
impl<C: HeaderBackend<Block>> EmptyParachainsInherentDataProvider<C> {
169
6209
    pub fn new(client: Arc<C>, parent: Hash) -> Self {
170
6209
        EmptyParachainsInherentDataProvider { client, parent }
171
6209
    }
172

            
173
6209
    pub async fn create(
174
6209
        client: Arc<C>,
175
6209
        parent: Hash,
176
6209
    ) -> Result<ParachainsInherentData, InherentError> {
177
6209
        let parent_header = match client.header(parent) {
178
6209
            Ok(Some(h)) => h,
179
            Ok(None) => return Err(InherentError::ParentHeaderNotFound(parent)),
180
            Err(err) => return Err(InherentError::Blockchain(err)),
181
        };
182

            
183
6209
        Ok(ParachainsInherentData {
184
6209
            bitfields: Vec::new(),
185
6209
            backed_candidates: Vec::new(),
186
6209
            disputes: Vec::new(),
187
6209
            parent_header,
188
6209
        })
189
6209
    }
190
}
191

            
192
#[async_trait::async_trait]
193
impl<C: HeaderBackend<Block>> sp_inherents::InherentDataProvider
194
    for EmptyParachainsInherentDataProvider<C>
195
{
196
    async fn provide_inherent_data(
197
        &self,
198
        dst_inherent_data: &mut sp_inherents::InherentData,
199
6209
    ) -> Result<(), sp_inherents::Error> {
200
6209
        let inherent_data =
201
6209
            EmptyParachainsInherentDataProvider::create(self.client.clone(), self.parent)
202
                .await
203
6209
                .map_err(|e| sp_inherents::Error::Application(Box::new(e)))?;
204

            
205
6209
        dst_inherent_data.put_data(
206
6209
            polkadot_primitives::PARACHAINS_INHERENT_IDENTIFIER,
207
6209
            &inherent_data,
208
6209
        )
209
12418
    }
210

            
211
    async fn try_handle_error(
212
        &self,
213
        _identifier: &sp_inherents::InherentIdentifier,
214
        _error: &[u8],
215
    ) -> Option<Result<(), sp_inherents::Error>> {
216
        // Inherent isn't checked and can not return any error
217
        None
218
    }
219
}
220

            
221
/// Creates new development full node with manual seal
222
238
pub fn build_full<OverseerGenerator: OverseerGen>(
223
238
    sealing: Sealing,
224
238
    config: Configuration,
225
238
    mut params: NewFullParams<OverseerGenerator>,
226
238
) -> Result<NewFull, Error> {
227
238
    let is_polkadot = config.chain_spec.is_polkadot();
228
238

            
229
238
    params.overseer_message_channel_capacity_override = params
230
238
        .overseer_message_channel_capacity_override
231
238
        .map(move |capacity| {
232
            if is_polkadot {
233
                gum::warn!("Channel capacity should _never_ be tampered with on polkadot!");
234
            }
235
            capacity
236
238
        });
237
238

            
238
238
    match config.network.network_backend {
239
        sc_network::config::NetworkBackendType::Libp2p => {
240
238
            new_full::<_, sc_network::NetworkWorker<Block, Hash>>(sealing, config, params)
241
        }
242
        sc_network::config::NetworkBackendType::Litep2p => {
243
            new_full::<_, sc_network::Litep2pNetworkBackend>(sealing, config, params)
244
        }
245
    }
246
238
}
247

            
248
/// We store past timestamp we created in the aux storage, which enable us to return timestamp which is increased by
249
/// slot duration from previous timestamp or current timestamp if in reality more time is passed.
250
6209
fn get_next_timestamp(
251
6209
    client: Arc<FullClient>,
252
6209
    slot_duration: SlotDuration,
253
6209
) -> sp_timestamp::InherentDataProvider {
254
    const TIMESTAMP_AUX_KEY: &[u8] = b"__DEV_TIMESTAMP";
255

            
256
6209
    let maybe_last_timestamp = client
257
6209
        .get_aux(TIMESTAMP_AUX_KEY)
258
6209
        .expect("Should be able to query aux storage; qed");
259
6209
    if let Some(last_timestamp) = maybe_last_timestamp {
260
6013
        let last_inherent_data = sp_timestamp::InherentType::decode(&mut last_timestamp.as_slice())
261
6013
            .expect("Timestamp data must be decoded; qed");
262
6013
        let new_inherent_data: sp_timestamp::InherentType = max(
263
6013
            last_inherent_data.add(slot_duration.as_millis()),
264
6013
            sp_timestamp::InherentType::current(),
265
6013
        );
266
6013
        client
267
6013
            .insert_aux(
268
6013
                &[(TIMESTAMP_AUX_KEY, new_inherent_data.encode().as_slice())],
269
6013
                &[],
270
6013
            )
271
6013
            .expect("Should be able to write to aux storage; qed");
272
6013
        sp_timestamp::InherentDataProvider::new(new_inherent_data)
273
    } else {
274
196
        let current_timestamp = sp_timestamp::InherentType::current();
275
196
        client
276
196
            .insert_aux(
277
196
                &[(TIMESTAMP_AUX_KEY, current_timestamp.encode().as_slice())],
278
196
                &[],
279
196
            )
280
196
            .expect("Should be able to write to aux storage; qed");
281
196
        sp_timestamp::InherentDataProvider::new(current_timestamp)
282
    }
283
6209
}
284

            
285
238
fn new_full<
286
238
    OverseerGenerator: OverseerGen,
287
238
    Network: sc_network::NetworkBackend<Block, <Block as BlockT>::Hash>,
288
238
>(
289
238
    sealing: Sealing,
290
238
    mut config: Configuration,
291
238
    NewFullParams {
292
238
        telemetry_worker_handle,
293
238
        ..
294
238
    }: NewFullParams<OverseerGenerator>,
295
238
) -> Result<NewFull, Error> {
296
238
    let role = config.role.clone();
297

            
298
238
    let basics = new_partial_basics(&mut config, telemetry_worker_handle)?;
299

            
300
238
    let prometheus_registry = config.prometheus_registry().cloned();
301
238

            
302
238
    let keystore = basics.keystore_container.local_keystore();
303
238

            
304
238
    let select_chain = SelectRelayChain::new_longest_chain(basics.backend.clone());
305

            
306
238
    let service::PartialComponents::<_, _, SelectRelayChain<_>, _, _, _> {
307
238
        client,
308
238
        backend,
309
238
        mut task_manager,
310
238
        keystore_container,
311
238
        select_chain,
312
238
        import_queue,
313
238
        transaction_pool,
314
238
        other: (block_import, babe_link, slot_duration, mut telemetry),
315
238
    } = new_partial::<SelectRelayChain<_>>(&mut config, basics, select_chain)?;
316

            
317
238
    let metrics = Network::register_notification_metrics(
318
238
        config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
319
238
    );
320
238

            
321
238
    let net_config =
322
238
        sc_network::config::FullNetworkConfiguration::<_, _, Network>::new(&config.network);
323

            
324
238
    let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
325
238
        service::build_network(service::BuildNetworkParams {
326
238
            config: &config,
327
238
            net_config,
328
238
            client: client.clone(),
329
238
            transaction_pool: transaction_pool.clone(),
330
238
            spawn_handle: task_manager.spawn_handle(),
331
238
            import_queue,
332
238
            block_announce_validator_builder: None,
333
238
            warp_sync_params: None,
334
238
            block_relay: None,
335
238
            metrics,
336
238
        })?;
337

            
338
238
    if config.offchain_worker.enabled {
339
238
        use futures::FutureExt;
340
238

            
341
238
        task_manager.spawn_handle().spawn(
342
238
            "offchain-workers-runner",
343
238
            "offchain-work",
344
238
            sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
345
238
                runtime_api_provider: client.clone(),
346
238
                keystore: Some(keystore_container.keystore()),
347
238
                offchain_db: backend.offchain_storage(),
348
238
                transaction_pool: Some(OffchainTransactionPoolFactory::new(
349
238
                    transaction_pool.clone(),
350
238
                )),
351
238
                network_provider: Arc::new(network.clone()),
352
238
                is_validator: role.is_authority(),
353
238
                enable_http_requests: false,
354
6209
                custom_extensions: move |_| vec![],
355
238
            })
356
238
            .run(client.clone(), task_manager.spawn_handle())
357
238
            .boxed(),
358
238
        );
359
238
    }
360

            
361
238
    let mut command_sink = None;
362
238

            
363
238
    if role.is_authority() {
364
238
        let proposer = sc_basic_authorship::ProposerFactory::new(
365
238
            task_manager.spawn_handle(),
366
238
            client.clone(),
367
238
            transaction_pool.clone(),
368
238
            prometheus_registry.as_ref(),
369
238
            telemetry.as_ref().map(|x| x.handle()),
370
238
        );
371

            
372
238
        let commands_stream: Box<
373
238
            dyn Stream<Item = EngineCommand<<Block as BlockT>::Hash>> + Send + Sync + Unpin,
374
238
        > = match sealing {
375
            Sealing::Instant => {
376
                Box::new(
377
                    // This bit cribbed from the implementation of instant seal.
378
                    transaction_pool
379
                        .pool()
380
                        .validated_pool()
381
                        .import_notification_stream()
382
                        .map(|_| EngineCommand::SealNewBlock {
383
                            create_empty: false,
384
                            finalize: false,
385
                            parent_hash: None,
386
                            sender: None,
387
                        }),
388
                )
389
            }
390
            Sealing::Manual => {
391
238
                let (sink, stream) = futures::channel::mpsc::channel(1000);
392
238
                // Keep a reference to the other end of the channel. It goes to the RPC.
393
238
                command_sink = Some(sink);
394
238
                Box::new(stream)
395
            }
396
            Sealing::Interval(millis) => Box::new(StreamExt::map(
397
                Timer::interval(Duration::from_millis(millis)),
398
                |_| EngineCommand::SealNewBlock {
399
                    create_empty: true,
400
                    finalize: true,
401
                    parent_hash: None,
402
                    sender: None,
403
                },
404
            )),
405
        };
406

            
407
238
        let babe_config = babe_link.config();
408
238
        let babe_consensus_provider = BabeConsensusDataProvider::new(
409
238
            client.clone(),
410
238
            keystore,
411
238
            babe_link.epoch_changes().clone(),
412
238
            babe_config.authorities.clone(),
413
238
        )
414
238
        .map_err(|babe_error| {
415
            Error::Consensus(consensus_common::Error::Other(babe_error.into()))
416
238
        })?;
417

            
418
        // Need to clone it and store here to avoid moving of `client`
419
        // variable in closure below.
420
238
        let client_clone = client.clone();
421
238
        task_manager.spawn_essential_handle().spawn_blocking(
422
238
            "authorship_task",
423
238
            Some("block-authoring"),
424
238
            run_manual_seal(ManualSealParams {
425
238
                block_import,
426
238
                env: proposer,
427
238
                client: client.clone(),
428
238
                pool: transaction_pool.clone(),
429
238
                commands_stream,
430
238
                select_chain,
431
6209
                create_inherent_data_providers: move |parent, ()| {
432
6209
                    let client_clone = client_clone.clone();
433

            
434
6209
                    async move {
435
6209
                        let parachain =
436
6209
                            EmptyParachainsInherentDataProvider::new(
437
6209
                                client_clone.clone(),
438
6209
                                parent,
439
6209
                            );
440
6209

            
441
6209
                        let timestamp = get_next_timestamp(client_clone, slot_duration);
442
6209

            
443
6209
                        let slot =
444
6209
                            sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
445
6209
                                *timestamp,
446
6209
                                slot_duration,
447
6209
                            );
448
6209

            
449
6209
                        Ok((slot, timestamp, parachain))
450
6209
                    }
451
6209
                },
452
238
                consensus_data_provider: Some(Box::new(babe_consensus_provider)),
453
238
            }),
454
238
        );
455
238
    }
456

            
457
238
    let rpc_extensions_builder = {
458
238
        let client = client.clone();
459
238
        let transaction_pool = transaction_pool.clone();
460
238
        let chain_spec = config.chain_spec.cloned_box();
461

            
462
        move |deny_unsafe,
463
              _subscription_executor: polkadot_rpc::SubscriptionTaskExecutor|
464
476
              -> Result<RpcExtension, service::Error> {
465
476
            let deps = DevDeps {
466
476
                client: client.clone(),
467
476
                pool: transaction_pool.clone(),
468
476
                chain_spec: chain_spec.cloned_box(),
469
476
                deny_unsafe,
470
476
                command_sink: command_sink.clone(),
471
476
            };
472
476

            
473
476
            create_dev_rpc_extension(deps).map_err(Into::into)
474
476
        }
475
    };
476

            
477
238
    let rpc_handlers = service::spawn_tasks(service::SpawnTasksParams {
478
238
        config,
479
238
        backend: backend.clone(),
480
238
        client: client.clone(),
481
238
        keystore: keystore_container.keystore(),
482
238
        network: network.clone(),
483
238
        sync_service: sync_service.clone(),
484
238
        rpc_builder: Box::new(rpc_extensions_builder),
485
238
        transaction_pool: transaction_pool.clone(),
486
238
        task_manager: &mut task_manager,
487
238
        system_rpc_tx,
488
238
        tx_handler_controller,
489
238
        telemetry: telemetry.as_mut(),
490
238
    })?;
491

            
492
238
    network_starter.start_network();
493
238

            
494
238
    Ok(NewFull {
495
238
        task_manager,
496
238
        client,
497
238
        overseer_handle: None,
498
238
        network,
499
238
        sync_service,
500
238
        rpc_handlers,
501
238
        backend,
502
238
    })
503
238
}
504

            
505
238
fn new_partial<ChainSelection>(
506
238
    config: &mut Configuration,
507
238
    Basics {
508
238
        task_manager,
509
238
        backend,
510
238
        client,
511
238
        keystore_container,
512
238
        telemetry,
513
238
    }: Basics,
514
238
    select_chain: ChainSelection,
515
238
) -> Result<
516
238
    service::PartialComponents<
517
238
        FullClient,
518
238
        FullBackend,
519
238
        ChainSelection,
520
238
        sc_consensus::DefaultImportQueue<Block>,
521
238
        sc_transaction_pool::FullPool<Block, FullClient>,
522
238
        (
523
238
            BabeBlockImport<Block, FullClient, Arc<FullClient>>,
524
238
            BabeLink<Block>,
525
238
            SlotDuration,
526
238
            Option<Telemetry>,
527
238
        ),
528
238
    >,
529
238
    Error,
530
238
>
531
238
where
532
238
    ChainSelection: 'static + SelectChain<Block>,
533
238
{
534
238
    let transaction_pool = sc_transaction_pool::BasicPool::new_full(
535
238
        config.transaction_pool.clone(),
536
238
        config.role.is_authority().into(),
537
238
        config.prometheus_registry(),
538
238
        task_manager.spawn_essential_handle(),
539
238
        client.clone(),
540
238
    );
541

            
542
    // Create babe block import queue; this is required to have correct epoch data
543
    // available for manual seal to produce block
544
238
    let babe_config = babe::configuration(&*client)?;
545
238
    let (babe_block_import, babe_link) =
546
238
        babe::block_import(babe_config.clone(), client.clone(), client.clone())?;
547
238
    let slot_duration = babe_link.config().slot_duration();
548
238

            
549
238
    // Create manual seal block import with manual seal block import queue
550
238
    let import_queue = sc_consensus_manual_seal::import_queue(
551
238
        Box::new(babe_block_import.clone()),
552
238
        &task_manager.spawn_essential_handle(),
553
238
        config.prometheus_registry(),
554
238
    );
555
238

            
556
238
    Ok(service::PartialComponents {
557
238
        client,
558
238
        backend,
559
238
        task_manager,
560
238
        keystore_container,
561
238
        select_chain,
562
238
        import_queue,
563
238
        transaction_pool,
564
238
        other: (babe_block_import, babe_link, slot_duration, telemetry),
565
238
    })
566
238
}
567

            
568
238
fn new_partial_basics(
569
238
    config: &mut Configuration,
570
238
    telemetry_worker_handle: Option<TelemetryWorkerHandle>,
571
238
) -> Result<Basics, Error> {
572
238
    let telemetry = config
573
238
        .telemetry_endpoints
574
238
        .clone()
575
238
        .filter(|x| !x.is_empty())
576
238
        .map(move |endpoints| -> Result<_, telemetry::Error> {
577
            let (worker, mut worker_handle) = if let Some(worker_handle) = telemetry_worker_handle {
578
                (None, worker_handle)
579
            } else {
580
                let worker = TelemetryWorker::new(16)?;
581
                let worker_handle = worker.handle();
582
                (Some(worker), worker_handle)
583
            };
584
            let telemetry = worker_handle.new_telemetry(endpoints);
585
            Ok((worker, telemetry))
586
238
        })
587
238
        .transpose()?;
588

            
589
238
    let heap_pages = config
590
238
        .default_heap_pages
591
238
        .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
592
            extra_pages: h as u32,
593
238
        });
594
238

            
595
238
    let executor = WasmExecutor::builder()
596
238
        .with_execution_method(config.wasm_method)
597
238
        .with_onchain_heap_alloc_strategy(heap_pages)
598
238
        .with_offchain_heap_alloc_strategy(heap_pages)
599
238
        .with_max_runtime_instances(config.max_runtime_instances)
600
238
        .with_runtime_cache_size(config.runtime_cache_size)
601
238
        .build();
602

            
603
238
    let (client, backend, keystore_container, task_manager) =
604
238
        service::new_full_parts::<Block, RuntimeApi, _>(
605
238
            config,
606
238
            telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
607
238
            executor,
608
238
        )?;
609
238
    let client = Arc::new(client);
610
238

            
611
238
    let telemetry = telemetry.map(|(worker, telemetry)| {
612
        if let Some(worker) = worker {
613
            task_manager.spawn_handle().spawn(
614
                "telemetry",
615
                Some("telemetry"),
616
                Box::pin(worker.run()),
617
            );
618
        }
619
        telemetry
620
238
    });
621
238

            
622
238
    Ok(Basics {
623
238
        task_manager,
624
238
        client,
625
238
        backend,
626
238
        keystore_container,
627
238
        telemetry,
628
238
    })
629
238
}