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
    crate::dev_rpcs::{DevApiServer, DevRpc},
35
    async_io::Timer,
36
    babe::{BabeBlockImport, BabeLink},
37
    codec::{Decode, Encode},
38
    consensus_common::SelectChain,
39
    cumulus_primitives_core::ParaId,
40
    dancelight_runtime::RuntimeApi,
41
    futures::{Stream, StreamExt},
42
    jsonrpsee::RpcModule,
43
    manual_container_chains_exclusion_rpc::{
44
        ManualContainerChainsExclusion, ManualContainerChainsExclusionApiServer,
45
    },
46
    node_common::service::node_builder::Sealing,
47
    polkadot_core_primitives::{AccountId, Balance, Block, Hash, Nonce},
48
    polkadot_node_core_parachains_inherent::Error as InherentError,
49
    polkadot_overseer::Handle,
50
    polkadot_parachain_primitives::primitives::UpwardMessages,
51
    polkadot_primitives::{
52
        runtime_api::ParachainHost, BackedCandidate, CandidateCommitments, CandidateDescriptor,
53
        CollatorPair, CommittedCandidateReceipt, CompactStatement, EncodeAs,
54
        InherentData as ParachainsInherentData, OccupiedCoreAssumption, SigningContext,
55
        ValidityAttestation,
56
    },
57
    polkadot_rpc::RpcExtension,
58
    polkadot_service::{
59
        BlockT, Error, IdentifyVariant, NewFullParams, OverseerGen, SelectRelayChain,
60
    },
61
    sc_client_api::{AuxStore, Backend},
62
    sc_consensus_manual_seal::{
63
        consensus::babe::BabeConsensusDataProvider,
64
        rpc::{ManualSeal, ManualSealApiServer},
65
        run_manual_seal, EngineCommand, ManualSealParams,
66
    },
67
    sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY},
68
    sc_keystore::Keystore,
69
    sc_transaction_pool_api::{OffchainTransactionPoolFactory, TransactionPool},
70
    service::{Configuration, KeystoreContainer, RpcHandlers, TaskManager},
71
    sp_api::ProvideRuntimeApi,
72
    sp_block_builder::BlockBuilder,
73
    sp_blockchain::{HeaderBackend, HeaderMetadata},
74
    sp_consensus_aura::{inherents::InherentType as AuraInherentType, AURA_ENGINE_ID},
75
    sp_consensus_babe::SlotDuration,
76
    sp_core::{ByteArray, Pair, H256},
77
    sp_keystore::KeystorePtr,
78
    sp_runtime::{traits::BlakeTwo256, DigestItem, RuntimeAppPublic},
79
    std::{cmp::max, ops::Add, sync::Arc, time::Duration},
80
    telemetry::{Telemetry, TelemetryWorker, TelemetryWorkerHandle},
81
};
82

            
83
// We use this key to store whether we want the para inherent mocker to be active
84
const PARA_INHERENT_SELECTOR_AUX_KEY: &[u8] = b"__DEV_PARA_INHERENT_SELECTOR";
85

            
86
const CONTAINER_CHAINS_EXCLUSION_AUX_KEY: &[u8] = b"__DEV_CONTAINER_CHAINS_EXCLUSION";
87

            
88
pub type FullBackend = service::TFullBackend<Block>;
89

            
90
pub type FullClient = service::TFullClient<
91
    Block,
92
    RuntimeApi,
93
    WasmExecutor<(
94
        sp_io::SubstrateHostFunctions,
95
        frame_benchmarking::benchmarking::HostFunctions,
96
    )>,
97
>;
98

            
99
pub struct NewFull {
100
    pub task_manager: TaskManager,
101
    pub client: Arc<FullClient>,
102
    pub overseer_handle: Option<Handle>,
103
    pub network: Arc<dyn sc_network::service::traits::NetworkService>,
104
    pub sync_service: Arc<sc_network_sync::SyncingService<Block>>,
105
    pub rpc_handlers: RpcHandlers,
106
    pub backend: Arc<FullBackend>,
107
}
108

            
109
/// Custom Deps for dev Rpc extension
110
struct DevDeps<C, P> {
111
    /// The client instance to use.
112
    pub client: Arc<C>,
113
    /// Transaction pool instance.
114
    pub pool: Arc<P>,
115
    /// Manual seal command sink
116
    pub command_sink: Option<futures::channel::mpsc::Sender<EngineCommand<Hash>>>,
117
    /// Dev rpcs
118
    pub dev_rpc: Option<DevRpc>,
119
    /// Channels for manually excluding container chains from producing blocks
120
    pub container_chain_exclusion_sender: Option<flume::Sender<Vec<ParaId>>>,
121
}
122

            
123
2328
fn create_dev_rpc_extension<C, P>(
124
2328
    DevDeps {
125
2328
        client,
126
2328
        pool,
127
2328
        command_sink: maybe_command_sink,
128
2328
        dev_rpc: maybe_dev_rpc,
129
2328
        container_chain_exclusion_sender: maybe_container_chain_exclusion_sender,
130
2328
    }: DevDeps<C, P>,
131
2328
) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>>
132
2328
where
133
2328
    C: ProvideRuntimeApi<Block>
134
2328
        + HeaderBackend<Block>
135
2328
        + AuxStore
136
2328
        + HeaderMetadata<Block, Error = sp_blockchain::Error>
137
2328
        + Send
138
2328
        + Sync
139
2328
        + 'static,
140
2328
    C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
141
2328
    C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
142
2328
    C::Api: BlockBuilder<Block>,
143
2328
    P: TransactionPool + Sync + Send + 'static,
144
2328
{
145
    use {
146
        pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer},
147
        substrate_frame_rpc_system::{System, SystemApiServer},
148
    };
149

            
150
2328
    let mut io = RpcModule::new(());
151
2328
    io.merge(System::new(client.clone(), pool.clone()).into_rpc())?;
152
2328
    io.merge(TransactionPayment::new(client.clone()).into_rpc())?;
153

            
154
2328
    if let Some(command_sink) = maybe_command_sink {
155
2328
        io.merge(ManualSeal::new(command_sink).into_rpc())?;
156
    }
157

            
158
2328
    if let Some(dev_rpc_data) = maybe_dev_rpc {
159
2328
        io.merge(dev_rpc_data.into_rpc())?;
160
    }
161

            
162
2328
    if let Some(container_chain_exclusion_message_channel) = maybe_container_chain_exclusion_sender
163
    {
164
2328
        io.merge(
165
2328
            ManualContainerChainsExclusion {
166
2328
                container_chain_exclusion_message_channel,
167
2328
            }
168
2328
            .into_rpc(),
169
2328
        )?;
170
    }
171

            
172
2328
    Ok(io)
173
2328
}
174

            
175
/// We use EmptyParachainsInherentDataProvider to insert an empty parachain inherent in the block
176
/// to satisfy runtime
177
struct EmptyParachainsInherentDataProvider;
178

            
179
/// Copied from polkadot service just so that this code retains same structure as
180
/// polkadot_service crate.
181
struct Basics {
182
    task_manager: TaskManager,
183
    client: Arc<FullClient>,
184
    backend: Arc<FullBackend>,
185
    keystore_container: KeystoreContainer,
186
    telemetry: Option<Telemetry>,
187
}
188

            
189
impl EmptyParachainsInherentDataProvider {
190
64482
    pub async fn create<C: HeaderBackend<Block>>(
191
64482
        client: Arc<C>,
192
64482
        parent: Hash,
193
64482
    ) -> Result<ParachainsInherentData, InherentError> {
194
64482
        let parent_header = match client.header(parent) {
195
64482
            Ok(Some(h)) => h,
196
            Ok(None) => return Err(InherentError::ParentHeaderNotFound(parent)),
197
            Err(err) => return Err(InherentError::Blockchain(err)),
198
        };
199

            
200
64482
        Ok(ParachainsInherentData {
201
64482
            bitfields: Vec::new(),
202
64482
            backed_candidates: Vec::new(),
203
64482
            disputes: Vec::new(),
204
64482
            parent_header,
205
64482
        })
206
64482
    }
207
}
208

            
209
/// Creates new development full node with manual seal
210
1164
pub fn build_full<OverseerGenerator: OverseerGen>(
211
1164
    sealing: Sealing,
212
1164
    config: Configuration,
213
1164
    mut params: NewFullParams<OverseerGenerator>,
214
1164
) -> Result<NewFull, Error> {
215
1164
    let is_polkadot = config.chain_spec.is_polkadot();
216
1164

            
217
1164
    params.overseer_message_channel_capacity_override = params
218
1164
        .overseer_message_channel_capacity_override
219
1164
        .map(move |capacity| {
220
            if is_polkadot {
221
                gum::warn!("Channel capacity should _never_ be tampered with on polkadot!");
222
            }
223
            capacity
224
1164
        });
225
1164

            
226
1164
    match config
227
1164
        .network
228
1164
        .network_backend
229
1164
        .unwrap_or(sc_network::config::NetworkBackendType::Libp2p)
230
    {
231
        sc_network::config::NetworkBackendType::Libp2p => {
232
1164
            new_full::<_, sc_network::NetworkWorker<Block, Hash>>(sealing, config, params)
233
        }
234
        sc_network::config::NetworkBackendType::Litep2p => {
235
            new_full::<_, sc_network::Litep2pNetworkBackend>(sealing, config, params)
236
        }
237
    }
238
1164
}
239

            
240
/// We use MockParachainsInherentDataProvider to insert an parachain inherent with mocked
241
/// candidates
242
/// We detect whether any of the keys in our keystore is assigned to a core and provide
243
/// a mocked candidate in such core
244
struct MockParachainsInherentDataProvider<C: HeaderBackend<Block> + ProvideRuntimeApi<Block>> {
245
    pub client: Arc<C>,
246
    pub parent: Hash,
247
    pub keystore: KeystorePtr,
248
    pub upward_messages_receiver: flume::Receiver<Vec<u8>>,
249
    pub container_chain_exclusion_receiver: flume::Receiver<Vec<ParaId>>,
250
}
251

            
252
impl<C: HeaderBackend<Block> + ProvideRuntimeApi<Block>> MockParachainsInherentDataProvider<C>
253
where
254
    C::Api: ParachainHost<Block>,
255
    C: AuxStore,
256
{
257
80646
    pub fn new(
258
80646
        client: Arc<C>,
259
80646
        parent: Hash,
260
80646
        keystore: KeystorePtr,
261
80646
        upward_messages_receiver: flume::Receiver<Vec<u8>>,
262
80646
        container_chain_exclusion_receiver: flume::Receiver<Vec<ParaId>>,
263
80646
    ) -> Self {
264
80646
        MockParachainsInherentDataProvider {
265
80646
            client,
266
80646
            parent,
267
80646
            keystore,
268
80646
            upward_messages_receiver,
269
80646
            container_chain_exclusion_receiver,
270
80646
        }
271
80646
    }
272

            
273
16164
    pub async fn create(
274
16164
        client: Arc<C>,
275
16164
        parent: Hash,
276
16164
        keystore: KeystorePtr,
277
16164
        upward_messages_receiver: flume::Receiver<Vec<u8>>,
278
16164
        container_chains_exclusion_receiver: flume::Receiver<Vec<ParaId>>,
279
16164
    ) -> Result<ParachainsInherentData, InherentError> {
280
16164
        let parent_header = match client.header(parent) {
281
16164
            Ok(Some(h)) => h,
282
            Ok(None) => return Err(InherentError::ParentHeaderNotFound(parent)),
283
            Err(err) => return Err(InherentError::Blockchain(err)),
284
        };
285

            
286
        // Strategy:
287
        // we usually have 1 validator per core, and we usually run with --alice
288
        // the idea is that at least alice will be assigned to one core
289
        // if we find in the keystore the validator attached to a particular core,
290
        // we generate a signature for the parachain assigned to that core
291
        // To retrieve the validator keys, cal runtime api:
292

            
293
        // this following piece of code predicts whether the validator is assigned to a particular
294
        // core where a candidate for a parachain needs to be created
295
16164
        let runtime_api = client.runtime_api();
296
16164

            
297
16164
        // we get all validators
298
16164

            
299
16164
        // we get the current claim queue to know core availability
300
16164
        let claim_queue = runtime_api.claim_queue(parent).unwrap();
301
16164

            
302
16164
        // we get the validator groups
303
16164
        let (groups, rotation_info) = runtime_api.validator_groups(parent).unwrap();
304
16164

            
305
16164
        // we calculate rotation since start, which will define the core assignation
306
16164
        // to validators
307
16164
        let rotations_since_session_start = (parent_header.number
308
16164
            - rotation_info.session_start_block)
309
16164
            / rotation_info.group_rotation_frequency;
310
16164

            
311
16164
        // Get all the available keys in the keystore
312
16164
        let available_keys = keystore
313
16164
            .keys(polkadot_primitives::PARACHAIN_KEY_TYPE_ID)
314
16164
            .unwrap();
315
16164

            
316
16164
        // create a slot number identical to the parent block num
317
16164
        let slot_number = AuraInherentType::from(u64::from(parent_header.number));
318
16164

            
319
16164
        // create a mocked header
320
16164
        let parachain_mocked_header = sp_runtime::generic::Header::<u32, BlakeTwo256> {
321
16164
            parent_hash: Default::default(),
322
16164
            number: parent_header.number,
323
16164
            state_root: Default::default(),
324
16164
            extrinsics_root: Default::default(),
325
16164
            digest: sp_runtime::generic::Digest {
326
16164
                logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot_number.encode())],
327
16164
            },
328
16164
        };
329
16164

            
330
16164
        // retrieve availability cores
331
16164
        let availability_cores = runtime_api.availability_cores(parent).unwrap();
332
16164

            
333
16164
        // retrieve current session_idx
334
16164
        let session_idx = runtime_api.session_index_for_child(parent).unwrap();
335
16164

            
336
16164
        // retrieve all validators
337
16164
        let all_validators = runtime_api.validators(parent).unwrap();
338
16164

            
339
16164
        // construct full availability bitvec
340
16164
        let availability_bitvec = availability_bitvec(1, availability_cores.len());
341
16164

            
342
16164
        let signature_ctx = SigningContext {
343
16164
            parent_hash: parent,
344
16164
            session_index: session_idx,
345
16164
        };
346
16164

            
347
16164
        // we generate the availability bitfield sigs
348
16164
        // TODO: here we assume all validator keys are able to sign with our keystore
349
16164
        // we need to make sure the key is there before we try to sign
350
16164
        // this is mostly to indicate that the erasure coding chunks where received by all val
351
16164
        let bitfields: Vec<UncheckedSigned<AvailabilityBitfield>> = all_validators
352
16164
            .iter()
353
16164
            .enumerate()
354
16164
            .map(|(i, public)| {
355
16164
                keystore_sign(
356
16164
                    &keystore,
357
16164
                    availability_bitvec.clone(),
358
16164
                    &signature_ctx,
359
16164
                    ValidatorIndex(i as u32),
360
16164
                    public,
361
16164
                )
362
16164
                .unwrap()
363
16164
                .unwrap()
364
16164
            })
365
16164
            .collect();
366
16164

            
367
16164
        // generate a random collator pair
368
16164
        let collator_pair = CollatorPair::generate().0;
369
16164
        let mut backed_cand: Vec<BackedCandidate<H256>> = vec![];
370
16164

            
371
16164
        let container_chains_exclusion_messages: Vec<Vec<ParaId>> =
372
16164
            container_chains_exclusion_receiver.drain().collect();
373
        // If there is a new set of excluded container chains, we update it
374
16164
        if let Some(mock_excluded_container_chains) = container_chains_exclusion_messages.last() {
375
            client
376
                .insert_aux(
377
                    &[(
378
                        CONTAINER_CHAINS_EXCLUSION_AUX_KEY,
379
                        mock_excluded_container_chains.encode().as_slice(),
380
                    )],
381
                    &[],
382
                )
383
                .expect("Should be able to write to aux storage; qed");
384
16164
        }
385
16164
        let new_excluded_container_chains_value = client
386
16164
            .get_aux(CONTAINER_CHAINS_EXCLUSION_AUX_KEY)
387
16164
            .expect("Should be able to query aux storage; qed")
388
16164
            .unwrap_or(Vec::<ParaId>::new().encode());
389
16164
        let mock_excluded_container_chains: Vec<ParaId> =
390
16164
            Decode::decode(&mut new_excluded_container_chains_value.as_slice())
391
16164
                .expect("Vector non-decodable");
392

            
393
        // iterate over every core|para pair
394
45144
        for (core, para) in claim_queue {
395
            // allows preventing container chains from producing blocks in dev mode
396
28980
            let mut para = para.clone();
397
57936
            para.retain(|x| !mock_excluded_container_chains.contains(x));
398
28980
            // check which group is assigned to each core
399
28980
            let group_assigned_to_core =
400
28980
                core.0 + rotations_since_session_start % groups.len() as u32;
401
28980
            // check validator indices associated to the core
402
28980
            let indices_associated_to_core = groups.get(group_assigned_to_core as usize).unwrap();
403
43638
            for index in indices_associated_to_core {
404
                // fetch validator keys
405
14658
                let validator_keys_to_find = all_validators.get(index.0 as usize).unwrap();
406
                // Iterate keys until we find an eligible one, or run out of candidates.
407
29316
                for type_public_pair in &available_keys {
408
14658
                    if let Ok(validator) =
409
14658
                        polkadot_primitives::ValidatorId::from_slice(type_public_pair)
410
                    {
411
                        // if we find the validator in keystore, we try to create a backed cand
412
14658
                        if validator_keys_to_find == &validator {
413
14658
                            // we work with the previous included data
414
14658
                            let mut persisted_validation_data = runtime_api
415
14658
                                .persisted_validation_data(
416
14658
                                    parent,
417
14658
                                    para[0],
418
14658
                                    OccupiedCoreAssumption::Included,
419
14658
                                )
420
14658
                                .unwrap()
421
14658
                                .unwrap();
422
14658

            
423
14658
                            // if we dont do this we have a backed candidate every 2 blocks
424
14658
                            // we want
425
14658
                            persisted_validation_data.relay_parent_storage_root =
426
14658
                                parent_header.state_root;
427
14658

            
428
14658
                            let persisted_validation_data_hash = persisted_validation_data.hash();
429
14658
                            // retrieve the validation code hash
430
14658
                            let validation_code_hash = runtime_api
431
14658
                                .validation_code_hash(
432
14658
                                    parent,
433
14658
                                    para[0],
434
14658
                                    OccupiedCoreAssumption::Included,
435
14658
                                )
436
14658
                                .unwrap()
437
14658
                                .unwrap();
438
14658
                            let pov_hash = Default::default();
439
14658
                            // generate a fake collator signature
440
14658
                            let payload = polkadot_primitives::collator_signature_payload(
441
14658
                                &parent,
442
14658
                                &para[0],
443
14658
                                &persisted_validation_data_hash,
444
14658
                                &pov_hash,
445
14658
                                &validation_code_hash,
446
14658
                            );
447
14658
                            let collator_signature = collator_pair.sign(&payload);
448
14658

            
449
14658
                            let upward_messages = UpwardMessages::try_from(
450
14658
                                upward_messages_receiver.drain().collect::<Vec<_>>(),
451
14658
                            )
452
14658
                            .expect("create upward messages from raw messages");
453
14658

            
454
14658
                            // generate a candidate with most of the values mocked
455
14658
                            let candidate = CommittedCandidateReceipt::<H256> {
456
14658
                                descriptor: CandidateDescriptor::<H256> {
457
14658
                                    para_id: para[0],
458
14658
                                    relay_parent: parent,
459
14658
                                    collator: collator_pair.public(),
460
14658
                                    persisted_validation_data_hash,
461
14658
                                    pov_hash,
462
14658
                                    erasure_root: Default::default(),
463
14658
                                    signature: collator_signature,
464
14658
                                    para_head: parachain_mocked_header.clone().hash(),
465
14658
                                    validation_code_hash,
466
14658
                                },
467
14658
                                commitments: CandidateCommitments::<u32> {
468
14658
                                    upward_messages,
469
14658
                                    horizontal_messages: Default::default(),
470
14658
                                    new_validation_code: None,
471
14658
                                    head_data: parachain_mocked_header.clone().encode().into(),
472
14658
                                    processed_downward_messages: 0,
473
14658
                                    hrmp_watermark: parent_header.number,
474
14658
                                },
475
14658
                            };
476
14658
                            let candidate_hash = candidate.hash();
477
14658
                            let payload = CompactStatement::Valid(candidate_hash);
478
14658

            
479
14658
                            let signature_ctx = SigningContext {
480
14658
                                parent_hash: parent,
481
14658
                                session_index: session_idx,
482
14658
                            };
483
14658

            
484
14658
                            // sign the candidate with the validator key
485
14658
                            let signature = keystore_sign(
486
14658
                                &keystore,
487
14658
                                payload,
488
14658
                                &signature_ctx,
489
14658
                                *index,
490
14658
                                &validator,
491
14658
                            )
492
14658
                            .unwrap()
493
14658
                            .unwrap()
494
14658
                            .benchmark_signature();
495
14658

            
496
14658
                            // construct a validity vote
497
14658
                            let validity_votes = vec![ValidityAttestation::Explicit(signature)];
498
14658

            
499
14658
                            // push the candidate
500
14658
                            backed_cand.push(BackedCandidate::<H256>::new(
501
14658
                                candidate,
502
14658
                                validity_votes.clone(),
503
14658
                                bitvec::bitvec![u8, bitvec::order::Lsb0; 1; indices_associated_to_core.len()],
504
14658
                                core,
505
14658
                            ));
506
14658
                        }
507
                    }
508
                }
509
            }
510
        }
511

            
512
16164
        Ok(ParachainsInherentData {
513
16164
            bitfields,
514
16164
            backed_candidates: backed_cand,
515
16164
            disputes: Vec::new(),
516
16164
            parent_header,
517
16164
        })
518
16164
    }
519
}
520

            
521
#[async_trait::async_trait]
522
impl<C: HeaderBackend<Block> + ProvideRuntimeApi<Block>> sp_inherents::InherentDataProvider
523
    for MockParachainsInherentDataProvider<C>
524
where
525
    C::Api: ParachainHost<Block>,
526
    C: AuxStore,
527
{
528
    async fn provide_inherent_data(
529
        &self,
530
        dst_inherent_data: &mut sp_inherents::InherentData,
531
80646
    ) -> Result<(), sp_inherents::Error> {
532
        // fetch whether the para inherent selector has been set
533
80646
        let maybe_para_selector = self
534
80646
            .client
535
80646
            .get_aux(PARA_INHERENT_SELECTOR_AUX_KEY)
536
80646
            .expect("Should be able to query aux storage; qed");
537

            
538
80646
        let inherent_data = {
539
80646
            if let Some(aux) = maybe_para_selector {
540
                // if it is true, the candidates need to be mocked
541
                // else, we output the empty parachain inherent data provider
542
16164
                if aux == true.encode() {
543
16164
                    MockParachainsInherentDataProvider::create(
544
16164
                        self.client.clone(),
545
16164
                        self.parent,
546
16164
                        self.keystore.clone(),
547
16164
                        self.upward_messages_receiver.clone(),
548
16164
                        self.container_chain_exclusion_receiver.clone(),
549
16164
                    )
550
16164
                    .await
551
16164
                    .map_err(|e| sp_inherents::Error::Application(Box::new(e)))?
552
                } else {
553
                    EmptyParachainsInherentDataProvider::create(self.client.clone(), self.parent)
554
                        .await
555
                        .map_err(|e| sp_inherents::Error::Application(Box::new(e)))?
556
                }
557
            } else {
558
64482
                EmptyParachainsInherentDataProvider::create(self.client.clone(), self.parent)
559
64482
                    .await
560
64482
                    .map_err(|e| sp_inherents::Error::Application(Box::new(e)))?
561
            }
562
        };
563

            
564
80646
        dst_inherent_data.put_data(
565
80646
            polkadot_primitives::PARACHAINS_INHERENT_IDENTIFIER,
566
80646
            &inherent_data,
567
80646
        )
568
161292
    }
569

            
570
    async fn try_handle_error(
571
        &self,
572
        _identifier: &sp_inherents::InherentIdentifier,
573
        _error: &[u8],
574
    ) -> Option<Result<(), sp_inherents::Error>> {
575
        // Inherent isn't checked and can not return any error
576
        None
577
    }
578
}
579

            
580
/// We store past timestamp we created in the aux storage, which enable us to return timestamp which is increased by
581
/// slot duration from previous timestamp or current timestamp if in reality more time is passed.
582
80646
fn get_next_timestamp(
583
80646
    client: Arc<FullClient>,
584
80646
    slot_duration: SlotDuration,
585
80646
) -> sp_timestamp::InherentDataProvider {
586
    const TIMESTAMP_AUX_KEY: &[u8] = b"__DEV_TIMESTAMP";
587

            
588
80646
    let maybe_last_timestamp = client
589
80646
        .get_aux(TIMESTAMP_AUX_KEY)
590
80646
        .expect("Should be able to query aux storage; qed");
591
80646
    if let Some(last_timestamp) = maybe_last_timestamp {
592
79632
        let last_inherent_data = sp_timestamp::InherentType::decode(&mut last_timestamp.as_slice())
593
79632
            .expect("Timestamp data must be decoded; qed");
594
79632
        let new_inherent_data: sp_timestamp::InherentType = max(
595
79632
            last_inherent_data.add(slot_duration.as_millis()),
596
79632
            sp_timestamp::InherentType::current(),
597
79632
        );
598
79632
        client
599
79632
            .insert_aux(
600
79632
                &[(TIMESTAMP_AUX_KEY, new_inherent_data.encode().as_slice())],
601
79632
                &[],
602
79632
            )
603
79632
            .expect("Should be able to write to aux storage; qed");
604
79632
        sp_timestamp::InherentDataProvider::new(new_inherent_data)
605
    } else {
606
1014
        let current_timestamp = sp_timestamp::InherentType::current();
607
1014
        client
608
1014
            .insert_aux(
609
1014
                &[(TIMESTAMP_AUX_KEY, current_timestamp.encode().as_slice())],
610
1014
                &[],
611
1014
            )
612
1014
            .expect("Should be able to write to aux storage; qed");
613
1014
        sp_timestamp::InherentDataProvider::new(current_timestamp)
614
    }
615
80646
}
616

            
617
1164
fn new_full<
618
1164
    OverseerGenerator: OverseerGen,
619
1164
    Network: sc_network::NetworkBackend<Block, <Block as BlockT>::Hash>,
620
1164
>(
621
1164
    sealing: Sealing,
622
1164
    mut config: Configuration,
623
1164
    NewFullParams {
624
1164
        telemetry_worker_handle,
625
1164
        ..
626
1164
    }: NewFullParams<OverseerGenerator>,
627
1164
) -> Result<NewFull, Error> {
628
1164
    let role = config.role;
629

            
630
1164
    let basics = new_partial_basics(&mut config, telemetry_worker_handle)?;
631

            
632
1164
    let prometheus_registry = config.prometheus_registry().cloned();
633
1164

            
634
1164
    let keystore = basics.keystore_container.local_keystore();
635
1164

            
636
1164
    let select_chain = SelectRelayChain::new_longest_chain(basics.backend.clone());
637

            
638
1164
    let service::PartialComponents::<_, _, SelectRelayChain<_>, _, _, _> {
639
1164
        client,
640
1164
        backend,
641
1164
        mut task_manager,
642
1164
        keystore_container,
643
1164
        select_chain,
644
1164
        import_queue,
645
1164
        transaction_pool,
646
1164
        other: (block_import, babe_link, slot_duration, mut telemetry),
647
1164
    } = new_partial::<SelectRelayChain<_>>(&mut config, basics, select_chain)?;
648

            
649
1164
    let metrics = Network::register_notification_metrics(
650
1164
        config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
651
1164
    );
652
1164

            
653
1164
    let net_config = sc_network::config::FullNetworkConfiguration::<_, _, Network>::new(
654
1164
        &config.network,
655
1164
        prometheus_registry.clone(),
656
1164
    );
657
1164

            
658
1164
    // Create channels for mocked parachain candidates.
659
1164
    let (downward_mock_para_inherent_sender, downward_mock_para_inherent_receiver) =
660
1164
        flume::bounded::<Vec<u8>>(100);
661
1164

            
662
1164
    let (upward_mock_sender, upward_mock_receiver) = flume::bounded::<Vec<u8>>(100);
663

            
664
1164
    let (network, system_rpc_tx, tx_handler_controller, sync_service) =
665
1164
        service::build_network(service::BuildNetworkParams {
666
1164
            config: &config,
667
1164
            net_config,
668
1164
            client: client.clone(),
669
1164
            transaction_pool: transaction_pool.clone(),
670
1164
            spawn_handle: task_manager.spawn_handle(),
671
1164
            import_queue,
672
1164
            block_announce_validator_builder: None,
673
1164
            warp_sync_config: None,
674
1164
            block_relay: None,
675
1164
            metrics,
676
1164
        })?;
677

            
678
1164
    if config.offchain_worker.enabled {
679
1164
        use futures::FutureExt;
680

            
681
1164
        task_manager.spawn_handle().spawn(
682
1164
            "offchain-workers-runner",
683
1164
            "offchain-work",
684
1164
            sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
685
1164
                runtime_api_provider: client.clone(),
686
1164
                keystore: Some(keystore_container.keystore()),
687
1164
                offchain_db: backend.offchain_storage(),
688
1164
                transaction_pool: Some(OffchainTransactionPoolFactory::new(
689
1164
                    transaction_pool.clone(),
690
1164
                )),
691
1164
                network_provider: Arc::new(network.clone()),
692
1164
                is_validator: role.is_authority(),
693
1164
                enable_http_requests: false,
694
80646
                custom_extensions: move |_| vec![],
695
1164
            })?
696
1164
            .run(client.clone(), task_manager.spawn_handle())
697
1164
            .boxed(),
698
        );
699
    }
700

            
701
1164
    let mut command_sink = None;
702
1164
    let mut container_chain_exclusion_sender = None;
703
1164

            
704
1164
    if role.is_authority() {
705
1164
        let proposer = sc_basic_authorship::ProposerFactory::with_proof_recording(
706
1164
            task_manager.spawn_handle(),
707
1164
            client.clone(),
708
1164
            transaction_pool.clone(),
709
1164
            prometheus_registry.as_ref(),
710
1164
            telemetry.as_ref().map(|x| x.handle()),
711
1164
        );
712

            
713
1164
        let commands_stream: Box<
714
1164
            dyn Stream<Item = EngineCommand<<Block as BlockT>::Hash>> + Send + Sync + Unpin,
715
1164
        > = match sealing {
716
            Sealing::Instant => {
717
                Box::new(
718
                    // This bit cribbed from the implementation of instant seal.
719
                    transaction_pool.import_notification_stream().map(|_| {
720
                        EngineCommand::SealNewBlock {
721
                            create_empty: false,
722
                            finalize: false,
723
                            parent_hash: None,
724
                            sender: None,
725
                        }
726
                    }),
727
                )
728
            }
729
            Sealing::Manual => {
730
1164
                let (sink, stream) = futures::channel::mpsc::channel(1000);
731
1164
                // Keep a reference to the other end of the channel. It goes to the RPC.
732
1164
                command_sink = Some(sink);
733
1164
                Box::new(stream)
734
            }
735
            Sealing::Interval(millis) => Box::new(StreamExt::map(
736
                Timer::interval(Duration::from_millis(millis)),
737
                |_| EngineCommand::SealNewBlock {
738
                    create_empty: true,
739
                    finalize: true,
740
                    parent_hash: None,
741
                    sender: None,
742
                },
743
            )),
744
        };
745
1164
        let keystore_clone = keystore.clone();
746
1164

            
747
1164
        let babe_config = babe_link.config();
748
1164
        let babe_consensus_provider = BabeConsensusDataProvider::new(
749
1164
            client.clone(),
750
1164
            keystore,
751
1164
            babe_link.epoch_changes().clone(),
752
1164
            babe_config.authorities.clone(),
753
1164
        )
754
1164
        .map_err(|babe_error| {
755
            Error::Consensus(consensus_common::Error::Other(babe_error.into()))
756
1164
        })?;
757

            
758
1164
        let (mock_container_chains_exclusion_sender, mock_container_chains_exclusion_receiver) =
759
1164
            flume::bounded::<Vec<ParaId>>(100);
760
1164
        container_chain_exclusion_sender = Some(mock_container_chains_exclusion_sender);
761
1164

            
762
1164
        // Need to clone it and store here to avoid moving of `client`
763
1164
        // variable in closure below.
764
1164
        let client_clone = client.clone();
765
1164

            
766
1164
        task_manager.spawn_essential_handle().spawn_blocking(
767
1164
            "authorship_task",
768
1164
            Some("block-authoring"),
769
1164
            run_manual_seal(ManualSealParams {
770
1164
                block_import,
771
1164
                env: proposer,
772
1164
                client: client.clone(),
773
1164
                pool: transaction_pool.clone(),
774
1164
                commands_stream,
775
1164
                select_chain,
776
80646
                create_inherent_data_providers: move |parent, ()| {
777
80646
                    let client_clone = client_clone.clone();
778
80646
                    let keystore = keystore_clone.clone();
779
80646
                    let downward_mock_para_inherent_receiver = downward_mock_para_inherent_receiver.clone();
780
80646
                    let upward_mock_receiver = upward_mock_receiver.clone();
781
80646
                    let mock_container_chains_exclusion_receiver = mock_container_chains_exclusion_receiver.clone();
782
80646
                    async move {
783
80646

            
784
80646
                        let downward_mock_para_inherent_receiver = downward_mock_para_inherent_receiver.clone();
785
80646
                        // here we only take the last one
786
80646
                        let para_inherent_decider_messages: Vec<Vec<u8>> = downward_mock_para_inherent_receiver.drain().collect();
787
80646

            
788
80646
                        let upward_messages_receiver = upward_mock_receiver.clone();
789

            
790
                        // If there is a value to be updated, we update it
791
80646
                        if let Some(value) = para_inherent_decider_messages.last() {
792
78
                            client_clone
793
78
                            .insert_aux(
794
78
                                &[(PARA_INHERENT_SELECTOR_AUX_KEY, value.as_slice())],
795
78
                                &[],
796
78
                            )
797
78
                            .expect("Should be able to write to aux storage; qed");
798
80568
                        }
799

            
800
80646
                        let parachain = MockParachainsInherentDataProvider::new(
801
80646
                            client_clone.clone(),
802
80646
                            parent,
803
80646
                            keystore,
804
80646
                            upward_messages_receiver,
805
80646
                            mock_container_chains_exclusion_receiver
806
80646
                        );
807
80646

            
808
80646
                        let timestamp = get_next_timestamp(client_clone, slot_duration);
809
80646

            
810
80646
                        let slot =
811
80646
                            sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
812
80646
                                *timestamp,
813
80646
                                slot_duration,
814
80646
                            );
815
80646

            
816
80646
                        Ok((slot, timestamp, parachain))
817
80646
                    }
818
80646
                },
819
1164
                consensus_data_provider: Some(Box::new(babe_consensus_provider)),
820
1164
            }),
821
1164
        );
822
1164
    }
823

            
824
1164
    let dev_rpc = if role.clone().is_authority() {
825
1164
        Some(DevRpc {
826
1164
            mock_para_inherent_channel: downward_mock_para_inherent_sender,
827
1164
            upward_message_channel: upward_mock_sender,
828
1164
        })
829
    } else {
830
        None
831
    };
832

            
833
1164
    let rpc_extensions_builder = {
834
1164
        let client = client.clone();
835
1164
        let transaction_pool = transaction_pool.clone();
836

            
837
        move |_subscription_executor: polkadot_rpc::SubscriptionTaskExecutor|
838
2328
            -> Result<RpcExtension, service::Error> {
839
2328
            let deps = DevDeps {
840
2328
                client: client.clone(),
841
2328
                pool: transaction_pool.clone(),
842
2328
                command_sink: command_sink.clone(),
843
2328
                dev_rpc: dev_rpc.clone(),
844
2328
                container_chain_exclusion_sender: container_chain_exclusion_sender.clone(),
845
2328
            };
846
2328

            
847
2328
            create_dev_rpc_extension(deps).map_err(Into::into)
848
2328
        }
849
    };
850

            
851
1164
    let rpc_handlers = service::spawn_tasks(service::SpawnTasksParams {
852
1164
        config,
853
1164
        backend: backend.clone(),
854
1164
        client: client.clone(),
855
1164
        keystore: keystore_container.keystore(),
856
1164
        network: network.clone(),
857
1164
        sync_service: sync_service.clone(),
858
1164
        rpc_builder: Box::new(rpc_extensions_builder),
859
1164
        transaction_pool: transaction_pool.clone(),
860
1164
        task_manager: &mut task_manager,
861
1164
        system_rpc_tx,
862
1164
        tx_handler_controller,
863
1164
        telemetry: telemetry.as_mut(),
864
1164
    })?;
865

            
866
1164
    Ok(NewFull {
867
1164
        task_manager,
868
1164
        client,
869
1164
        overseer_handle: None,
870
1164
        network,
871
1164
        sync_service,
872
1164
        rpc_handlers,
873
1164
        backend,
874
1164
    })
875
1164
}
876

            
877
1164
fn new_partial<ChainSelection>(
878
1164
    config: &mut Configuration,
879
1164
    Basics {
880
1164
        task_manager,
881
1164
        backend,
882
1164
        client,
883
1164
        keystore_container,
884
1164
        telemetry,
885
1164
    }: Basics,
886
1164
    select_chain: ChainSelection,
887
1164
) -> Result<
888
1164
    service::PartialComponents<
889
1164
        FullClient,
890
1164
        FullBackend,
891
1164
        ChainSelection,
892
1164
        sc_consensus::DefaultImportQueue<Block>,
893
1164
        sc_transaction_pool::TransactionPoolHandle<Block, FullClient>,
894
1164
        (
895
1164
            BabeBlockImport<Block, FullClient, Arc<FullClient>>,
896
1164
            BabeLink<Block>,
897
1164
            SlotDuration,
898
1164
            Option<Telemetry>,
899
1164
        ),
900
1164
    >,
901
1164
    Error,
902
1164
>
903
1164
where
904
1164
    ChainSelection: 'static + SelectChain<Block>,
905
1164
{
906
1164
    let transaction_pool = sc_transaction_pool::Builder::new(
907
1164
        task_manager.spawn_essential_handle(),
908
1164
        client.clone(),
909
1164
        config.role.is_authority().into(),
910
1164
    )
911
1164
    .with_options(config.transaction_pool.clone())
912
1164
    .with_prometheus(config.prometheus_registry())
913
1164
    .build();
914

            
915
    // Create babe block import queue; this is required to have correct epoch data
916
    // available for manual seal to produce block
917
1164
    let babe_config = babe::configuration(&*client)?;
918
1164
    let (babe_block_import, babe_link) =
919
1164
        babe::block_import(babe_config.clone(), client.clone(), client.clone())?;
920
1164
    let slot_duration = babe_link.config().slot_duration();
921
1164

            
922
1164
    // Create manual seal block import with manual seal block import queue
923
1164
    let import_queue = sc_consensus_manual_seal::import_queue(
924
1164
        Box::new(babe_block_import.clone()),
925
1164
        &task_manager.spawn_essential_handle(),
926
1164
        config.prometheus_registry(),
927
1164
    );
928
1164

            
929
1164
    Ok(service::PartialComponents {
930
1164
        client,
931
1164
        backend,
932
1164
        task_manager,
933
1164
        keystore_container,
934
1164
        select_chain,
935
1164
        import_queue,
936
1164
        transaction_pool: transaction_pool.into(),
937
1164
        other: (babe_block_import, babe_link, slot_duration, telemetry),
938
1164
    })
939
1164
}
940

            
941
1164
fn new_partial_basics(
942
1164
    config: &mut Configuration,
943
1164
    telemetry_worker_handle: Option<TelemetryWorkerHandle>,
944
1164
) -> Result<Basics, Error> {
945
1164
    let telemetry = config
946
1164
        .telemetry_endpoints
947
1164
        .clone()
948
1164
        .filter(|x| !x.is_empty())
949
1164
        .map(move |endpoints| -> Result<_, telemetry::Error> {
950
            let (worker, mut worker_handle) = if let Some(worker_handle) = telemetry_worker_handle {
951
                (None, worker_handle)
952
            } else {
953
                let worker = TelemetryWorker::new(16)?;
954
                let worker_handle = worker.handle();
955
                (Some(worker), worker_handle)
956
            };
957
            let telemetry = worker_handle.new_telemetry(endpoints);
958
            Ok((worker, telemetry))
959
1164
        })
960
1164
        .transpose()?;
961

            
962
1164
    let heap_pages = config
963
1164
        .executor
964
1164
        .default_heap_pages
965
1164
        .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
966
            extra_pages: h as u32,
967
1164
        });
968
1164

            
969
1164
    let mut wasm_builder = WasmExecutor::builder()
970
1164
        .with_execution_method(config.executor.wasm_method)
971
1164
        .with_onchain_heap_alloc_strategy(heap_pages)
972
1164
        .with_offchain_heap_alloc_strategy(heap_pages)
973
1164
        .with_max_runtime_instances(config.executor.max_runtime_instances)
974
1164
        .with_runtime_cache_size(config.executor.runtime_cache_size);
975
1164
    if let Some(ref wasmtime_precompiled_path) = config.executor.wasmtime_precompiled {
976
1104
        wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
977
1104
    }
978
1164
    let executor = wasm_builder.build();
979

            
980
1164
    let (client, backend, keystore_container, task_manager) =
981
1164
        service::new_full_parts::<Block, RuntimeApi, _>(
982
1164
            config,
983
1164
            telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
984
1164
            executor,
985
1164
        )?;
986
1164
    let client = Arc::new(client);
987
1164

            
988
1164
    let telemetry = telemetry.map(|(worker, telemetry)| {
989
        if let Some(worker) = worker {
990
            task_manager.spawn_handle().spawn(
991
                "telemetry",
992
                Some("telemetry"),
993
                Box::pin(worker.run()),
994
            );
995
        }
996
        telemetry
997
1164
    });
998
1164

            
999
1164
    Ok(Basics {
1164
        task_manager,
1164
        client,
1164
        backend,
1164
        keystore_container,
1164
        telemetry,
1164
    })
1164
}
use {
    polkadot_primitives::{AvailabilityBitfield, UncheckedSigned, ValidatorId, ValidatorIndex},
    sp_keystore::Error as KeystoreError,
};
30822
fn keystore_sign<H: Encode, Payload: Encode>(
30822
    keystore: &KeystorePtr,
30822
    payload: Payload,
30822
    context: &SigningContext<H>,
30822
    validator_index: ValidatorIndex,
30822
    key: &ValidatorId,
30822
) -> Result<Option<UncheckedSigned<Payload>>, KeystoreError> {
30822
    let data = payload_data(&payload, context);
30822
    let signature = keystore
30822
        .sr25519_sign(ValidatorId::ID, key.as_ref(), &data)?
30822
        .map(|sig| UncheckedSigned::new(payload, validator_index, sig.into()));
30822
    Ok(signature)
30822
}
30822
fn payload_data<H: Encode, Payload: Encode>(
30822
    payload: &Payload,
30822
    context: &SigningContext<H>,
30822
) -> Vec<u8> {
30822
    // equivalent to (`real_payload`, context).encode()
30822
    let mut out = payload.encode_as();
30822
    out.extend(context.encode());
30822
    out
30822
}
/// Create an `AvailabilityBitfield` with size `total_cores`. The first `used_cores` set to true (occupied),
/// and the remaining to false (available).
16164
fn availability_bitvec(used_cores: usize, total_cores: usize) -> AvailabilityBitfield {
16164
    let mut bitfields = bitvec::bitvec![u8, bitvec::order::Lsb0; 0; 0];
62136
    for i in 0..total_cores {
62136
        if i < used_cores {
15534
            bitfields.push(true);
15534
        } else {
46602
            bitfields.push(false)
        }
    }
16164
    bitfields.into()
16164
}