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_core::inbound::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
265
pub fn run_to_block(n: u32) -> BTreeMap<u32, RunSummary> {
144
265
    let current_block_number = System::block_number();
145
265
    assert!(
146
265
        current_block_number < n,
147
        "run_to_block called with block {} when current block is {}",
148
        n,
149
        current_block_number
150
    );
151

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

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

            
160
265
    summaries
161
265
}
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
3676
pub fn insert_authorities_and_slot_digests(slot: u64) {
178
3676
    let pre_digest = Digest {
179
3676
        logs: vec![DigestItem::PreRuntime(
180
3676
            BABE_ENGINE_ID,
181
3676
            PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
182
3676
                slot: slot.into(),
183
3676
                authority_index: 0,
184
3676
            })
185
3676
            .encode(),
186
3676
        )],
187
3676
    };
188
3676

            
189
3676
    System::reset_events();
190
3676
    System::initialize(
191
3676
        &(System::block_number() + 1),
192
3676
        &System::parent_hash(),
193
3676
        &pre_digest,
194
3676
    );
195
3676
}
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
3498
    Start(u32),
205
3498
    End(u32),
206
}
207

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

            
233
7174
fn advance_block_state_machine(new_state: RunBlockState) {
234
7174
    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
7174
    }
239
7174
    let old_state: RunBlockState =
240
7174
        frame_support::storage::unhashed::get(b"__mock_debug_block_state").unwrap_or(
241
7174
            // Initial state is expecting a call to start() with block number 1, so old state should be
242
7174
            // end of block 0
243
7174
            RunBlockState::End(0),
244
7174
        );
245
7174
    old_state.assert_can_advance(&new_state);
246
7174
    frame_support::storage::unhashed::put(b"__mock_debug_block_state", &new_state);
247
7174
}
248

            
249
3676
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
3676
    let mock_inherent_data: Option<cumulus_primitives_core::relay_chain::vstaging::InherentData> =
255
3676
        if is_para_inherent_enabled() {
256
            // We check the inherent data in storage else we construct an empty one
257
96
            Some(
258
96
                take_new_inherent_data()
259
96
                    .unwrap_or(ParasInherentTestBuilder::<Runtime>::new().build()),
260
96
            )
261
        } else {
262
3580
            None
263
        };
264

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

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

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

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

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

            
285
3676
    if let Some(mock_inherent_data) = mock_inherent_data {
286
96
        set_paras_inherent(mock_inherent_data);
287
3580
    }
288

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

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

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

            
319
3496
    start_block()
320
3496
}
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
178
pub fn default_config() -> pallet_configuration::HostConfiguration {
344
178
    pallet_configuration::HostConfiguration {
345
178
        max_collators: 100,
346
178
        min_orchestrator_collators: 2,
347
178
        max_orchestrator_collators: 2,
348
178
        collators_per_container: 2,
349
178
        full_rotation_period: 0,
350
178
        ..Default::default()
351
178
    }
352
178
}
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
178
    fn default() -> Self {
380
178
        Self {
381
178
            balances: vec![
382
178
                // Alice gets 10k extra tokens for her mapping deposit
383
178
                (AccountId::from(ALICE), 210_000 * UNIT),
384
178
                (AccountId::from(BOB), 100_000 * UNIT),
385
178
            ],
386
178
            validators: vec![
387
178
                (AccountId::from(ALICE), 210 * UNIT),
388
178
                (AccountId::from(BOB), 100 * UNIT),
389
178
            ],
390
178
            external_validators: vec![],
391
178
            collators: Default::default(),
392
178
            sudo: Default::default(),
393
178
            para_ids: Default::default(),
394
178
            config: default_config(),
395
178
            relay_config: runtime_parachains::configuration::HostConfiguration {
396
178
                scheduler_params: SchedulerParams {
397
178
                    num_cores: 6,
398
178
                    ..Default::default()
399
178
                },
400
178
                max_head_data_size: 20500,
401
178
                ..Default::default()
402
178
            },
403
178
            own_para_id: Default::default(),
404
178
            next_free_para_id: Default::default(),
405
178
            keystore: None,
406
178
            safe_xcm_version: Default::default(),
407
178
            inherent_data_enabled: false,
408
178
        }
409
178
    }
410
}
411

            
412
impl ExtBuilder {
413
149
    pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
414
149
        self.balances = balances;
415
149
        self
416
149
    }
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
78
    pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
434
78
        self.collators = collators;
435
78
        self
436
78
    }
437

            
438
13
    pub fn with_para_ids(mut self, para_ids: Vec<ParaRegistrationParams>) -> Self {
439
13
        self.para_ids = para_ids;
440
13
        self
441
13
    }
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
19
    pub fn with_config(mut self, config: pallet_configuration::HostConfiguration) -> Self {
479
19
        self.config = config;
480
19
        self
481
19
    }
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
13
    pub fn with_relay_config(
490
13
        mut self,
491
13
        relay_config: runtime_parachains::configuration::HostConfiguration<BlockNumberFor<Runtime>>,
492
13
    ) -> Self {
493
13
        self.relay_config = relay_config;
494
13
        self
495
13
    }
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
8
    pub fn with_keystore(mut self, keystore: KeystorePtr) -> Self {
505
8
        self.keystore = Some(keystore);
506
8
        self
507
8
    }
508

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

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

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

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

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

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

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

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

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

            
604
178
        // TODO: add here pallet_services_payment::GenesisConfig
605
178

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
789
178
        t
790
178
    }
791

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

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

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

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

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

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

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

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

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

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

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

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

            
873
96
    data
874
96
}
875

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
994
    /// Maximum number of validators per core (a.k.a. max validators per group). This value is used
995
    /// if none is explicitly set on the builder.
996
    pub(crate) fn fallback_max_validators_per_core() -> u32 {
997
        runtime_parachains::configuration::ActiveConfig::<T>::get()
998
            .scheduler_params
999
            .max_validators_per_core
            .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.
104
    fn availability_bitvec(concluding_cores: &BTreeSet<u32>, cores: usize) -> AvailabilityBitfield {
104
        let mut bitfields = bitvec::bitvec![u8, bitvec::order::Lsb0; 0; 0];
208
        for i in 0..cores {
208
            if concluding_cores.contains(&(i as u32)) {
9
                bitfields.push(true);
9
            } else {
199
                bitfields.push(false)
            }
        }
104
        bitfields.into()
104
    }
    /// 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]
    }
18
    pub fn mock_head_data() -> HeadData {
18
        let max_head_size =
18
            runtime_parachains::configuration::ActiveConfig::<T>::get().max_head_data_size;
18
        HeadData(vec![0xFF; max_head_size as usize])
18
    }
    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.
18
    fn relay_parent_number(&self) -> u32 {
18
        (Self::block_number() - One::one())
18
            .try_into()
18
            .map_err(|_| ())
18
            .expect("Self::block_number() is u32")
18
    }
    /// 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
104
    fn create_backed_candidates(
104
        &self,
104
        paras_with_backed_candidates: &BTreeMap<u32, u32>,
104
    ) -> Vec<BackedCandidate<T::Hash>> {
104
        let current_session = runtime_parachains::shared::CurrentSessionIndex::<T>::get();
104
        // We need to refetch validators since they have been shuffled.
104
        let validators_shuffled =
104
            runtime_parachains::session_info::Sessions::<T>::get(current_session)
104
                .unwrap()
104
                .validators
104
                .clone();
104

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

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

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

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

            
9
                        let persisted_validation_data_hash = persisted_validation_data.hash();
9

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

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

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

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

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

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

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

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

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

            
9
                        assert_eq!(group_validators.len(), 1);
9
                        BackedCandidate::<T::Hash>::new(
9
                            candidate,
9
                            validity_votes,
9
                            bitvec::bitvec![u8, bitvec::order::Lsb0; 1; group_validators.len()],
9
                            core_idx,
9
                        )
9
                    })
9
                    .collect::<Vec<_>>()
104
            })
104
            .collect()
104
    }
    /// 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.
9
    pub(crate) fn group_assigned_to_core(
9
        core: CoreIndex,
9
        at: BlockNumberFor<T>,
9
    ) -> Option<GroupIndex> {
9
        let config = runtime_parachains::configuration::ActiveConfig::<T>::get();
9
        let session_start_block = runtime_parachains::scheduler::SessionStartBlock::<T>::get();
9

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

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

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

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

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

            
9
        let group_idx =
9
            (core.0 as usize + rotations_since_session_start as usize) % validator_groups.len();
9
        Some(GroupIndex(group_idx as u32))
9
    }
    /// Get the validators in the given group, if the group index is valid for this session.
9
    pub(crate) fn group_validators(group_index: GroupIndex) -> Option<Vec<ValidatorIndex>> {
9
        runtime_parachains::scheduler::ValidatorGroups::<T>::get()
9
            .get(group_index.0 as usize)
9
            .cloned()
9
    }
9
    pub fn heads_insert(para_id: &ParaId, head_data: HeadData) {
9
        runtime_parachains::paras::Heads::<T>::insert(para_id, head_data);
9
    }
    /// 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.
104
    pub(crate) fn build(self) -> ParachainsInherentData<HeaderFor<T>> {
104
        let current_session = runtime_parachains::shared::CurrentSessionIndex::<T>::get();
104
        // We need to refetch validators since they have been shuffled.
104
        let validators = runtime_parachains::session_info::Sessions::<T>::get(current_session)
104
            .unwrap()
104
            .validators
104
            .clone();
104

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

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

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

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

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

            
104
        data
104
    }
357
    pub(crate) fn block_number() -> BlockNumberFor<T> {
357
        frame_system::Pallet::<T>::block_number()
357
    }
}
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
}