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
    alloc::collections::btree_map::BTreeMap,
25
    babe_primitives::{
26
        digests::{PreDigest, SecondaryPlainPreDigest},
27
        BABE_ENGINE_ID,
28
    },
29
    beefy_primitives::{ecdsa_crypto::AuthorityId as BeefyId, ConsensusLog, BEEFY_ENGINE_ID},
30
    bitvec::prelude::BitVec,
31
    cumulus_primitives_core::{
32
        relay_chain::{
33
            node_features::FeatureIndex, vstaging::BackedCandidate,
34
            vstaging::CandidateDescriptorV2, vstaging::CommittedCandidateReceiptV2,
35
            vstaging::InherentData as ParachainsInherentData, AvailabilityBitfield,
36
            CandidateCommitments, CompactStatement, CoreIndex, GroupIndex, HeadData,
37
            PersistedValidationData, SigningContext, UncheckedSigned, ValidationCode,
38
            ValidatorIndex, ValidityAttestation,
39
        },
40
        ParaId,
41
    },
42
    frame_support::{
43
        assert_ok,
44
        traits::{OnFinalize, OnInitialize},
45
        BoundedVec,
46
    },
47
    frame_system::pallet_prelude::{BlockNumberFor, HeaderFor},
48
    nimbus_primitives::NimbusId,
49
    pallet_registrar_runtime_api::ContainerChainGenesisData,
50
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
51
    parity_scale_codec::{Decode, Encode, MaxEncodedLen},
52
    runtime_parachains::{
53
        paras::{ParaGenesisArgs, ParaKind},
54
        paras_inherent as parachains_paras_inherent,
55
    },
56
    snowbridge_beacon_primitives::{types::deneb, ExecutionProof, VersionedExecutionPayloadHeader},
57
    snowbridge_verification_primitives::Proof,
58
    sp_core::Pair,
59
    sp_core::Public,
60
    sp_keystore::{KeystoreExt, KeystorePtr},
61
    sp_runtime::{
62
        traits::{Dispatchable, Header, One, SaturatedConversion, Zero},
63
        BuildStorage, Digest, DigestItem,
64
    },
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
187
pub fn session_to_block(n: u32) -> u32 {
87
    // let block_number = flashbox_runtime::Period::get() * n;
88
187
    let block_number = Babe::current_epoch().duration.saturated_into::<u32>() * n;
89

            
90
    // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
91
    // so this is the first block of the new session that can actually be used
92
187
    block_number + 1
93
187
}
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
656
210
        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
204
        }
683

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

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

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

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

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

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

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

            
776
210
        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
210
        }
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
210
        t.top.insert(
785
210
            b"ParasInherentEnabled".to_vec(),
786
210
            self.inherent_data_enabled.encode(),
787
        );
788

            
789
210
        t
790
210
    }
791

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

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

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

            
815
101
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
816
101
    <Runtime as frame_system::Config>::RuntimeOrigin::none()
817
101
}
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
139
pub fn empty_genesis_data() -> ContainerChainGenesisData {
833
139
    ContainerChainGenesisData {
834
139
        storage: Default::default(),
835
139
        name: Default::default(),
836
139
        id: Default::default(),
837
139
        fork_id: Default::default(),
838
139
        extensions: Default::default(),
839
139
        properties: Default::default(),
840
139
    }
841
139
}
842

            
843
3808
pub fn current_slot() -> u64 {
844
3808
    Babe::current_slot().into()
845
3808
}
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
92
fn take_new_inherent_data() -> Option<cumulus_primitives_core::relay_chain::vstaging::InherentData>
869
{
870
92
    let data: Option<cumulus_primitives_core::relay_chain::vstaging::InherentData> =
871
92
        frame_support::storage::unhashed::take(b"ParasInherentData");
872

            
873
92
    data
874
92
}
875

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

            
882
// Set new data to inject in paras inherent
883
7
pub fn set_new_inherent_data(data: cumulus_primitives_core::relay_chain::vstaging::InherentData) {
884
7
    frame_support::storage::unhashed::put(b"ParasInherentData", &data);
885
7
}
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
92
pub fn set_paras_inherent(data: cumulus_primitives_core::relay_chain::vstaging::InherentData) {
895
    // In order for this inherent to work, we need to match the parent header
896
    // the parent header does not play a significant role in the rest of the framework so
897
    // we are simply going to mock it
898
92
    System::set_parent_hash(data.parent_header.hash());
899
92
    assert_ok!(
900
92
        RuntimeCall::ParaInherent(parachains_paras_inherent::Call::<Runtime>::enter { data })
901
92
            .dispatch(inherent_origin())
902
    );
903
    // Error: InherentDataFilteredDuringExecution
904
89
    frame_support::storage::unhashed::kill(&frame_support::storage::storage_prefix(
905
89
        b"ParaInherent",
906
89
        b"Included",
907
89
    ));
908
89
}
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
192
pub fn mock_validation_code() -> ValidationCode {
928
192
    ValidationCode(vec![1; 10])
929
192
}
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((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((0..64).collect::<Vec<_>>().as_slice()).expect("64 bytes; qed")
939
}
940

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

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

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

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

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

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

            
993
    /// Maximum number of validators per core (a.k.a. max validators per group). This value is used
994
    /// if none is explicitly set on the builder.
995
    pub(crate) fn fallback_max_validators_per_core() -> u32 {
996
        runtime_parachains::configuration::ActiveConfig::<T>::get()
997
            .scheduler_params
998
            .max_validators_per_core
999
            .unwrap_or(5)
    }
    /// Get the maximum number of validators per core.
    fn max_validators_per_core(&self) -> u32 {
        Self::fallback_max_validators_per_core()
    }
    /// Get the maximum number of cores we expect from this configuration.
    pub(crate) fn max_cores(&self) -> u32 {
        self.max_validators() / self.max_validators_per_core()
    }
    /// Create an `AvailabilityBitfield` where `concluding` is a map where each key is a core index
    /// that is concluding and `cores` is the total number of cores in the system.
99
    fn availability_bitvec(concluding_cores: &BTreeSet<u32>, cores: usize) -> AvailabilityBitfield {
99
        let mut bitfields = bitvec::bitvec![u8, bitvec::order::Lsb0; 0; 0];
198
        for i in 0..cores {
198
            if concluding_cores.contains(&(i as u32)) {
8
                bitfields.push(true);
8
            } else {
190
                bitfields.push(false)
            }
        }
99
        bitfields.into()
99
    }
    /// Create a bitvec of `validators` length with all yes votes.
    fn validator_availability_votes_yes(validators: usize) -> BitVec<u8, bitvec::order::Lsb0> {
        // every validator confirms availability.
        bitvec::bitvec![u8, bitvec::order::Lsb0; 1; validators]
    }
16
    pub fn mock_head_data() -> HeadData {
16
        let max_head_size =
16
            runtime_parachains::configuration::ActiveConfig::<T>::get().max_head_data_size;
16
        HeadData(vec![0xFF; max_head_size as usize])
16
    }
    fn candidate_descriptor_mock(
        para_id: ParaId,
        candidate_descriptor_v2: bool,
    ) -> CandidateDescriptorV2<T::Hash> {
        if candidate_descriptor_v2 {
            CandidateDescriptorV2::new(
                para_id,
                Default::default(),
                CoreIndex(200),
                2,
                Default::default(),
                Default::default(),
                Default::default(),
                Default::default(),
                mock_validation_code().hash(),
            )
        } else {
            // Convert v1 to v2.
            CandidateDescriptor::<T::Hash> {
                para_id,
                relay_parent: Default::default(),
                collator: junk_collator(),
                persisted_validation_data_hash: Default::default(),
                pov_hash: Default::default(),
                erasure_root: Default::default(),
                signature: junk_collator_signature(),
                para_head: Default::default(),
                validation_code_hash: mock_validation_code().hash(),
            }
            .into()
        }
    }
    /*
    /// Create a mock of `CandidatePendingAvailability`.
    fn candidate_availability_mock(
        para_id: ParaId,
        group_idx: GroupIndex,
        core_idx: CoreIndex,
        candidate_hash: CandidateHash,
        availability_votes: BitVec<u8, bitvec::order::Lsb0>,
        commitments: CandidateCommitments,
        candidate_descriptor_v2: bool,
    ) -> CandidatePendingAvailability<T::Hash, BlockNumberFor<T>> {
        CandidatePendingAvailability::<T::Hash, BlockNumberFor<T>>::new(
            core_idx,                                                          // core
            candidate_hash,                                                    // hash
            Self::candidate_descriptor_mock(para_id, candidate_descriptor_v2), /* candidate descriptor */
            commitments,                                                       // commitments
            availability_votes,                                                /* availability
                                                                                            * votes */
            Default::default(), // backers
            Zero::zero(),       // relay parent
            One::one(),         /* relay chain block this
                                             * was backed in */
            group_idx, // backing group
        )
    }
     */
    /*
    /// Add `CandidatePendingAvailability` and `CandidateCommitments` to the relevant storage items.
    ///
    /// NOTE: the default `CandidateCommitments` used does not include any data that would lead to
    /// heavy code paths in `enact_candidate`. But enact_candidates does return a weight which will
    /// get taken into account.
    fn add_availability(
        para_id: ParaId,
        core_idx: CoreIndex,
        group_idx: GroupIndex,
        availability_votes: BitVec<u8, bitvec::order::Lsb0>,
        candidate_hash: CandidateHash,
        candidate_descriptor_v2: bool,
    ) {
        let commitments = CandidateCommitments::<u32> {
            upward_messages: Default::default(),
            horizontal_messages: Default::default(),
            new_validation_code: None,
            head_data: Self::mock_head_data(),
            processed_downward_messages: 0,
            hrmp_watermark: 0u32.into(),
        };
        let candidate_availability = Self::candidate_availability_mock(
            para_id,
            group_idx,
            core_idx,
            candidate_hash,
            availability_votes,
            commitments,
            candidate_descriptor_v2,
        );
        inclusion::PendingAvailability::<T>::mutate(para_id, |maybe_candidates| {
            if let Some(candidates) = maybe_candidates {
                candidates.push_back(candidate_availability);
            } else {
                *maybe_candidates =
                    Some([candidate_availability].into_iter().collect::<VecDeque<_>>());
            }
        });
    }
     */
    /// Number of the relay parent block.
16
    fn relay_parent_number(&self) -> u32 {
16
        (Self::block_number() - One::one())
16
            .try_into()
16
            .map_err(|_| ())
16
            .expect("Self::block_number() is u32")
16
    }
    /// Create backed candidates for `cores_with_backed_candidates`. You need these cores to be
    /// scheduled _within_ paras inherent, which requires marking the available bitfields as fully
    /// available.
    /// - `cores_with_backed_candidates` Mapping of `para_id` seed to number of validity votes.
    ///   Important! this uses a BtreeMap, which means that elements will use increasing core orders
    ///   Example: if we have parachains 1000, 1001, and 1002, they will use respectively cores
    ///   0, 1 and 2. There is no way in which we force 1002 to use core 0 in this setup
99
    fn create_backed_candidates(
99
        &self,
99
        paras_with_backed_candidates: &BTreeMap<u32, u32>,
99
    ) -> Vec<BackedCandidate<T::Hash>> {
99
        let current_session = runtime_parachains::shared::CurrentSessionIndex::<T>::get();
        // 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
        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());
                // How many chained candidates we want to build ?
8
                (0..1)
8
                    .map(|chain_idx| {
8
                        let core_idx = CoreIndex::from(current_core_idx);
                        // 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
                        let header = Self::header(Self::block_number());
8
                        let relay_parent = header.hash();
                        // Set the head data so it can be used while validating the signatures on
                        // the candidate receipt.
8
                        let mut head_data = Self::mock_head_data();
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
                        let persisted_validation_data_hash = persisted_validation_data.hash();
8
                        let pov_hash = Default::default();
8
                        let validation_code_hash = mock_validation_code().hash();
                        /*
                        let mut past_code_meta =
                            paras::ParaPastCodeMeta::<BlockNumberFor<T>>::default();
                        past_code_meta.note_replacement(0u32.into(), 0u32.into());
                         */
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,
                            )
                        } 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
                        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
                        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
                                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
                                ValidityAttestation::Explicit(sig.clone())
8
                            })
8
                            .collect();
                        // Check if the elastic scaling bit is set, if so we need to supply the core
                        // 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
                        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
                    .collect::<Vec<_>>()
8
            })
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
        if at < session_start_block {
            return None;
8
        }
8
        let validator_groups = runtime_parachains::scheduler::ValidatorGroups::<T>::get();
8
        if core.0 as usize >= validator_groups.len() {
            return None;
8
        }
8
        let rotations_since_session_start: BlockNumberFor<T> =
8
            (at - session_start_block) / config.scheduler_params.group_rotation_frequency;
8
        let rotations_since_session_start =
8
            <BlockNumberFor<T> as TryInto<u32>>::try_into(rotations_since_session_start)
8
                .unwrap_or(0);
        // Error case can only happen if rotations occur only once every u32::max(),
        // so functionally no difference in behavior.
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();
        // 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();
        //let max_cores = self.max_cores() as usize;
99
        let max_cores = 2;
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
        let availability_bitvec = Self::availability_bitvec(&used_cores_set, max_cores);
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
            })
99
            .collect();
99
        ParachainsInherentData {
99
            bitfields,
99
            backed_candidates,
99
            disputes: vec![],
99
            parent_header: Self::header(Self::block_number()),
99
        }
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
    let mut final_key = Vec::with_capacity(
3
        pallet_prefix_hashed.len() + storage_prefix_hashed.len() + key_hashed.as_ref().len(),
    );
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
    final_key
3
}
23
pub fn set_dummy_boot_node(para_manager: RuntimeOrigin, para_id: ParaId) {
    use {
        pallet_data_preservers::{NodeType, ParaIdsFilter, Profile},
        tp_data_preservers_common::{AssignerExtra, ProviderRequest},
    };
23
    let profile = Profile {
23
        bootnode_url: Some(
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
        ),
23
        direct_rpc_urls: Default::default(),
23
        proxy_rpc_urls: Default::default(),
23
        para_ids: ParaIdsFilter::AnyParaId,
23
        node_type: NodeType::Substrate,
23
        assignment_request: ProviderRequest::Free,
23
        additional_info: Default::default(),
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
    DataPreservers::start_assignment(para_manager, profile_id, para_id, AssignerExtra::Free)
23
        .expect("assignment to work");
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
        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
    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
}
/// 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
    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
        header.digest_mut().push(seal);
16
    };
    // generate two headers at the current block
8
    let (mut h1, mut h2) = make_headers();
8
    seal_header(&mut h1);
8
    seal_header(&mut h2);
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
    TPublic::Pair::from_string(&secret_uri, None).expect("static values are valid; qed")
11
}
20
pub fn mock_snowbridge_message_proof() -> Proof {
20
    Proof {
20
        receipt_proof: (vec![], vec![]),
20
        execution_proof: ExecutionProof {
20
            header: Default::default(),
20
            ancestry_proof: None,
20
            execution_header: VersionedExecutionPayloadHeader::Deneb(
20
                deneb::ExecutionPayloadHeader {
20
                    parent_hash: Default::default(),
20
                    fee_recipient: Default::default(),
20
                    state_root: Default::default(),
20
                    receipts_root: Default::default(),
20
                    logs_bloom: vec![],
20
                    prev_randao: Default::default(),
20
                    block_number: 0,
20
                    gas_limit: 0,
20
                    gas_used: 0,
20
                    timestamp: 0,
20
                    extra_data: vec![],
20
                    base_fee_per_gas: Default::default(),
20
                    block_hash: Default::default(),
20
                    transactions_root: Default::default(),
20
                    withdrawals_root: Default::default(),
20
                    blob_gas_used: 0,
20
                    excess_blob_gas: 0,
20
                },
20
            ),
20
            execution_branch: vec![],
20
        },
20
    }
20
}