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, InflationRewards, Initializer, Mmr, Runtime, RuntimeOrigin, Session,
74
    System, TanssiAuthorityAssignment, TanssiCollatorAssignment, TransactionPayment,
75
};
76

            
77
pub const UNIT: Balance = 1_000_000_000_000;
78

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

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

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

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

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

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

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

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

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

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

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

            
151
263
    let mut summaries = BTreeMap::new();
152

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

            
159
263
    summaries
160
263
}
161

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

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

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

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

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

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

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

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

            
264
3602
    let block_number = System::block_number();
265
3602
    advance_block_state_machine(RunBlockState::Start(block_number + 1));
266
3602

            
267
3602
    insert_authorities_and_slot_digests(current_slot() + 1);
268
3602

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

            
276
3602
    Initializer::on_initialize(System::block_number());
277
3602
    TanssiCollatorAssignment::on_initialize(System::block_number());
278
3602
    MessageQueue::on_initialize(System::block_number());
279
3602

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

            
284
3602
    if let Some(mock_inherent_data) = mock_inherent_data {
285
92
        set_paras_inherent(mock_inherent_data);
286
3510
    }
287

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

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

            
313
3436
pub fn run_block() -> RunSummary {
314
3436
    end_block();
315
3436

            
316
3436
    start_block()
317
3436
}
318

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

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

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

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

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

            
409
impl ExtBuilder {
410
132
    pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
411
132
        self.balances = balances;
412
132
        self
413
132
    }
414

            
415
1
    pub fn with_sudo(mut self, sudo: AccountId) -> Self {
416
1
        self.sudo = Some(sudo);
417
1
        self
418
1
    }
419

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

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

            
430
76
    pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
431
76
        self.collators = collators;
432
76
        self
433
76
    }
434

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

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

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

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

            
480
    pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
481
        self.safe_xcm_version = Some(safe_xcm_version);
482
        self
483
    }
484

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

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

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

            
506
7
    pub fn with_inherent_data_enabled(mut self) -> Self {
507
7
        self.inherent_data_enabled = true;
508
7
        self
509
7
    }
510

            
511
164
    pub fn build_storage(self) -> sp_core::storage::Storage {
512
164
        let mut t = frame_system::GenesisConfig::<Runtime>::default()
513
164
            .build_storage()
514
164
            .unwrap();
515
164

            
516
164
        pallet_babe::GenesisConfig::<Runtime> {
517
164
            ..Default::default()
518
164
        }
519
164
        .assimilate_storage(&mut t)
520
164
        .unwrap();
521
164

            
522
164
        pallet_balances::GenesisConfig::<Runtime> {
523
164
            balances: self.balances,
524
164
            ..Default::default()
525
164
        }
526
164
        .assimilate_storage(&mut t)
527
164
        .unwrap();
528
164

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

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

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

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

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

            
602
164
        pallet_configuration::GenesisConfig::<Runtime> {
603
164
            config: self.config,
604
164
            ..Default::default()
605
164
        }
606
164
        .assimilate_storage(&mut t)
607
164
        .unwrap();
608
164

            
609
164
        pallet_xcm::GenesisConfig::<Runtime> {
610
164
            safe_xcm_version: self.safe_xcm_version,
611
164
            ..Default::default()
612
164
        }
613
164
        .assimilate_storage(&mut t)
614
164
        .unwrap();
615
164

            
616
164
        runtime_parachains::configuration::GenesisConfig::<Runtime> {
617
164
            config: self.relay_config,
618
164
        }
619
164
        .assimilate_storage(&mut t)
620
164
        .unwrap();
621
164

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

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

            
680
164
        if !self.collators.is_empty() {
681
            // We set invulnerables in pallet_invulnerables
682
76
            let invulnerables: Vec<AccountId> = self
683
76
                .collators
684
76
                .clone()
685
76
                .into_iter()
686
245
                .map(|(account, _balance)| account)
687
76
                .collect();
688
76

            
689
76
            pallet_invulnerables::GenesisConfig::<Runtime> {
690
76
                invulnerables: invulnerables.clone(),
691
76
            }
692
76
            .assimilate_storage(&mut t)
693
76
            .unwrap();
694
76

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

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

            
751
164
        pallet_session::GenesisConfig::<Runtime> {
752
164
            keys,
753
164
            non_authority_keys,
754
164
        }
755
164
        .assimilate_storage(&mut t)
756
164
        .unwrap();
757
164

            
758
164
        pallet_sudo::GenesisConfig::<Runtime> { key: self.sudo }
759
164
            .assimilate_storage(&mut t)
760
164
            .unwrap();
761
164

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

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

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

            
785
164
        t
786
164
    }
787

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

            
803
155
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
804
155
    <Runtime as frame_system::Config>::RuntimeOrigin::root()
805
155
}
806

            
807
340
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
808
340
    <Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
809
340
}
810

            
811
100
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
812
100
    <Runtime as frame_system::Config>::RuntimeOrigin::none()
813
100
}
814

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

            
822
8
    assert_ok!(RuntimeCall::AuthorNoting(
823
8
        pallet_author_noting::Call::<Runtime>::set_latest_author_data { data: () }
824
8
    )
825
8
    .dispatch(inherent_origin()));
826
8
}
827

            
828
133
pub fn empty_genesis_data() -> ContainerChainGenesisData {
829
133
    ContainerChainGenesisData {
830
133
        storage: Default::default(),
831
133
        name: Default::default(),
832
133
        id: Default::default(),
833
133
        fork_id: Default::default(),
834
133
        extensions: Default::default(),
835
133
        properties: Default::default(),
836
133
    }
837
133
}
838

            
839
3602
pub fn current_slot() -> u64 {
840
3602
    Babe::current_slot().into()
841
3602
}
842

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

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

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

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

            
869
92
    data
870
92
}
871

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

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

            
883
1
pub fn set_new_randomness_data(data: Option<[u8; 32]>) {
884
1
    pallet_babe::AuthorVrfRandomness::<Runtime>::set(data);
885
1
}
886

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

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

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

            
923
186
pub fn mock_validation_code() -> ValidationCode {
924
186
    ValidationCode(vec![1; 10])
925
186
}
926

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

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

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

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

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

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

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

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

            
990
    /// Maximum number of validators per core (a.k.a. max validators per group). This value is used
991
    /// if none is explicitly set on the builder.
992
    pub(crate) fn fallback_max_validators_per_core() -> u32 {
993
        runtime_parachains::configuration::ActiveConfig::<T>::get()
994
            .scheduler_params
995
            .max_validators_per_core
996
            .unwrap_or(5)
997
    }
998

            
999
    /// 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;
pub fn generate_ethereum_pub_keys(n: u32) -> Vec<Keypair> {
    let mut keys = vec![];
    for _i in 0..n {
        let keypair = Keypair::random(&mut rand::thread_rng());
        keys.push(keypair);
    }
    keys
}
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
}
7
pub fn mock_snowbridge_message_proof() -> Proof {
7
    Proof {
7
        receipt_proof: (vec![], vec![]),
7
        execution_proof: ExecutionProof {
7
            header: Default::default(),
7
            ancestry_proof: None,
7
            execution_header: VersionedExecutionPayloadHeader::Deneb(
7
                deneb::ExecutionPayloadHeader {
7
                    parent_hash: Default::default(),
7
                    fee_recipient: Default::default(),
7
                    state_root: Default::default(),
7
                    receipts_root: Default::default(),
7
                    logs_bloom: vec![],
7
                    prev_randao: Default::default(),
7
                    block_number: 0,
7
                    gas_limit: 0,
7
                    gas_used: 0,
7
                    timestamp: 0,
7
                    extra_data: vec![],
7
                    base_fee_per_gas: Default::default(),
7
                    block_hash: Default::default(),
7
                    transactions_root: Default::default(),
7
                    withdrawals_root: Default::default(),
7
                    blob_gas_used: 0,
7
                    excess_blob_gas: 0,
7
                },
7
            ),
7
            execution_branch: vec![],
7
        },
7
    }
7
}