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
#![allow(dead_code)]
18

            
19
use {
20
    crate::{
21
        Authorship, BlockProductionCost, CollatorAssignmentCost, ExternalValidatorSlashes,
22
        MessageQueue, RuntimeCall,
23
    },
24
    babe_primitives::{
25
        digests::{PreDigest, SecondaryPlainPreDigest},
26
        BABE_ENGINE_ID,
27
    },
28
    beefy_primitives::{ecdsa_crypto::AuthorityId as BeefyId, ConsensusLog, BEEFY_ENGINE_ID},
29
    bitvec::prelude::BitVec,
30
    cumulus_primitives_core::{
31
        relay_chain::{
32
            node_features::FeatureIndex, vstaging::BackedCandidate,
33
            vstaging::CandidateDescriptorV2, vstaging::CommittedCandidateReceiptV2,
34
            vstaging::InherentData as ParachainsInherentData, AvailabilityBitfield,
35
            CandidateCommitments, CompactStatement, CoreIndex, GroupIndex, HeadData,
36
            PersistedValidationData, SigningContext, UncheckedSigned, ValidationCode,
37
            ValidatorIndex, ValidityAttestation,
38
        },
39
        ParaId,
40
    },
41
    frame_support::{
42
        assert_ok,
43
        traits::{OnFinalize, OnInitialize},
44
        BoundedVec,
45
    },
46
    frame_system::pallet_prelude::{BlockNumberFor, HeaderFor},
47
    nimbus_primitives::NimbusId,
48
    pallet_registrar_runtime_api::ContainerChainGenesisData,
49
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
50
    parity_scale_codec::{Decode, Encode, MaxEncodedLen},
51
    runtime_parachains::{
52
        paras::{ParaGenesisArgs, ParaKind},
53
        paras_inherent as parachains_paras_inherent,
54
    },
55
    snowbridge_beacon_primitives::{types::deneb, ExecutionProof, VersionedExecutionPayloadHeader},
56
    snowbridge_verification_primitives::Proof,
57
    sp_core::Pair,
58
    sp_core::Public,
59
    sp_keystore::{KeystoreExt, KeystorePtr},
60
    sp_runtime::{
61
        traits::{Dispatchable, Header, One, SaturatedConversion, Zero},
62
        BuildStorage, Digest, DigestItem,
63
    },
64
    sp_std::collections::btree_map::BTreeMap,
65
    sp_storage::well_known_keys,
66
    std::collections::BTreeSet,
67
    test_relay_sproof_builder::ParaHeaderSproofBuilder,
68
};
69

            
70
pub use crate::{
71
    genesis_config_presets::{get_authority_keys_from_seed, insert_authority_keys_into_keystore},
72
    AccountId, AuthorNoting, Babe, Balance, Balances, Beefy, BeefyMmrLeaf, ContainerRegistrar,
73
    DataPreservers, Grandpa, InactivityTracking, InflationRewards, Initializer, Mmr, Runtime,
74
    RuntimeOrigin, Session, System, TanssiAuthorityAssignment, TanssiCollatorAssignment,
75
    TransactionPayment,
76
};
77

            
78
pub const UNIT: Balance = 1_000_000_000_000;
79

            
80
3
pub fn read_last_entropy() -> [u8; 32] {
81
3
    let mut last = [0u8; 32];
82
3
    sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
83
3
    last
84
3
}
85

            
86
182
pub fn session_to_block(n: u32) -> u32 {
87
182
    // let block_number = flashbox_runtime::Period::get() * n;
88
182
    let block_number = Babe::current_epoch().duration.saturated_into::<u32>() * n;
89
182

            
90
182
    // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
91
182
    // so this is the first block of the new session that can actually be used
92
182
    block_number + 1
93
182
}
94

            
95
17
pub fn babe_authorities() -> Vec<babe_primitives::AuthorityId> {
96
17
    Babe::authorities()
97
17
        .iter()
98
34
        .map(|(key, _)| key.clone())
99
17
        .collect()
100
17
}
101

            
102
8
pub fn grandpa_authorities() -> Vec<pallet_grandpa::AuthorityId> {
103
8
    Grandpa::grandpa_authorities()
104
8
        .iter()
105
16
        .map(|(key, _)| key.clone())
106
8
        .collect()
107
8
}
108

            
109
13
pub fn authorities_for_container(para_id: ParaId) -> Option<Vec<NimbusId>> {
110
13
    let session_index = Session::current_index();
111
13

            
112
13
    TanssiAuthorityAssignment::collator_container_chain(session_index)
113
13
        .expect("authorities should be set")
114
13
        .container_chains
115
13
        .get(&para_id)
116
13
        .cloned()
117
13
}
118

            
119
pub fn accounts_for_container(para_id: ParaId) -> Option<Vec<AccountId>> {
120
    TanssiCollatorAssignment::collator_container_chain()
121
        .container_chains
122
        .get(&para_id)
123
        .cloned()
124
}
125

            
126
3
pub fn get_beefy_digest(log: ConsensusLog<BeefyId>) -> DigestItem {
127
3
    DigestItem::Consensus(BEEFY_ENGINE_ID, log.encode())
128
3
}
129

            
130
/// FIXME: run_to_session(n) only runs to the last block of session n-1, so Session::index() will
131
/// return n-1. To actually run to session n, create an additional block afterwards using `run_block()`.
132
175
pub fn run_to_session(n: u32) {
133
175
    run_to_block(session_to_block(n));
134
175
}
135

            
136
/// Utility function that advances the chain to the desired block number.
137
///
138
/// After this function returns, the current block number will be `n`, and the block will be "open",
139
/// meaning that on_initialize has been executed, but on_finalize has not. To execute on_finalize as
140
/// well, for example to test a runtime api, manually call `end_block` after this, run the test, and
141
/// call `start_block` to ensure that this function keeps working as expected.
142
/// Extrinsics should always be executed before on_finalize.
143
264
pub fn run_to_block(n: u32) -> BTreeMap<u32, RunSummary> {
144
264
    let current_block_number = System::block_number();
145
264
    assert!(
146
264
        current_block_number < n,
147
        "run_to_block called with block {} when current block is {}",
148
        n,
149
        current_block_number
150
    );
151

            
152
264
    let mut summaries = BTreeMap::new();
153

            
154
3717
    while System::block_number() < n {
155
3453
        let summary = run_block();
156
3453
        let block_number = System::block_number();
157
3453
        summaries.insert(block_number, summary);
158
3453
    }
159

            
160
264
    summaries
161
264
}
162

            
163
45
pub fn get_genesis_data_with_validation_code() -> (ContainerChainGenesisData, Vec<u8>) {
164
45
    let validation_code = mock_validation_code().0;
165
45
    let genesis_data = ContainerChainGenesisData {
166
45
        storage: BoundedVec::try_from(vec![(b":code".to_vec(), validation_code.clone()).into()])
167
45
            .unwrap(),
168
45
        name: Default::default(),
169
45
        id: Default::default(),
170
45
        fork_id: Default::default(),
171
45
        extensions: BoundedVec::try_from(vec![]).unwrap(),
172
45
        properties: Default::default(),
173
45
    };
174
45
    (genesis_data, validation_code)
175
45
}
176

            
177
3668
pub fn insert_authorities_and_slot_digests(slot: u64) {
178
3668
    let pre_digest = Digest {
179
3668
        logs: vec![DigestItem::PreRuntime(
180
3668
            BABE_ENGINE_ID,
181
3668
            PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
182
3668
                slot: slot.into(),
183
3668
                authority_index: 0,
184
3668
            })
185
3668
            .encode(),
186
3668
        )],
187
3668
    };
188
3668

            
189
3668
    System::reset_events();
190
3668
    System::initialize(
191
3668
        &(System::block_number() + 1),
192
3668
        &System::parent_hash(),
193
3668
        &pre_digest,
194
3668
    );
195
3668
}
196

            
197
#[derive(Debug, Clone, Eq, PartialEq)]
198
pub struct RunSummary {
199
    pub inflation: Balance,
200
}
201

            
202
#[derive(Clone, Encode, Decode, PartialEq, Debug, scale_info::TypeInfo, MaxEncodedLen)]
203
enum RunBlockState {
204
    Start(u32),
205
    End(u32),
206
}
207

            
208
impl RunBlockState {
209
7163
    fn assert_can_advance(&self, new_state: &RunBlockState) {
210
7163
        match self {
211
3495
            RunBlockState::Start(n) => {
212
3495
                assert_eq!(
213
3495
                    new_state,
214
3495
                    &RunBlockState::End(*n),
215
                    "expected a call to end_block({}), but user called {:?}",
216
                    *n,
217
                    new_state
218
                );
219
            }
220
3668
            RunBlockState::End(n) => {
221
3668
                assert_eq!(
222
3668
                    new_state,
223
3668
                    &RunBlockState::Start(*n + 1),
224
                    "expected a call to start_block({}), but user called {:?}",
225
                    *n + 1,
226
                    new_state
227
                )
228
            }
229
        }
230
7163
    }
231
}
232

            
233
7163
fn advance_block_state_machine(new_state: RunBlockState) {
234
7163
    if frame_support::storage::unhashed::exists(b"__mock_is_xcm_test") {
235
        // Disable this check in XCM tests, because the XCM emulator runs on_initialize and
236
        // on_finalize automatically
237
        return;
238
7163
    }
239
7163
    let old_state: RunBlockState =
240
7163
        frame_support::storage::unhashed::get(b"__mock_debug_block_state").unwrap_or(
241
7163
            // Initial state is expecting a call to start() with block number 1, so old state should be
242
7163
            // end of block 0
243
7163
            RunBlockState::End(0),
244
7163
        );
245
7163
    old_state.assert_can_advance(&new_state);
246
7163
    frame_support::storage::unhashed::put(b"__mock_debug_block_state", &new_state);
247
7163
}
248

            
249
3668
pub fn start_block() -> RunSummary {
250
    // we inject empty data
251
    // We need to create it here, because otherwise the block number increases
252
    // on-initialize.
253
    // This requires signatures so we should not run it unless we have a keystore
254
3668
    let mock_inherent_data: Option<cumulus_primitives_core::relay_chain::vstaging::InherentData> =
255
3668
        if is_para_inherent_enabled() {
256
            // We check the inherent data in storage else we construct an empty one
257
92
            Some(
258
92
                take_new_inherent_data()
259
92
                    .unwrap_or(ParasInherentTestBuilder::<Runtime>::new().build()),
260
92
            )
261
        } else {
262
3576
            None
263
        };
264

            
265
3668
    let block_number = System::block_number();
266
3668
    advance_block_state_machine(RunBlockState::Start(block_number + 1));
267
3668

            
268
3668
    insert_authorities_and_slot_digests(current_slot() + 1);
269
3668

            
270
3668
    // Initialize the new block
271
3668
    Babe::on_initialize(System::block_number());
272
3668
    Authorship::on_initialize(System::block_number());
273
3668
    ContainerRegistrar::on_initialize(System::block_number());
274
3668
    ExternalValidatorSlashes::on_initialize(System::block_number());
275
3668
    Session::on_initialize(System::block_number());
276
3668

            
277
3668
    Initializer::on_initialize(System::block_number());
278
3668
    TanssiCollatorAssignment::on_initialize(System::block_number());
279
3668
    MessageQueue::on_initialize(System::block_number());
280
3668

            
281
3668
    let current_issuance = Balances::total_issuance();
282
3668
    InflationRewards::on_initialize(System::block_number());
283
3668
    let new_issuance = Balances::total_issuance();
284

            
285
3668
    if let Some(mock_inherent_data) = mock_inherent_data {
286
92
        set_paras_inherent(mock_inherent_data);
287
3576
    }
288

            
289
3668
    Beefy::on_initialize(System::block_number());
290
3668
    Mmr::on_initialize(System::block_number());
291
3668
    BeefyMmrLeaf::on_initialize(System::block_number());
292
3668
    InactivityTracking::on_initialize(System::block_number());
293
3668
    RunSummary {
294
3668
        inflation: new_issuance - current_issuance,
295
3668
    }
296
3668
}
297

            
298
3495
pub fn end_block() {
299
3495
    let block_number = System::block_number();
300
3495
    advance_block_state_machine(RunBlockState::End(block_number));
301
3495
    // Finalize the block
302
3495
    Babe::on_finalize(System::block_number());
303
3495
    Authorship::on_finalize(System::block_number());
304
3495
    Session::on_finalize(System::block_number());
305
3495
    Grandpa::on_finalize(System::block_number());
306
3495
    TransactionPayment::on_finalize(System::block_number());
307
3495
    Initializer::on_finalize(System::block_number());
308
3495
    ContainerRegistrar::on_finalize(System::block_number());
309
3495
    TanssiCollatorAssignment::on_finalize(System::block_number());
310
3495
    Beefy::on_finalize(System::block_number());
311
3495
    Mmr::on_finalize(System::block_number());
312
3495
    BeefyMmrLeaf::on_finalize(System::block_number());
313
3495
    InactivityTracking::on_finalize(System::block_number());
314
3495
}
315

            
316
3493
pub fn run_block() -> RunSummary {
317
3493
    end_block();
318
3493

            
319
3493
    start_block()
320
3493
}
321

            
322
#[derive(Default, Clone)]
323
pub struct ParaRegistrationParams {
324
    pub para_id: u32,
325
    pub genesis_data: ContainerChainGenesisData,
326
    pub block_production_credits: u32,
327
    pub collator_assignment_credits: u32,
328
    pub parathread_params: Option<tp_traits::ParathreadParams>,
329
}
330

            
331
impl From<(u32, ContainerChainGenesisData, u32, u32)> for ParaRegistrationParams {
332
10
    fn from(value: (u32, ContainerChainGenesisData, u32, u32)) -> Self {
333
10
        Self {
334
10
            para_id: value.0,
335
10
            genesis_data: value.1,
336
10
            block_production_credits: value.2,
337
10
            collator_assignment_credits: value.3,
338
10
            parathread_params: None,
339
10
        }
340
10
    }
341
}
342

            
343
173
pub fn default_config() -> pallet_configuration::HostConfiguration {
344
173
    pallet_configuration::HostConfiguration {
345
173
        max_collators: 100,
346
173
        min_orchestrator_collators: 2,
347
173
        max_orchestrator_collators: 2,
348
173
        collators_per_container: 2,
349
173
        full_rotation_period: 0,
350
173
        ..Default::default()
351
173
    }
352
173
}
353

            
354
#[derive(Clone)]
355
pub struct ExtBuilder {
356
    // endowed accounts with balances
357
    balances: Vec<(AccountId, Balance)>,
358
    // [validator, amount]
359
    validators: Vec<(AccountId, Balance)>,
360
    // [validator, amount]
361
    external_validators: Vec<(AccountId, Balance)>,
362
    // [collator, amount]
363
    collators: Vec<(AccountId, Balance)>,
364
    // sudo key
365
    sudo: Option<AccountId>,
366
    // list of registered para ids: para_id, genesis_data, boot_nodes, block_credits, session_credits
367
    para_ids: Vec<ParaRegistrationParams>,
368
    // configuration to apply
369
    config: pallet_configuration::HostConfiguration,
370
    relay_config: runtime_parachains::configuration::HostConfiguration<BlockNumberFor<Runtime>>,
371
    own_para_id: Option<ParaId>,
372
    next_free_para_id: ParaId,
373
    keystore: Option<KeystorePtr>,
374
    safe_xcm_version: Option<u32>,
375
    inherent_data_enabled: bool,
376
}
377

            
378
impl Default for ExtBuilder {
379
173
    fn default() -> Self {
380
173
        Self {
381
173
            balances: vec![
382
173
                // Alice gets 10k extra tokens for her mapping deposit
383
173
                (AccountId::from(ALICE), 210_000 * UNIT),
384
173
                (AccountId::from(BOB), 100_000 * UNIT),
385
173
            ],
386
173
            validators: vec![
387
173
                (AccountId::from(ALICE), 210 * UNIT),
388
173
                (AccountId::from(BOB), 100 * UNIT),
389
173
            ],
390
173
            external_validators: vec![],
391
173
            collators: Default::default(),
392
173
            sudo: Default::default(),
393
173
            para_ids: Default::default(),
394
173
            config: default_config(),
395
173
            relay_config: runtime_parachains::configuration::HostConfiguration {
396
173
                scheduler_params: SchedulerParams {
397
173
                    num_cores: 6,
398
173
                    ..Default::default()
399
173
                },
400
173
                max_head_data_size: 20500,
401
173
                ..Default::default()
402
173
            },
403
173
            own_para_id: Default::default(),
404
173
            next_free_para_id: Default::default(),
405
173
            keystore: None,
406
173
            safe_xcm_version: Default::default(),
407
173
            inherent_data_enabled: false,
408
173
        }
409
173
    }
410
}
411

            
412
impl ExtBuilder {
413
144
    pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
414
144
        self.balances = balances;
415
144
        self
416
144
    }
417

            
418
1
    pub fn with_sudo(mut self, sudo: AccountId) -> Self {
419
1
        self.sudo = Some(sudo);
420
1
        self
421
1
    }
422

            
423
13
    pub fn with_validators(mut self, validators: Vec<(AccountId, Balance)>) -> Self {
424
13
        self.validators = validators;
425
13
        self
426
13
    }
427

            
428
6
    pub fn with_external_validators(mut self, validators: Vec<(AccountId, Balance)>) -> Self {
429
6
        self.external_validators = validators;
430
6
        self
431
6
    }
432

            
433
77
    pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
434
77
        self.collators = collators;
435
77
        self
436
77
    }
437

            
438
12
    pub fn with_para_ids(mut self, para_ids: Vec<ParaRegistrationParams>) -> Self {
439
12
        self.para_ids = para_ids;
440
12
        self
441
12
    }
442

            
443
    /// Helper function like `with_para_ids` but registering parachains with an empty genesis data,
444
    /// and max amount of credits.
445
47
    pub fn with_empty_parachains(mut self, para_ids: Vec<u32>) -> Self {
446
47
        self.para_ids = para_ids
447
47
            .into_iter()
448
103
            .map(|para_id| ParaRegistrationParams {
449
103
                para_id,
450
103
                genesis_data: empty_genesis_data(),
451
103
                block_production_credits: u32::MAX,
452
103
                collator_assignment_credits: u32::MAX,
453
103
                parathread_params: None,
454
103
            })
455
47
            .collect();
456
47
        self
457
47
    }
458

            
459
5
    pub fn with_additional_empty_parathreads(mut self, para_ids: Vec<u32>) -> Self {
460
5
        self.para_ids = self
461
5
            .para_ids
462
5
            .iter()
463
5
            .cloned()
464
14
            .chain(para_ids.into_iter().map(|para_id| ParaRegistrationParams {
465
14
                para_id,
466
14
                genesis_data: empty_genesis_data(),
467
14
                block_production_credits: u32::MAX,
468
14
                collator_assignment_credits: u32::MAX,
469
14
                parathread_params: Some(ParathreadParams {
470
14
                    slot_frequency: Default::default(),
471
14
                }),
472
14
            }))
473
5
            .collect();
474
5
        self
475
5
    }
476

            
477
    // Maybe change to with_collators_config?
478
18
    pub fn with_config(mut self, config: pallet_configuration::HostConfiguration) -> Self {
479
18
        self.config = config;
480
18
        self
481
18
    }
482

            
483
    pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
484
        self.safe_xcm_version = Some(safe_xcm_version);
485
        self
486
    }
487

            
488
    // Maybe change to with_collators_config?
489
12
    pub fn with_relay_config(
490
12
        mut self,
491
12
        relay_config: runtime_parachains::configuration::HostConfiguration<BlockNumberFor<Runtime>>,
492
12
    ) -> Self {
493
12
        self.relay_config = relay_config;
494
12
        self
495
12
    }
496

            
497
    // Maybe change to with_collators_config?
498
1
    pub fn with_next_free_para_id(mut self, para_id: ParaId) -> Self {
499
1
        self.next_free_para_id = para_id;
500
1
        self
501
1
    }
502

            
503
    // Maybe change to with_collators_config?
504
7
    pub fn with_keystore(mut self, keystore: KeystorePtr) -> Self {
505
7
        self.keystore = Some(keystore);
506
7
        self
507
7
    }
508

            
509
7
    pub fn with_inherent_data_enabled(mut self) -> Self {
510
7
        self.inherent_data_enabled = true;
511
7
        self
512
7
    }
513

            
514
173
    pub fn build_storage(self) -> sp_core::storage::Storage {
515
173
        let mut t = frame_system::GenesisConfig::<Runtime>::default()
516
173
            .build_storage()
517
173
            .unwrap();
518
173

            
519
173
        pallet_babe::GenesisConfig::<Runtime> {
520
173
            ..Default::default()
521
173
        }
522
173
        .assimilate_storage(&mut t)
523
173
        .unwrap();
524
173

            
525
173
        pallet_balances::GenesisConfig::<Runtime> {
526
173
            balances: self.balances,
527
173
            ..Default::default()
528
173
        }
529
173
        .assimilate_storage(&mut t)
530
173
        .unwrap();
531
173

            
532
173
        // We need to initialize these pallets first. When initializing pallet-session,
533
173
        // these values will be taken into account for collator-assignment.
534
173

            
535
173
        pallet_registrar::GenesisConfig::<Runtime> {
536
173
            para_ids: self
537
173
                .para_ids
538
173
                .iter()
539
173
                .cloned()
540
173
                .map(|registered_para| {
541
135
                    (
542
135
                        registered_para.para_id.into(),
543
135
                        registered_para.genesis_data,
544
135
                        registered_para.parathread_params,
545
135
                    )
546
173
                })
547
173
                .collect(),
548
173
            ..Default::default()
549
173
        }
550
173
        .assimilate_storage(&mut t)
551
173
        .unwrap();
552
173

            
553
173
        // We register mock wasm
554
173
        runtime_parachains::paras::GenesisConfig::<Runtime> {
555
173
            paras: self
556
173
                .para_ids
557
173
                .iter()
558
173
                .cloned()
559
173
                .map(|registered_para| {
560
135
                    let para_kind = if registered_para.parathread_params.is_some() {
561
18
                        ParaKind::Parathread
562
                    } else {
563
117
                        ParaKind::Parachain
564
                    };
565
135
                    (
566
135
                        registered_para.para_id.into(),
567
135
                        ParaGenesisArgs {
568
135
                            validation_code: mock_validation_code(),
569
135
                            para_kind,
570
135
                            genesis_head: HeadData::from(vec![0u8]),
571
135
                        },
572
135
                    )
573
173
                })
574
173
                .collect(),
575
173
            ..Default::default()
576
173
        }
577
173
        .assimilate_storage(&mut t)
578
173
        .unwrap();
579
173

            
580
173
        pallet_services_payment::GenesisConfig::<Runtime> {
581
173
            para_id_credits: self
582
173
                .para_ids
583
173
                .clone()
584
173
                .into_iter()
585
173
                .map(|registered_para| {
586
135
                    (
587
135
                        registered_para.para_id.into(),
588
135
                        registered_para.block_production_credits,
589
135
                        registered_para.collator_assignment_credits,
590
135
                    )
591
135
                        .into()
592
173
                })
593
173
                .collect(),
594
173
        }
595
173
        .assimilate_storage(&mut t)
596
173
        .unwrap();
597
173

            
598
173
        runtime_common::paras_registrar::GenesisConfig::<Runtime> {
599
173
            next_free_para_id: self.next_free_para_id,
600
173
            ..Default::default()
601
173
        }
602
173
        .assimilate_storage(&mut t)
603
173
        .unwrap();
604
173

            
605
173
        pallet_configuration::GenesisConfig::<Runtime> {
606
173
            config: self.config,
607
173
            ..Default::default()
608
173
        }
609
173
        .assimilate_storage(&mut t)
610
173
        .unwrap();
611
173

            
612
173
        pallet_xcm::GenesisConfig::<Runtime> {
613
173
            safe_xcm_version: self.safe_xcm_version,
614
173
            ..Default::default()
615
173
        }
616
173
        .assimilate_storage(&mut t)
617
173
        .unwrap();
618
173

            
619
173
        runtime_parachains::configuration::GenesisConfig::<Runtime> {
620
173
            config: self.relay_config,
621
173
        }
622
173
        .assimilate_storage(&mut t)
623
173
        .unwrap();
624
173

            
625
173
        let mut keys: Vec<_> = Vec::new();
626
173
        let mut non_authority_keys: Vec<_> = Vec::new();
627
173
        if !self.validators.is_empty() {
628
167
            let validator_keys: Vec<_> = self
629
167
                .validators
630
167
                .clone()
631
167
                .into_iter()
632
349
                .map(|(account, _balance)| {
633
349
                    let authority_keys = get_authority_keys_from_seed(&account.to_string());
634
349
                    if let Some(keystore) = self.keystore.as_ref() {
635
14
                        insert_authority_keys_into_keystore(&account.to_string(), keystore)
636
335
                    }
637
349
                    (
638
349
                        account.clone(),
639
349
                        account,
640
349
                        crate::SessionKeys {
641
349
                            babe: authority_keys.babe.clone(),
642
349
                            grandpa: authority_keys.grandpa.clone(),
643
349
                            para_validator: authority_keys.para_validator.clone(),
644
349
                            para_assignment: authority_keys.para_assignment.clone(),
645
349
                            authority_discovery: authority_keys.authority_discovery.clone(),
646
349
                            beefy: authority_keys.beefy.clone(),
647
349
                            nimbus: authority_keys.nimbus.clone(),
648
349
                        },
649
349
                    )
650
349
                })
651
167
                .collect();
652
167
            keys.extend(validator_keys)
653
6
        }
654

            
655
173
        if !self.external_validators.is_empty() {
656
6
            let validator_keys: Vec<_> = self
657
6
                .external_validators
658
6
                .clone()
659
6
                .into_iter()
660
12
                .map(|(account, _balance)| {
661
12
                    let authority_keys = get_authority_keys_from_seed(&account.to_string());
662
12
                    if let Some(keystore) = self.keystore.as_ref() {
663
                        insert_authority_keys_into_keystore(&account.to_string(), keystore)
664
12
                    }
665
12
                    (
666
12
                        account.clone(),
667
12
                        account,
668
12
                        crate::SessionKeys {
669
12
                            babe: authority_keys.babe.clone(),
670
12
                            grandpa: authority_keys.grandpa.clone(),
671
12
                            para_validator: authority_keys.para_validator.clone(),
672
12
                            para_assignment: authority_keys.para_assignment.clone(),
673
12
                            authority_discovery: authority_keys.authority_discovery.clone(),
674
12
                            beefy: authority_keys.beefy.clone(),
675
12
                            nimbus: authority_keys.nimbus.clone(),
676
12
                        },
677
12
                    )
678
12
                })
679
6
                .collect();
680
6
            keys.extend(validator_keys)
681
167
        }
682

            
683
173
        if !self.collators.is_empty() {
684
            // We set invulnerables in pallet_invulnerables
685
77
            let invulnerables: Vec<AccountId> = self
686
77
                .collators
687
77
                .clone()
688
77
                .into_iter()
689
249
                .map(|(account, _balance)| account)
690
77
                .collect();
691
77

            
692
77
            pallet_invulnerables::GenesisConfig::<Runtime> {
693
77
                invulnerables: invulnerables.clone(),
694
77
            }
695
77
            .assimilate_storage(&mut t)
696
77
            .unwrap();
697
77

            
698
77
            // But we also initialize their keys in the session pallet
699
77
            // We discard those that had the key initialized already
700
77
            // from the validator list
701
77
            // in other words, for testing purposes we allow to inject a validator account
702
77
            // in the collator list
703
77
            let validator_unique_accounts: Vec<_> = self
704
77
                .validators
705
77
                .iter()
706
154
                .map(|(account, _)| account.clone())
707
77
                .collect();
708
77
            let collator_keys: Vec<_> = self
709
77
                .collators
710
77
                .into_iter()
711
249
                .filter_map(|(account, _balance)| {
712
249
                    if validator_unique_accounts.contains(&account) {
713
152
                        None
714
                    } else {
715
97
                        let authority_keys = get_authority_keys_from_seed(&account.to_string());
716
97
                        if let Some(keystore) = self.keystore.as_ref() {
717
                            insert_authority_keys_into_keystore(&account.to_string(), keystore)
718
97
                        }
719
97
                        Some((
720
97
                            account.clone(),
721
97
                            account,
722
97
                            crate::SessionKeys {
723
97
                                babe: authority_keys.babe.clone(),
724
97
                                grandpa: authority_keys.grandpa.clone(),
725
97
                                para_validator: authority_keys.para_validator.clone(),
726
97
                                para_assignment: authority_keys.para_assignment.clone(),
727
97
                                authority_discovery: authority_keys.authority_discovery.clone(),
728
97
                                beefy: authority_keys.beefy.clone(),
729
97
                                nimbus: authority_keys.nimbus.clone(),
730
97
                            },
731
97
                        ))
732
                    }
733
249
                })
734
77
                .collect();
735
77
            non_authority_keys.extend(collator_keys)
736
96
        }
737

            
738
173
        pallet_external_validators::GenesisConfig::<Runtime> {
739
173
            skip_external_validators: false,
740
173
            whitelisted_validators: self
741
173
                .validators
742
173
                .iter()
743
349
                .map(|(account, _)| account.clone())
744
173
                .collect(),
745
173
            external_validators: self
746
173
                .external_validators
747
173
                .iter()
748
173
                .map(|(account, _)| account.clone())
749
173
                .collect(),
750
173
        }
751
173
        .assimilate_storage(&mut t)
752
173
        .unwrap();
753
173

            
754
173
        pallet_session::GenesisConfig::<Runtime> {
755
173
            keys,
756
173
            non_authority_keys,
757
173
        }
758
173
        .assimilate_storage(&mut t)
759
173
        .unwrap();
760
173

            
761
173
        pallet_sudo::GenesisConfig::<Runtime> { key: self.sudo }
762
173
            .assimilate_storage(&mut t)
763
173
            .unwrap();
764
173

            
765
173
        snowbridge_pallet_system::GenesisConfig::<Runtime> {
766
173
            // This is irrelevant, we can put any number here
767
173
            // as long as it is a non-used para id
768
173
            para_id: 1000u32.into(),
769
173
            asset_hub_para_id: 1001u32.into(),
770
173
            ..Default::default()
771
173
        }
772
173
        .assimilate_storage(&mut t)
773
173
        .unwrap();
774
173

            
775
173
        if self.safe_xcm_version.is_some() {
776
            // Disable run_block checks in XCM tests, because the XCM emulator runs on_initialize and
777
            // on_finalize automatically
778
            t.top.insert(b"__mock_is_xcm_test".to_vec(), b"1".to_vec());
779
173
        }
780

            
781
        // Indicate that we should always (for every block) inject the paras_inherent.
782
        // Wether we inject an empty one or not its decided by b'ParasInherentData
783
173
        t.top.insert(
784
173
            b"ParasInherentEnabled".to_vec(),
785
173
            self.inherent_data_enabled.encode(),
786
173
        );
787
173

            
788
173
        t
789
173
    }
790

            
791
173
    pub fn build(self) -> sp_io::TestExternalities {
792
173
        let keystore = self.keystore.clone();
793
173
        let t = self.build_storage();
794
173
        let mut ext = sp_io::TestExternalities::new(t);
795
173
        if let Some(keystore) = keystore {
796
7
            ext.register_extension(KeystoreExt(keystore));
797
166
        }
798
173
        ext.execute_with(|| {
799
173
            // Start block 1
800
173
            start_block();
801
173
        });
802
173
        ext
803
173
    }
804
}
805

            
806
171
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
807
171
    <Runtime as frame_system::Config>::RuntimeOrigin::root()
808
171
}
809

            
810
350
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
811
350
    <Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
812
350
}
813

            
814
101
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
815
101
    <Runtime as frame_system::Config>::RuntimeOrigin::none()
816
101
}
817

            
818
/// This function is different in solochains: instead of creating a storage proof and calling the
819
/// `set_latest_author_data` inherent with that proof as argument, this writes to storage directly.
820
9
pub fn set_author_noting_inherent_data(builder: ParaHeaderSproofBuilder) {
821
30
    for (k, v) in builder.key_values() {
822
30
        frame_support::storage::unhashed::put_raw(&k, &v);
823
30
    }
824

            
825
9
    assert_ok!(RuntimeCall::AuthorNoting(
826
9
        pallet_author_noting::Call::<Runtime>::set_latest_author_data { data: () }
827
9
    )
828
9
    .dispatch(inherent_origin()));
829
9
}
830

            
831
135
pub fn empty_genesis_data() -> ContainerChainGenesisData {
832
135
    ContainerChainGenesisData {
833
135
        storage: Default::default(),
834
135
        name: Default::default(),
835
135
        id: Default::default(),
836
135
        fork_id: Default::default(),
837
135
        extensions: Default::default(),
838
135
        properties: Default::default(),
839
135
    }
840
135
}
841

            
842
3668
pub fn current_slot() -> u64 {
843
3668
    Babe::current_slot().into()
844
3668
}
845

            
846
21
pub fn block_credits_to_required_balance(number_of_blocks: u32, para_id: ParaId) -> Balance {
847
21
    let block_cost = BlockProductionCost::block_cost(&para_id).0;
848
21
    u128::from(number_of_blocks).saturating_mul(block_cost)
849
21
}
850

            
851
4
pub fn collator_assignment_credits_to_required_balance(
852
4
    number_of_sessions: u32,
853
4
    para_id: ParaId,
854
4
) -> Balance {
855
4
    let collator_assignment_cost = CollatorAssignmentCost::collator_assignment_cost(&para_id).0;
856
4
    u128::from(number_of_sessions).saturating_mul(collator_assignment_cost)
857
4
}
858

            
859
pub const ALICE: [u8; 32] = [4u8; 32];
860
pub const BOB: [u8; 32] = [5u8; 32];
861
pub const CHARLIE: [u8; 32] = [6u8; 32];
862
pub const DAVE: [u8; 32] = [7u8; 32];
863
pub const EVE: [u8; 32] = [8u8; 32];
864
pub const FERDIE: [u8; 32] = [9u8; 32];
865

            
866
// Whether we have custom data to inject in paras inherent
867
92
fn take_new_inherent_data() -> Option<cumulus_primitives_core::relay_chain::vstaging::InherentData>
868
92
{
869
92
    let data: Option<cumulus_primitives_core::relay_chain::vstaging::InherentData> =
870
92
        frame_support::storage::unhashed::take(b"ParasInherentData");
871
92

            
872
92
    data
873
92
}
874

            
875
// Whether we should inject the paras inherent.
876
3668
fn is_para_inherent_enabled() -> bool {
877
3668
    let enabled: Option<bool> = frame_support::storage::unhashed::get(b"ParasInherentEnabled");
878
3668
    enabled.unwrap_or(false)
879
3668
}
880

            
881
// Set new data to inject in paras inherent
882
7
pub fn set_new_inherent_data(data: cumulus_primitives_core::relay_chain::vstaging::InherentData) {
883
7
    frame_support::storage::unhashed::put(b"ParasInherentData", &data);
884
7
}
885

            
886
1
pub fn set_new_randomness_data(data: Option<[u8; 32]>) {
887
1
    pallet_babe::AuthorVrfRandomness::<Runtime>::set(data);
888
1
}
889

            
890
/// Mock the inherent that sets validation data in ParachainSystem, which
891
/// contains the `relay_chain_block_number`, which is used in `collator-assignment` as a
892
/// source of randomness.
893
92
pub fn set_paras_inherent(data: cumulus_primitives_core::relay_chain::vstaging::InherentData) {
894
92
    // In order for this inherent to work, we need to match the parent header
895
92
    // the parent header does not play a significant role in the rest of the framework so
896
92
    // we are simply going to mock it
897
92
    System::set_parent_hash(data.parent_header.hash());
898
92
    assert_ok!(
899
92
        RuntimeCall::ParaInherent(parachains_paras_inherent::Call::<Runtime>::enter { data })
900
92
            .dispatch(inherent_origin())
901
92
    );
902
    // Error: InherentDataFilteredDuringExecution
903
89
    frame_support::storage::unhashed::kill(&frame_support::storage::storage_prefix(
904
89
        b"ParaInherent",
905
89
        b"Included",
906
89
    ));
907
89
}
908

            
909
pub(crate) struct ParasInherentTestBuilder<T: runtime_parachains::paras_inherent::Config> {
910
    /// Starting block number; we expect it to get incremented on session setup.
911
    block_number: BlockNumberFor<T>,
912
    /// Paras here will both be backed in the inherent data and already occupying a core (which is
913
    /// freed via bitfields).
914
    ///
915
    /// Map from para id to number of validity votes. Core indices are generated based on
916
    /// `elastic_paras` configuration. Each para id in `elastic_paras` gets the
917
    /// specified amount of consecutive cores assigned to it. If a para id is not present
918
    /// in `elastic_paras` it get assigned to a single core.
919
    backed_and_concluding_paras: BTreeMap<u32, u32>,
920

            
921
    /// Paras which don't yet occupy a core, but will after the inherent has been processed.
922
    backed_in_inherent_paras: BTreeMap<u32, u32>,
923
    _phantom: core::marker::PhantomData<T>,
924
}
925

            
926
188
pub fn mock_validation_code() -> ValidationCode {
927
188
    ValidationCode(vec![1; 10])
928
188
}
929

            
930
/// Create a dummy collator id suitable to be used in a V1 candidate descriptor.
931
pub fn junk_collator() -> CollatorId {
932
    CollatorId::from_slice(&mut (0..32).collect::<Vec<_>>().as_slice()).expect("32 bytes; qed")
933
}
934

            
935
/// Creates a dummy collator signature suitable to be used in a V1 candidate descriptor.
936
pub fn junk_collator_signature() -> CollatorSignature {
937
    CollatorSignature::from_slice(&mut (0..64).collect::<Vec<_>>().as_slice())
938
        .expect("64 bytes; qed")
939
}
940

            
941
#[allow(dead_code)]
942
impl<T: runtime_parachains::paras_inherent::Config> ParasInherentTestBuilder<T> {
943
    /// Create a new `BenchBuilder` with some opinionated values that should work with the rest
944
    /// of the functions in this implementation.
945
99
    pub(crate) fn new() -> Self {
946
99
        ParasInherentTestBuilder {
947
99
            block_number: Zero::zero(),
948
99
            backed_and_concluding_paras: Default::default(),
949
99
            backed_in_inherent_paras: Default::default(),
950
99
            _phantom: core::marker::PhantomData::<T>,
951
99
        }
952
99
    }
953

            
954
    /// Set a map from para id seed to number of validity votes.
955
7
    pub(crate) fn set_backed_and_concluding_paras(
956
7
        mut self,
957
7
        backed_and_concluding_paras: BTreeMap<u32, u32>,
958
7
    ) -> Self {
959
7
        self.backed_and_concluding_paras = backed_and_concluding_paras;
960
7
        self
961
7
    }
962

            
963
    /// Set a map from para id seed to number of validity votes for votes in inherent data.
964
    pub(crate) fn set_backed_in_inherent_paras(mut self, backed: BTreeMap<u32, u32>) -> Self {
965
        self.backed_in_inherent_paras = backed;
966
        self
967
    }
968

            
969
    /// Mock header.
970
313
    pub(crate) fn header(block_number: BlockNumberFor<T>) -> HeaderFor<T> {
971
313
        HeaderFor::<T>::new(
972
313
            block_number,       // `block_number`,
973
313
            Default::default(), // `extrinsics_root`,
974
313
            Default::default(), // `storage_root`,
975
313
            Default::default(), // `parent_hash`,
976
313
            Default::default(), // digest,
977
313
        )
978
313
    }
979

            
980
    /// Maximum number of validators that may be part of a validator group.
981
    pub(crate) fn fallback_max_validators() -> u32 {
982
        runtime_parachains::configuration::ActiveConfig::<T>::get()
983
            .max_validators
984
            .unwrap_or(200)
985
    }
986

            
987
    /// Maximum number of validators participating in parachains consensus (a.k.a. active
988
    /// validators).
989
    fn max_validators(&self) -> u32 {
990
        Self::fallback_max_validators()
991
    }
992

            
993
    /// Maximum number of validators per core (a.k.a. max validators per group). This value is used
994
    /// if none is explicitly set on the builder.
995
    pub(crate) fn fallback_max_validators_per_core() -> u32 {
996
        runtime_parachains::configuration::ActiveConfig::<T>::get()
997
            .scheduler_params
998
            .max_validators_per_core
999
            .unwrap_or(5)
    }
    /// Get the maximum number of validators per core.
    fn max_validators_per_core(&self) -> u32 {
        Self::fallback_max_validators_per_core()
    }
    /// Get the maximum number of cores we expect from this configuration.
    pub(crate) fn max_cores(&self) -> u32 {
        self.max_validators() / self.max_validators_per_core()
    }
    /// Create an `AvailabilityBitfield` where `concluding` is a map where each key is a core index
    /// that is concluding and `cores` is the total number of cores in the system.
99
    fn availability_bitvec(concluding_cores: &BTreeSet<u32>, cores: usize) -> AvailabilityBitfield {
99
        let mut bitfields = bitvec::bitvec![u8, bitvec::order::Lsb0; 0; 0];
198
        for i in 0..cores {
198
            if concluding_cores.contains(&(i as u32)) {
8
                bitfields.push(true);
8
            } else {
190
                bitfields.push(false)
            }
        }
99
        bitfields.into()
99
    }
    /// Create a bitvec of `validators` length with all yes votes.
    fn validator_availability_votes_yes(validators: usize) -> BitVec<u8, bitvec::order::Lsb0> {
        // every validator confirms availability.
        bitvec::bitvec![u8, bitvec::order::Lsb0; 1; validators]
    }
16
    pub fn mock_head_data() -> HeadData {
16
        let max_head_size =
16
            runtime_parachains::configuration::ActiveConfig::<T>::get().max_head_data_size;
16
        HeadData(vec![0xFF; max_head_size as usize])
16
    }
    fn candidate_descriptor_mock(
        para_id: ParaId,
        candidate_descriptor_v2: bool,
    ) -> CandidateDescriptorV2<T::Hash> {
        if candidate_descriptor_v2 {
            CandidateDescriptorV2::new(
                para_id,
                Default::default(),
                CoreIndex(200),
                2,
                Default::default(),
                Default::default(),
                Default::default(),
                Default::default(),
                mock_validation_code().hash(),
            )
        } else {
            // Convert v1 to v2.
            CandidateDescriptor::<T::Hash> {
                para_id,
                relay_parent: Default::default(),
                collator: junk_collator(),
                persisted_validation_data_hash: Default::default(),
                pov_hash: Default::default(),
                erasure_root: Default::default(),
                signature: junk_collator_signature(),
                para_head: Default::default(),
                validation_code_hash: mock_validation_code().hash(),
            }
            .into()
        }
    }
    /*
    /// Create a mock of `CandidatePendingAvailability`.
    fn candidate_availability_mock(
        para_id: ParaId,
        group_idx: GroupIndex,
        core_idx: CoreIndex,
        candidate_hash: CandidateHash,
        availability_votes: BitVec<u8, bitvec::order::Lsb0>,
        commitments: CandidateCommitments,
        candidate_descriptor_v2: bool,
    ) -> CandidatePendingAvailability<T::Hash, BlockNumberFor<T>> {
        CandidatePendingAvailability::<T::Hash, BlockNumberFor<T>>::new(
            core_idx,                                                          // core
            candidate_hash,                                                    // hash
            Self::candidate_descriptor_mock(para_id, candidate_descriptor_v2), /* candidate descriptor */
            commitments,                                                       // commitments
            availability_votes,                                                /* availability
                                                                                            * votes */
            Default::default(), // backers
            Zero::zero(),       // relay parent
            One::one(),         /* relay chain block this
                                             * was backed in */
            group_idx, // backing group
        )
    }
     */
    /*
    /// Add `CandidatePendingAvailability` and `CandidateCommitments` to the relevant storage items.
    ///
    /// NOTE: the default `CandidateCommitments` used does not include any data that would lead to
    /// heavy code paths in `enact_candidate`. But enact_candidates does return a weight which will
    /// get taken into account.
    fn add_availability(
        para_id: ParaId,
        core_idx: CoreIndex,
        group_idx: GroupIndex,
        availability_votes: BitVec<u8, bitvec::order::Lsb0>,
        candidate_hash: CandidateHash,
        candidate_descriptor_v2: bool,
    ) {
        let commitments = CandidateCommitments::<u32> {
            upward_messages: Default::default(),
            horizontal_messages: Default::default(),
            new_validation_code: None,
            head_data: Self::mock_head_data(),
            processed_downward_messages: 0,
            hrmp_watermark: 0u32.into(),
        };
        let candidate_availability = Self::candidate_availability_mock(
            para_id,
            group_idx,
            core_idx,
            candidate_hash,
            availability_votes,
            commitments,
            candidate_descriptor_v2,
        );
        inclusion::PendingAvailability::<T>::mutate(para_id, |maybe_candidates| {
            if let Some(candidates) = maybe_candidates {
                candidates.push_back(candidate_availability);
            } else {
                *maybe_candidates =
                    Some([candidate_availability].into_iter().collect::<VecDeque<_>>());
            }
        });
    }
     */
    /// Number of the relay parent block.
16
    fn relay_parent_number(&self) -> u32 {
16
        (Self::block_number() - One::one())
16
            .try_into()
16
            .map_err(|_| ())
16
            .expect("Self::block_number() is u32")
16
    }
    /// Create backed candidates for `cores_with_backed_candidates`. You need these cores to be
    /// scheduled _within_ paras inherent, which requires marking the available bitfields as fully
    /// available.
    /// - `cores_with_backed_candidates` Mapping of `para_id` seed to number of
    /// validity votes.
    /// Important! this uses a BtreeMap, which means that elements will use increasing core orders
    /// example: if we have parachains 1000, 1001, and 1002, they will use respectively cores
    /// 0 1 and 2. There is no way in which we force 1002 to use core 0 in this setup
99
    fn create_backed_candidates(
99
        &self,
99
        paras_with_backed_candidates: &BTreeMap<u32, u32>,
99
    ) -> Vec<BackedCandidate<T::Hash>> {
99
        let current_session = runtime_parachains::shared::CurrentSessionIndex::<T>::get();
99
        // We need to refetch validators since they have been shuffled.
99
        let validators_shuffled =
99
            runtime_parachains::session_info::Sessions::<T>::get(current_session)
99
                .unwrap()
99
                .validators
99
                .clone();
99

            
99
        let config = runtime_parachains::configuration::ActiveConfig::<T>::get();
99
        let mut current_core_idx = 0u32;
99
        paras_with_backed_candidates
99
            .iter()
99
            .flat_map(|(seed, num_votes)| {
8
                assert!(*num_votes <= validators_shuffled.len() as u32);
8
                let para_id = ParaId::from(*seed);
8
                let prev_head_non_mut = runtime_parachains::paras::Heads::<T>::get(para_id);
8
                let prev_head = prev_head_non_mut.unwrap_or(Self::mock_head_data());
8
                // How many chained candidates we want to build ?
8
                (0..1)
8
                    .map(|chain_idx| {
8
                        let core_idx = CoreIndex::from(current_core_idx);
8
                        // Advance core index.
8
                        current_core_idx += 1;
8
                        let group_idx =
8
                            Self::group_assigned_to_core(core_idx, Self::block_number())
8
                                .unwrap_or_else(|| {
                                    panic!("Validator group not assigned to core {:?}", core_idx)
8
                                });
8

            
8
                        let header = Self::header(Self::block_number());
8
                        let relay_parent = header.hash();
8

            
8
                        // Set the head data so it can be used while validating the signatures on
8
                        // the candidate receipt.
8
                        let mut head_data = Self::mock_head_data();
8

            
8
                        if chain_idx == 0 {
8
                            // Only first parahead of the chain needs to be set in storage.
8
                            Self::heads_insert(&para_id, prev_head.clone());
8
                        } else {
                            // Make each candidate head data unique to avoid cycles.
                            head_data.0[0] = chain_idx;
                        }
8
                        let persisted_validation_data = PersistedValidationData::<T::Hash> {
8
                            // To form a chain we set parent head to previous block if any, or
8
                            // default to what is in storage already setup.
8
                            parent_head: prev_head.clone(),
8
                            relay_parent_number: self.relay_parent_number() + 1,
8
                            relay_parent_storage_root: Default::default(),
8
                            max_pov_size: config.max_pov_size,
8
                        };
8

            
8
                        let persisted_validation_data_hash = persisted_validation_data.hash();
8

            
8
                        let pov_hash = Default::default();
8
                        let validation_code_hash = mock_validation_code().hash();
8

            
8
                        /*
8
                        let mut past_code_meta =
8
                            paras::ParaPastCodeMeta::<BlockNumberFor<T>>::default();
8
                        past_code_meta.note_replacement(0u32.into(), 0u32.into());
8
                         */
8

            
8
                        let group_validators = Self::group_validators(group_idx).unwrap();
8
                        let descriptor = if true
                        /* self.candidate_descriptor_v2 */
                        {
8
                            CandidateDescriptorV2::new(
8
                                para_id,
8
                                relay_parent,
8
                                core_idx,
8
                                current_session,
8
                                persisted_validation_data_hash,
8
                                pov_hash,
8
                                Default::default(),
8
                                prev_head.hash(),
8
                                validation_code_hash,
8
                            )
                        } else {
                            todo!()
                        };
8
                        let mut candidate = CommittedCandidateReceiptV2::<T::Hash> {
8
                            descriptor,
8
                            commitments: CandidateCommitments::<u32> {
8
                                upward_messages: Default::default(),
8
                                horizontal_messages: Default::default(),
8
                                new_validation_code: None,
8
                                head_data: prev_head.clone(),
8
                                processed_downward_messages: 0,
8
                                hrmp_watermark: self.relay_parent_number() + 1,
8
                            },
8
                        };
8

            
8
                        if true
                        /* self.candidate_descriptor_v2 */
8
                        {
8
                            // `UMPSignal` separator.
8
                            candidate
8
                                .commitments
8
                                .upward_messages
8
                                .force_push(UMP_SEPARATOR);
8

            
8
                            // `SelectCore` commitment.
8
                            // Claim queue offset must be `0` so this candidate is for the very
8
                            // next block.
8
                            candidate.commitments.upward_messages.force_push(
8
                                UMPSignal::SelectCore(CoreSelector(chain_idx), ClaimQueueOffset(0))
8
                                    .encode(),
8
                            );
8
                        }
8
                        let candidate_hash = candidate.hash();
8

            
8
                        let validity_votes: Vec<_> = group_validators
8
                            .iter()
8
                            .take(*num_votes as usize)
8
                            .map(|val_idx| {
8
                                let public = validators_shuffled.get(*val_idx).unwrap();
8

            
8
                                let signature_ctx = SigningContext {
8
                                    parent_hash: Self::header(Self::block_number()).hash(),
8
                                    session_index: Session::current_index(),
8
                                };
8
                                let sig = UncheckedSigned::<CompactStatement>::benchmark_sign(
8
                                    public,
8
                                    CompactStatement::Valid(candidate_hash),
8
                                    &signature_ctx,
8
                                    *val_idx,
8
                                )
8
                                .benchmark_signature();
8

            
8
                                ValidityAttestation::Explicit(sig.clone())
8
                            })
8
                            .collect();
8

            
8
                        // Check if the elastic scaling bit is set, if so we need to supply the core
8
                        // index in the generated candidate.
8
                        let core_idx = runtime_parachains::configuration::ActiveConfig::<T>::get()
8
                            .node_features
8
                            .get(FeatureIndex::ElasticScalingMVP as usize)
8
                            .and_then(|the_bit| if *the_bit { Some(core_idx) } else { None })
8
                            .expect("ElasticScalingMVP feature index should be present");
8

            
8
                        assert_eq!(group_validators.len(), 1);
8
                        BackedCandidate::<T::Hash>::new(
8
                            candidate,
8
                            validity_votes,
8
                            bitvec::bitvec![u8, bitvec::order::Lsb0; 1; group_validators.len()],
8
                            core_idx,
8
                        )
8
                    })
8
                    .collect::<Vec<_>>()
99
            })
99
            .collect()
99
    }
    /// Get the group assigned to a specific core by index at the current block number. Result
    /// undefined if the core index is unknown or the block number is less than the session start
    /// index.
8
    pub(crate) fn group_assigned_to_core(
8
        core: CoreIndex,
8
        at: BlockNumberFor<T>,
8
    ) -> Option<GroupIndex> {
8
        let config = runtime_parachains::configuration::ActiveConfig::<T>::get();
8
        let session_start_block = runtime_parachains::scheduler::SessionStartBlock::<T>::get();
8

            
8
        if at < session_start_block {
            return None;
8
        }
8

            
8
        let validator_groups = runtime_parachains::scheduler::ValidatorGroups::<T>::get();
8

            
8
        if core.0 as usize >= validator_groups.len() {
            return None;
8
        }
8

            
8
        let rotations_since_session_start: BlockNumberFor<T> =
8
            (at - session_start_block) / config.scheduler_params.group_rotation_frequency;
8

            
8
        let rotations_since_session_start =
8
            <BlockNumberFor<T> as TryInto<u32>>::try_into(rotations_since_session_start)
8
                .unwrap_or(0);
8
        // Error case can only happen if rotations occur only once every u32::max(),
8
        // so functionally no difference in behavior.
8

            
8
        let group_idx =
8
            (core.0 as usize + rotations_since_session_start as usize) % validator_groups.len();
8
        Some(GroupIndex(group_idx as u32))
8
    }
    /// Get the validators in the given group, if the group index is valid for this session.
8
    pub(crate) fn group_validators(group_index: GroupIndex) -> Option<Vec<ValidatorIndex>> {
8
        runtime_parachains::scheduler::ValidatorGroups::<T>::get()
8
            .get(group_index.0 as usize)
8
            .cloned()
8
    }
8
    pub fn heads_insert(para_id: &ParaId, head_data: HeadData) {
8
        runtime_parachains::paras::Heads::<T>::insert(para_id, head_data);
8
    }
    /// Build a scenario for testing.
    ///
    /// Note that this API only allows building scenarios where the `backed_and_concluding_paras`
    /// are mutually exclusive with the cores for disputes. So
    /// `backed_and_concluding_paras.len() + dispute_sessions.len() + backed_in_inherent_paras` must
    /// be less than the max number of cores.
99
    pub(crate) fn build(self) -> ParachainsInherentData<HeaderFor<T>> {
99
        let current_session = runtime_parachains::shared::CurrentSessionIndex::<T>::get();
99
        // We need to refetch validators since they have been shuffled.
99
        let validators = runtime_parachains::session_info::Sessions::<T>::get(current_session)
99
            .unwrap()
99
            .validators
99
            .clone();
99

            
99
        //let max_cores = self.max_cores() as usize;
99
        let max_cores = 2;
99

            
99
        let used_cores =
99
            self.backed_and_concluding_paras.len() + self.backed_in_inherent_paras.len();
99
        assert!(used_cores <= max_cores);
99
        let mut backed_in_inherent = BTreeMap::new();
99
        backed_in_inherent.append(&mut self.backed_and_concluding_paras.clone());
99
        backed_in_inherent.append(&mut self.backed_in_inherent_paras.clone());
99
        let backed_candidates = self.create_backed_candidates(&backed_in_inherent);
99
        let used_cores_set = (0..used_cores).map(|x| x as u32).collect();
99

            
99
        let availability_bitvec = Self::availability_bitvec(&used_cores_set, max_cores);
99

            
99
        let bitfields: Vec<UncheckedSigned<AvailabilityBitfield>> = validators
99
            .iter()
99
            .enumerate()
198
            .map(|(i, public)| {
198
                UncheckedSigned::<AvailabilityBitfield>::benchmark_sign(
198
                    public,
198
                    availability_bitvec.clone(),
198
                    &SigningContext {
198
                        parent_hash: Self::header(Self::block_number()).hash(),
198
                        session_index: Session::current_index(),
198
                    },
198
                    ValidatorIndex(i as u32),
198
                )
198
            })
99
            .collect();
99

            
99
        let data = ParachainsInherentData {
99
            bitfields,
99
            backed_candidates,
99
            disputes: vec![],
99
            parent_header: Self::header(Self::block_number()),
99
        };
99

            
99
        data
99
    }
337
    pub(crate) fn block_number() -> BlockNumberFor<T> {
337
        frame_system::Pallet::<T>::block_number()
337
    }
}
use {
    cumulus_primitives_core::relay_chain::SchedulerParams, frame_support::StorageHasher,
    tp_traits::ParathreadParams,
};
3
pub fn storage_map_final_key<H: frame_support::StorageHasher>(
3
    pallet_prefix: &str,
3
    map_name: &str,
3
    key: &[u8],
3
) -> Vec<u8> {
3
    let key_hashed = H::hash(key);
3
    let pallet_prefix_hashed = frame_support::Twox128::hash(pallet_prefix.as_bytes());
3
    let storage_prefix_hashed = frame_support::Twox128::hash(map_name.as_bytes());
3

            
3
    let mut final_key = Vec::with_capacity(
3
        pallet_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.as_ref().len(),
3
    );
3

            
3
    final_key.extend_from_slice(&pallet_prefix_hashed[..]);
3
    final_key.extend_from_slice(&storage_prefix_hashed[..]);
3
    final_key.extend_from_slice(key_hashed.as_ref());
3

            
3
    final_key
3
}
23
pub fn set_dummy_boot_node(para_manager: RuntimeOrigin, para_id: ParaId) {
    use {
        pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
        tp_data_preservers_common::{AssignerExtra, ProviderRequest},
    };
23
    let profile = Profile {
23
        url:
23
            b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
23
                .to_vec()
23
                .try_into()
23
                .expect("to fit in BoundedVec"),
23
        para_ids: ParaIdsFilter::AnyParaId,
23
        mode: ProfileMode::Bootnode,
23
        assignment_request: ProviderRequest::Free,
23
    };
23

            
23
    let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
23
    let profile_owner = AccountId::new([1u8; 32]);
23
    DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
23
        .expect("profile create to succeed");
23

            
23
    DataPreservers::start_assignment(para_manager, profile_id, para_id, AssignerExtra::Free)
23
        .expect("assignment to work");
23

            
23
    assert!(
23
        pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
        "profile should be correctly assigned"
    );
23
}
use milagro_bls::Keypair;
1
pub fn generate_ethereum_pub_keys(n: u32) -> Vec<Keypair> {
1
    let mut keys = vec![];
512
    for _i in 0..n {
512
        let keypair = Keypair::random(&mut rand::thread_rng());
512
        keys.push(keypair);
512
    }
1
    keys
1
}
use primitives::vstaging::{ClaimQueueOffset, CoreSelector, UMPSignal, UMP_SEPARATOR};
use primitives::{CandidateDescriptor, CollatorId, CollatorSignature};
use sp_core::ByteArray;
use {
    babe_primitives::AuthorityPair as BabeAuthorityPair,
    grandpa_primitives::{
        AuthorityPair as GrandpaAuthorityPair, Equivocation, EquivocationProof, RoundNumber, SetId,
    },
    sp_core::H256,
};
3
pub fn generate_grandpa_equivocation_proof(
3
    set_id: SetId,
3
    vote1: (RoundNumber, H256, u32, &GrandpaAuthorityPair),
3
    vote2: (RoundNumber, H256, u32, &GrandpaAuthorityPair),
3
) -> EquivocationProof<H256, u32> {
6
    let signed_prevote = |round, hash, number, authority_pair: &GrandpaAuthorityPair| {
6
        let prevote = finality_grandpa::Prevote {
6
            target_hash: hash,
6
            target_number: number,
6
        };
6

            
6
        let prevote_msg = finality_grandpa::Message::Prevote(prevote.clone());
6
        let payload = grandpa_primitives::localized_payload(round, set_id, &prevote_msg);
6
        let signed = authority_pair.sign(&payload);
6
        (prevote, signed)
6
    };
3
    let (prevote1, signed1) = signed_prevote(vote1.0, vote1.1, vote1.2, vote1.3);
3
    let (prevote2, signed2) = signed_prevote(vote2.0, vote2.1, vote2.2, vote2.3);
3

            
3
    EquivocationProof::new(
3
        set_id,
3
        Equivocation::Prevote(finality_grandpa::Equivocation {
3
            round_number: vote1.0,
3
            identity: vote1.3.public(),
3
            first: (prevote1, signed1),
3
            second: (prevote2, signed2),
3
        }),
3
    )
3
}
/// Creates an equivocation at the current block, by generating two headers.
8
pub fn generate_babe_equivocation_proof(
8
    offender_authority_pair: &BabeAuthorityPair,
8
) -> babe_primitives::EquivocationProof<crate::Header> {
    use babe_primitives::digests::CompatibleDigestItem;
8
    let current_digest = System::digest();
8
    let babe_predigest = current_digest
8
        .clone()
8
        .logs()
8
        .iter()
8
        .find_map(|log| log.as_babe_pre_digest());
8
    let slot_proof = babe_predigest.expect("babe should be presesnt").slot();
8

            
8
    let make_headers = || {
8
        (
8
            HeaderFor::<Runtime>::new(
8
                0,
8
                H256::default(),
8
                H256::default(),
8
                H256::default(),
8
                current_digest.clone(),
8
            ),
8
            HeaderFor::<Runtime>::new(
8
                1,
8
                H256::default(),
8
                H256::default(),
8
                H256::default(),
8
                current_digest.clone(),
8
            ),
8
        )
8
    };
    // sign the header prehash and sign it, adding it to the block as the seal
    // digest item
16
    let seal_header = |header: &mut crate::Header| {
16
        let prehash = header.hash();
16
        let seal = <DigestItem as CompatibleDigestItem>::babe_seal(
16
            offender_authority_pair.sign(prehash.as_ref()),
16
        );
16
        header.digest_mut().push(seal);
16
    };
    // generate two headers at the current block
8
    let (mut h1, mut h2) = make_headers();
8

            
8
    seal_header(&mut h1);
8
    seal_header(&mut h2);
8

            
8
    babe_primitives::EquivocationProof {
8
        slot: slot_proof,
8
        offender: offender_authority_pair.public(),
8
        first_header: h1,
8
        second_header: h2,
8
    }
8
}
/// Helper function to generate a crypto pair from seed
11
pub fn get_pair_from_seed<TPublic: Public>(seed: &str) -> TPublic::Pair {
11
    let secret_uri = format!("//{}", seed);
11
    let pair = TPublic::Pair::from_string(&secret_uri, None).expect("static values are valid; qed");
11

            
11
    pair
11
}
10
pub fn mock_snowbridge_message_proof() -> Proof {
10
    Proof {
10
        receipt_proof: (vec![], vec![]),
10
        execution_proof: ExecutionProof {
10
            header: Default::default(),
10
            ancestry_proof: None,
10
            execution_header: VersionedExecutionPayloadHeader::Deneb(
10
                deneb::ExecutionPayloadHeader {
10
                    parent_hash: Default::default(),
10
                    fee_recipient: Default::default(),
10
                    state_root: Default::default(),
10
                    receipts_root: Default::default(),
10
                    logs_bloom: vec![],
10
                    prev_randao: Default::default(),
10
                    block_number: 0,
10
                    gas_limit: 0,
10
                    gas_used: 0,
10
                    timestamp: 0,
10
                    extra_data: vec![],
10
                    base_fee_per_gas: Default::default(),
10
                    block_hash: Default::default(),
10
                    transactions_root: Default::default(),
10
                    withdrawals_root: Default::default(),
10
                    blob_gas_used: 0,
10
                    excess_blob_gas: 0,
10
                },
10
            ),
10
            execution_branch: vec![],
10
        },
10
    }
10
}