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
use {
18
    core::cell::Cell,
19
    cumulus_primitives_core::{ParaId, PersistedValidationData},
20
    cumulus_primitives_parachain_inherent::ParachainInherentData,
21
    dancebox_runtime::{
22
        AuthorInherent, BlockProductionCost, CollatorAssignmentCost, RuntimeOrigin,
23
    },
24
    dp_consensus::runtime_decl_for_tanssi_authority_assignment_api::TanssiAuthorityAssignmentApi,
25
    frame_support::{
26
        assert_ok,
27
        traits::{OnFinalize, OnInitialize},
28
    },
29
    nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID},
30
    pallet_registrar_runtime_api::ContainerChainGenesisData,
31
    pallet_services_payment::{ProvideBlockProductionCost, ProvideCollatorAssignmentCost},
32
    parity_scale_codec::{Decode, Encode, MaxEncodedLen},
33
    polkadot_parachain_primitives::primitives::HeadData,
34
    sp_consensus_aura::AURA_ENGINE_ID,
35
    sp_consensus_slots::Slot,
36
    sp_core::{Get, Pair},
37
    sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem},
38
    std::{collections::BTreeMap, thread_local},
39
    test_relay_sproof_builder::ParaHeaderSproofBuilder,
40
};
41

            
42
pub use dancebox_runtime::{
43
    AccountId, AssetRate, AuthorNoting, AuthorityAssignment, AuthorityMapping, Balance, Balances,
44
    CollatorAssignment, Configuration, DataPreservers, ForeignAssets, ForeignAssetsCreator,
45
    InactivityTracking, InflationRewards, Initializer, Invulnerables, MinimumSelfDelegation,
46
    ParachainInfo, PooledStaking, Proxy, ProxyType, Registrar, RewardsPortion, Runtime,
47
    RuntimeCall, ServicesPayment, Session, System, TransactionPayment,
48
};
49

            
50
pub const UNIT: Balance = 1_000_000_000_000;
51

            
52
266
pub fn session_to_block(n: u32) -> u32 {
53
266
    let block_number = dancebox_runtime::Period::get() * n;
54

            
55
    // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
56
    // so this is the first block of the new session that can actually be used
57
266
    block_number + 1
58
266
}
59

            
60
#[derive(Debug, Clone, Eq, PartialEq)]
61
pub struct RunSummary {
62
    pub author_id: AccountId,
63
    pub inflation: Balance,
64
}
65

            
66
thread_local! {
67
    static SHOULD_WRITE_SLOT_INFO: Cell<bool> = Cell::new(true);
68
}
69

            
70
24
pub fn set_should_write_slot_info(value: bool) {
71
24
    SHOULD_WRITE_SLOT_INFO.with(|flag| flag.set(value));
72
24
}
73

            
74
5042
fn should_write_slot_info() -> bool {
75
5042
    SHOULD_WRITE_SLOT_INFO.with(|flag| flag.get())
76
5042
}
77

            
78
260
pub fn run_to_session(n: u32) {
79
260
    run_to_block(session_to_block(n));
80
260
}
81

            
82
/// Utility function that advances the chain to the desired block number.
83
///
84
/// After this function returns, the current block number will be `n`, and the block will be "open",
85
/// meaning that on_initialize has been executed, but on_finalize has not. To execute on_finalize as
86
/// well, for example to test a runtime api, manually call `end_block` after this, run the test, and
87
/// call `start_block` to ensure that this function keeps working as expected.
88
/// Extrinsics should always be executed before on_finalize.
89
410
pub fn run_to_block(n: u32) -> BTreeMap<u32, RunSummary> {
90
410
    let current_block_number = System::block_number();
91
410
    assert!(
92
410
        current_block_number < n,
93
        "run_to_block called with block {} when current block is {}",
94
        n,
95
        current_block_number
96
    );
97
410
    let mut summaries = BTreeMap::new();
98

            
99
5102
    while System::block_number() < n {
100
4692
        let summary = run_block();
101
4692
        let block_number = System::block_number();
102
4692
        summaries.insert(block_number, summary);
103
4692
    }
104

            
105
410
    summaries
106
410
}
107

            
108
5042
pub fn insert_authorities_and_slot_digests(slot: u64) {
109
5042
    let authorities =
110
5042
        Runtime::para_id_authorities(ParachainInfo::get()).expect("authorities should be set");
111

            
112
5042
    let authority: NimbusId = authorities[slot as usize % authorities.len()].clone();
113

            
114
5042
    let pre_digest = Digest {
115
5042
        logs: vec![
116
5042
            DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode()),
117
5042
            DigestItem::PreRuntime(NIMBUS_ENGINE_ID, authority.encode()),
118
5042
        ],
119
5042
    };
120

            
121
5042
    System::reset_events();
122
5042
    System::initialize(
123
5042
        &(System::block_number() + 1),
124
5042
        &System::parent_hash(),
125
5042
        &pre_digest,
126
    );
127
5042
}
128

            
129
// Used to create the next block inherent data
130
#[derive(Clone, Encode, Decode, Default, PartialEq, Debug, scale_info::TypeInfo, MaxEncodedLen)]
131
pub struct MockInherentData {
132
    pub random_seed: Option<[u8; 32]>,
133
}
134

            
135
5042
fn take_new_inherent_data() -> Option<MockInherentData> {
136
5042
    let data: Option<MockInherentData> =
137
5042
        frame_support::storage::unhashed::take(b"__mock_new_inherent_data");
138

            
139
5042
    data
140
5042
}
141

            
142
4
fn set_new_inherent_data(data: MockInherentData) {
143
4
    frame_support::storage::unhashed::put(b"__mock_new_inherent_data", &Some(data));
144
4
}
145

            
146
#[derive(Clone, Encode, Decode, PartialEq, Debug, scale_info::TypeInfo, MaxEncodedLen)]
147
enum RunBlockState {
148
    Start(u32),
149
    End(u32),
150
}
151

            
152
impl RunBlockState {
153
9048
    fn assert_can_advance(&self, new_state: &RunBlockState) {
154
9048
        match self {
155
4410
            RunBlockState::Start(n) => {
156
4410
                assert_eq!(
157
                    new_state,
158
4410
                    &RunBlockState::End(*n),
159
                    "expected a call to end_block({}), but user called {:?}",
160
                    *n,
161
                    new_state
162
                );
163
            }
164
4638
            RunBlockState::End(n) => {
165
4638
                assert_eq!(
166
                    new_state,
167
4638
                    &RunBlockState::Start(*n + 1),
168
                    "expected a call to start_block({}), but user called {:?}",
169
                    *n + 1,
170
                    new_state
171
                )
172
            }
173
        }
174
9048
    }
175
}
176

            
177
9856
fn advance_block_state_machine(new_state: RunBlockState) {
178
9856
    if frame_support::storage::unhashed::exists(b"__mock_is_xcm_test") {
179
        // Disable this check in XCM tests, because the XCM emulator runs on_initialize and
180
        // on_finalize automatically
181
808
        return;
182
9048
    }
183
9048
    let old_state: RunBlockState =
184
9048
        frame_support::storage::unhashed::get(b"__mock_debug_block_state").unwrap_or(
185
            // Initial state is expecting a call to start() with block number 1, so old state should be
186
            // end of block 0
187
9048
            RunBlockState::End(0),
188
        );
189
9048
    old_state.assert_can_advance(&new_state);
190
9048
    frame_support::storage::unhashed::put(b"__mock_debug_block_state", &new_state);
191
9856
}
192

            
193
5042
pub fn start_block() -> RunSummary {
194
5042
    let block_number = System::block_number();
195
5042
    advance_block_state_machine(RunBlockState::Start(block_number + 1));
196
5042
    let mut slot = current_slot() + 1;
197
5042
    if block_number == 0 {
198
230
        // Hack to avoid breaking all tests. When the current block is 1, the slot number should be
199
230
        // 1. But all of our tests assume it will be 0. So use slot number = block_number - 1.
200
230
        slot = 0;
201
4812
    }
202

            
203
5042
    let maybe_mock_inherent = take_new_inherent_data();
204

            
205
5042
    if let Some(mock_inherent_data) = maybe_mock_inherent {
206
4
        set_parachain_inherent_data(mock_inherent_data);
207
5038
    }
208

            
209
5042
    insert_authorities_and_slot_digests(slot);
210

            
211
    // Initialize the new block
212
5042
    CollatorAssignment::on_initialize(System::block_number());
213
5042
    Session::on_initialize(System::block_number());
214
5042
    Initializer::on_initialize(System::block_number());
215
5042
    AuthorInherent::on_initialize(System::block_number());
216

            
217
    // `Initializer::on_finalize` needs to run at least one to have
218
    // author mapping setup.
219
5042
    let author_id = current_author();
220

            
221
5042
    let current_issuance = Balances::total_issuance();
222
5042
    InflationRewards::on_initialize(System::block_number());
223
5042
    let new_issuance = Balances::total_issuance();
224

            
225
5042
    if should_write_slot_info() {
226
4638
        frame_support::storage::unhashed::put(
227
4638
            &frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
228
4638
            &(Slot::from(slot), 1),
229
4638
        );
230
4638
    }
231

            
232
5042
    pallet_author_inherent::Pallet::<Runtime>::kick_off_authorship_validation(None.into())
233
5042
        .expect("author inherent to dispatch correctly");
234

            
235
5042
    InactivityTracking::on_initialize(System::block_number());
236

            
237
5042
    RunSummary {
238
5042
        author_id,
239
5042
        inflation: new_issuance - current_issuance,
240
5042
    }
241
5042
}
242

            
243
4814
pub fn end_block() {
244
4814
    let block_number = System::block_number();
245
4814
    advance_block_state_machine(RunBlockState::End(block_number));
246
    // Finalize the block
247
4814
    CollatorAssignment::on_finalize(System::block_number());
248
4814
    Session::on_finalize(System::block_number());
249
4814
    Initializer::on_finalize(System::block_number());
250
4814
    AuthorInherent::on_finalize(System::block_number());
251
4814
    TransactionPayment::on_finalize(System::block_number());
252
4814
    InactivityTracking::on_finalize(System::block_number());
253
4814
}
254

            
255
4808
pub fn run_block() -> RunSummary {
256
4808
    end_block();
257

            
258
4808
    start_block()
259
4808
}
260

            
261
/// Mock the inherent that sets validation data in ParachainSystem, which
262
/// contains the `relay_chain_block_number`, which is used in `collator-assignment` as a
263
/// source of randomness.
264
234
pub fn set_parachain_inherent_data(mock_inherent_data: MockInherentData) {
265
    use {
266
        cumulus_primitives_core::relay_chain::well_known_keys,
267
        cumulus_test_relay_sproof_builder::RelayStateSproofBuilder,
268
    };
269

            
270
234
    let relay_sproof = RelayStateSproofBuilder {
271
234
        para_id: 100u32.into(),
272
234
        included_para_head: Some(HeadData(vec![1, 2, 3])),
273
234
        current_slot: (current_slot()).into(),
274
234
        additional_key_values: if mock_inherent_data.random_seed.is_some() {
275
4
            vec![(
276
4
                well_known_keys::CURRENT_BLOCK_RANDOMNESS.to_vec(),
277
4
                Some(mock_inherent_data.random_seed).encode(),
278
4
            )]
279
        } else {
280
230
            vec![]
281
        },
282
234
        ..Default::default()
283
    };
284

            
285
234
    let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
286
234
    let vfp = PersistedValidationData {
287
234
        relay_parent_number: 1u32,
288
234
        relay_parent_storage_root,
289
234
        ..Default::default()
290
234
    };
291
234
    let parachain_inherent_data = ParachainInherentData {
292
234
        validation_data: vfp,
293
234
        relay_chain_state,
294
234
        downward_messages: Default::default(),
295
234
        horizontal_messages: Default::default(),
296
234
        relay_parent_descendants: Default::default(),
297
234
        collator_peer_id: Default::default(),
298
234
    };
299

            
300
    // Delete existing flag to avoid error
301
    // 'ValidationData must be updated only once in a block'
302
    // TODO: this is a hack
303
234
    frame_support::storage::unhashed::kill(&frame_support::storage::storage_prefix(
304
234
        b"ParachainSystem",
305
234
        b"ValidationData",
306
234
    ));
307

            
308
234
    assert_ok!(RuntimeCall::ParachainSystem(
309
234
        cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
310
234
            data: parachain_inherent_data
311
234
        }
312
234
    )
313
234
    .dispatch(inherent_origin()));
314
234
}
315

            
316
4
pub fn set_parachain_inherent_data_random_seed(random_seed: [u8; 32]) {
317
4
    set_new_inherent_data(MockInherentData {
318
4
        random_seed: Some(random_seed),
319
4
    });
320
4
}
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
230
pub fn default_config() -> pallet_configuration::HostConfiguration {
332
230
    pallet_configuration::HostConfiguration {
333
230
        max_collators: 100,
334
230
        min_orchestrator_collators: 2,
335
230
        max_orchestrator_collators: 2,
336
230
        collators_per_container: 2,
337
230
        full_rotation_period: 24,
338
230
        ..Default::default()
339
230
    }
340
230
}
341

            
342
pub struct ExtBuilder {
343
    // endowed accounts with balances
344
    balances: Vec<(AccountId, Balance)>,
345
    // [collator, amount]
346
    collators: Vec<(AccountId, Balance)>,
347
    // sudo key
348
    sudo: Option<AccountId>,
349
    // list of registered para ids: para_id, genesis_data, boot_nodes, block_credits, session_credits
350
    para_ids: Vec<ParaRegistrationParams>,
351
    // configuration to apply
352
    config: pallet_configuration::HostConfiguration,
353
    safe_xcm_version: Option<u32>,
354
    own_para_id: Option<ParaId>,
355
}
356

            
357
impl Default for ExtBuilder {
358
230
    fn default() -> Self {
359
230
        Self {
360
230
            balances: vec![
361
230
                // Alice gets 10k extra tokens for her mapping deposit
362
230
                (AccountId::from(ALICE), 210_000 * UNIT),
363
230
                (AccountId::from(BOB), 100_000 * UNIT),
364
230
            ],
365
230
            collators: vec![
366
230
                (AccountId::from(ALICE), 210 * UNIT),
367
230
                (AccountId::from(BOB), 100 * UNIT),
368
230
            ],
369
230
            sudo: Default::default(),
370
230
            para_ids: Default::default(),
371
230
            config: default_config(),
372
230
            safe_xcm_version: Default::default(),
373
230
            own_para_id: Default::default(),
374
230
        }
375
230
    }
376
}
377

            
378
impl ExtBuilder {
379
192
    pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
380
192
        self.balances = balances;
381
192
        self
382
192
    }
383

            
384
174
    pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
385
174
        self.collators = collators;
386
174
        self
387
174
    }
388

            
389
8
    pub fn with_sudo(mut self, sudo: AccountId) -> Self {
390
8
        self.sudo = Some(sudo);
391
8
        self
392
8
    }
393

            
394
8
    pub fn with_para_ids(mut self, para_ids: Vec<ParaRegistrationParams>) -> Self {
395
8
        self.para_ids = para_ids;
396
8
        self
397
8
    }
398

            
399
    /// Helper function like `with_para_ids` but registering parachains with an empty genesis data,
400
    /// and max amount of credits.
401
120
    pub fn with_empty_parachains(mut self, para_ids: Vec<u32>) -> Self {
402
120
        self.para_ids = para_ids
403
120
            .into_iter()
404
120
            .map(|para_id| ParaRegistrationParams {
405
242
                para_id,
406
242
                genesis_data: empty_genesis_data(),
407
                block_production_credits: u32::MAX,
408
                collator_assignment_credits: u32::MAX,
409
242
                parathread_params: None,
410
242
            })
411
120
            .collect();
412
120
        self
413
120
    }
414

            
415
10
    pub fn with_config(mut self, config: pallet_configuration::HostConfiguration) -> Self {
416
10
        self.config = config;
417
10
        self
418
10
    }
419

            
420
230
    pub fn build_storage(self) -> sp_core::storage::Storage {
421
230
        let mut t = frame_system::GenesisConfig::<Runtime>::default()
422
230
            .build_storage()
423
230
            .unwrap();
424

            
425
230
        pallet_balances::GenesisConfig::<Runtime> {
426
230
            balances: self.balances,
427
230
            ..Default::default()
428
230
        }
429
230
        .assimilate_storage(&mut t)
430
230
        .unwrap();
431

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

            
435
        pallet_registrar::GenesisConfig::<Runtime> {
436
230
            para_ids: self
437
230
                .para_ids
438
230
                .iter()
439
230
                .cloned()
440
256
                .map(|registered_para| {
441
256
                    (
442
256
                        registered_para.para_id.into(),
443
256
                        registered_para.genesis_data,
444
256
                        registered_para.parathread_params,
445
256
                    )
446
256
                })
447
230
                .collect(),
448
230
            phantom: Default::default(),
449
        }
450
230
        .assimilate_storage(&mut t)
451
230
        .unwrap();
452

            
453
        pallet_services_payment::GenesisConfig::<Runtime> {
454
230
            para_id_credits: self
455
230
                .para_ids
456
230
                .clone()
457
230
                .into_iter()
458
256
                .map(|registered_para| {
459
256
                    (
460
256
                        registered_para.para_id.into(),
461
256
                        registered_para.block_production_credits,
462
256
                        registered_para.collator_assignment_credits,
463
256
                    )
464
256
                        .into()
465
256
                })
466
230
                .collect(),
467
        }
468
230
        .assimilate_storage(&mut t)
469
230
        .unwrap();
470

            
471
230
        pallet_configuration::GenesisConfig::<Runtime> {
472
230
            config: self.config,
473
230
            ..Default::default()
474
230
        }
475
230
        .assimilate_storage(&mut t)
476
230
        .unwrap();
477

            
478
230
        pallet_xcm::GenesisConfig::<Runtime> {
479
230
            safe_xcm_version: self.safe_xcm_version,
480
230
            ..Default::default()
481
230
        }
482
230
        .assimilate_storage(&mut t)
483
230
        .unwrap();
484

            
485
230
        if let Some(own_para_id) = self.own_para_id {
486
            parachain_info::GenesisConfig::<Runtime> {
487
                parachain_id: own_para_id,
488
                ..Default::default()
489
            }
490
            .assimilate_storage(&mut t)
491
            .unwrap();
492
230
        }
493

            
494
230
        if !self.collators.is_empty() {
495
            // We set invulnerables in pallet_invulnerables
496
230
            let invulnerables: Vec<AccountId> = self
497
230
                .collators
498
230
                .clone()
499
230
                .into_iter()
500
230
                .map(|(account, _balance)| account)
501
230
                .collect();
502

            
503
230
            pallet_invulnerables::GenesisConfig::<Runtime> {
504
230
                invulnerables: invulnerables.clone(),
505
230
            }
506
230
            .assimilate_storage(&mut t)
507
230
            .unwrap();
508

            
509
            // But we also initialize their keys in the session pallet
510
230
            let keys: Vec<_> = self
511
230
                .collators
512
230
                .into_iter()
513
770
                .map(|(account, _balance)| {
514
770
                    let nimbus_id = get_aura_id_from_seed(&account.to_string());
515
770
                    (
516
770
                        account.clone(),
517
770
                        account,
518
770
                        dancebox_runtime::SessionKeys { nimbus: nimbus_id },
519
770
                    )
520
770
                })
521
230
                .collect();
522
230
            pallet_session::GenesisConfig::<Runtime> {
523
230
                keys,
524
230
                ..Default::default()
525
230
            }
526
230
            .assimilate_storage(&mut t)
527
230
            .unwrap();
528
        }
529
230
        pallet_sudo::GenesisConfig::<Runtime> { key: self.sudo }
530
230
            .assimilate_storage(&mut t)
531
230
            .unwrap();
532

            
533
230
        if self.safe_xcm_version.is_some() {
534
            // Disable run_block checks in XCM tests, because the XCM emulator runs on_initialize and
535
            // on_finalize automatically
536
            t.top.insert(b"__mock_is_xcm_test".to_vec(), b"1".to_vec());
537
230
        }
538

            
539
230
        t
540
230
    }
541

            
542
230
    pub fn build(self) -> sp_io::TestExternalities {
543
230
        let t = self.build_storage();
544
230
        let mut ext = sp_io::TestExternalities::new(t);
545

            
546
230
        ext.execute_with(|| {
547
            // Start block 1
548
230
            start_block();
549
230
            set_parachain_inherent_data(Default::default());
550
230
        });
551
230
        ext
552
230
    }
553
}
554

            
555
184
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
556
184
    <Runtime as frame_system::Config>::RuntimeOrigin::root()
557
184
}
558

            
559
416
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
560
416
    <Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
561
416
}
562

            
563
256
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
564
256
    <Runtime as frame_system::Config>::RuntimeOrigin::none()
565
256
}
566

            
567
/// Helper function to generate a crypto pair from seed
568
932
pub fn get_aura_id_from_seed(seed: &str) -> NimbusId {
569
932
    sp_core::sr25519::Pair::from_string(&format!("//{}", seed), None)
570
932
        .expect("static values are valid; qed")
571
932
        .public()
572
932
        .into()
573
932
}
574

            
575
/// Return the parachain that the given `AccountId` is collating for.
576
/// Returns `None` if the `AccountId` is not collating.
577
16
pub fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
578
16
    let assigned_collators = CollatorAssignment::collator_container_chain();
579
16
    let self_para_id = ParachainInfo::get();
580

            
581
16
    assigned_collators.para_id_of(&account, self_para_id)
582
16
}
583

            
584
/// Return the parachain that the given `AccountId` will be collating for
585
/// in the next session change.
586
/// Returns `None` if the `AccountId` will not be collating.
587
12
pub fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
588
12
    let assigned_collators = CollatorAssignment::pending_collator_container_chain();
589

            
590
12
    match assigned_collators {
591
8
        Some(assigned_collators) => {
592
8
            let self_para_id = ParachainInfo::get();
593

            
594
8
            assigned_collators.para_id_of(&account, self_para_id)
595
        }
596
4
        None => current_collator_parachain_assignment(account),
597
    }
598
12
}
599

            
600
/// Return the list of collators of the given `ParaId`.
601
/// Returns `None` if the `ParaId` is not in the registrar.
602
28
pub fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
603
28
    let assigned_collators = CollatorAssignment::collator_container_chain();
604
28
    let self_para_id = ParachainInfo::get();
605

            
606
28
    if para_id == self_para_id {
607
18
        Some(assigned_collators.orchestrator_chain)
608
    } else {
609
10
        assigned_collators.container_chains.get(&para_id).cloned()
610
    }
611
28
}
612

            
613
8
pub fn get_orchestrator_current_author() -> Option<AccountId> {
614
8
    let slot: u64 = current_slot();
615
8
    let orchestrator_collators = parachain_collators(ParachainInfo::get())?;
616
8
    let author_index = slot % orchestrator_collators.len() as u64;
617
8
    let account = orchestrator_collators.get(author_index as usize)?;
618
8
    Some(account.clone())
619
8
}
620
/// Mocks the author noting inherent to insert the data we
621
22
pub fn set_author_noting_inherent_data(builder: ParaHeaderSproofBuilder) {
622
22
    let (relay_storage_root, relay_storage_proof) = builder.into_state_root_and_proof();
623

            
624
    // For now we directly touch parachain_system storage to set the relay state root.
625
    // TODO: Properly set the parachain_system inherent, which require a sproof builder combining
626
    // what is required by parachain_system and author_noting.
627
22
    frame_support::storage::unhashed::put(
628
22
        &frame_support::storage::storage_prefix(b"ParachainSystem", b"ValidationData"),
629
22
        &PersistedValidationData {
630
22
            parent_head: HeadData(Default::default()),
631
22
            relay_parent_number: 0u32,
632
22
            relay_parent_storage_root: relay_storage_root,
633
22
            max_pov_size: 0u32,
634
22
        },
635
    );
636

            
637
    // But we also need to store the new proof submitted
638
22
    frame_support::storage::unhashed::put(
639
22
        &frame_support::storage::storage_prefix(b"ParachainSystem", b"RelayStateProof"),
640
22
        &relay_storage_proof,
641
    );
642

            
643
22
    assert_ok!(RuntimeCall::AuthorNoting(
644
22
        pallet_author_noting::Call::<Runtime>::set_latest_author_data {
645
22
            data: tp_author_noting_inherent::OwnParachainInherentData {
646
22
                relay_storage_proof,
647
22
            }
648
22
        }
649
22
    )
650
22
    .dispatch(inherent_origin()));
651
22
}
652

            
653
328
pub fn empty_genesis_data() -> ContainerChainGenesisData {
654
328
    ContainerChainGenesisData {
655
328
        storage: Default::default(),
656
328
        name: Default::default(),
657
328
        id: Default::default(),
658
328
        fork_id: Default::default(),
659
328
        extensions: Default::default(),
660
328
        properties: Default::default(),
661
328
    }
662
328
}
663

            
664
5330
pub fn current_slot() -> u64 {
665
5330
    u64::from(
666
5330
        pallet_async_backing::SlotInfo::<Runtime>::get()
667
5330
            .unwrap_or_default()
668
5330
            .0,
669
    )
670
5330
}
671

            
672
62
pub fn authorities() -> Vec<NimbusId> {
673
62
    let session_index = Session::current_index();
674

            
675
62
    AuthorityAssignment::collator_container_chain(session_index)
676
62
        .expect("authorities should be set")
677
62
        .orchestrator_chain
678
62
}
679

            
680
5096
pub fn current_author() -> AccountId {
681
5096
    let current_session = Session::current_index();
682
5096
    let mapping =
683
5096
        pallet_authority_mapping::Pallet::<Runtime>::authority_id_mapping(current_session)
684
5096
            .expect("there is a mapping for the current session");
685

            
686
5096
    let author = pallet_author_inherent::Author::<Runtime>::get()
687
5096
        .expect("there should be a registered author");
688

            
689
5096
    mapping
690
5096
        .get(&author)
691
5096
        .expect("there is a mapping for the current author")
692
5096
        .clone()
693
5096
}
694

            
695
30
pub fn block_credits_to_required_balance(number_of_blocks: u32, para_id: ParaId) -> Balance {
696
30
    let block_cost = BlockProductionCost::block_cost(&para_id).0;
697
30
    u128::from(number_of_blocks).saturating_mul(block_cost)
698
30
}
699

            
700
8
pub fn collator_assignment_credits_to_required_balance(
701
8
    number_of_sessions: u32,
702
8
    para_id: ParaId,
703
8
) -> Balance {
704
8
    let collator_assignment_cost = CollatorAssignmentCost::collator_assignment_cost(&para_id).0;
705
8
    u128::from(number_of_sessions).saturating_mul(collator_assignment_cost)
706
8
}
707

            
708
pub const ALICE: [u8; 32] = [4u8; 32];
709
pub const BOB: [u8; 32] = [5u8; 32];
710
pub const CHARLIE: [u8; 32] = [6u8; 32];
711
pub const DAVE: [u8; 32] = [7u8; 32];
712
pub const EVE: [u8; 32] = [8u8; 32];
713
pub const FERDIE: [u8; 32] = [9u8; 32];
714

            
715
66
pub fn set_dummy_boot_node(para_manager: RuntimeOrigin, para_id: ParaId) {
716
    use {
717
        pallet_data_preservers::{NodeType, ParaIdsFilter, Profile},
718
        tp_data_preservers_common::{AssignerExtra, ProviderRequest},
719
    };
720

            
721
66
    let profile = Profile {
722
66
        bootnode_url: Some(
723
66
            b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
724
66
                .to_vec()
725
66
                .try_into()
726
66
                .expect("to fit in BoundedVec"),
727
66
        ),
728
66
        direct_rpc_urls: Default::default(),
729
66
        proxy_rpc_urls: Default::default(),
730
66
        para_ids: ParaIdsFilter::AnyParaId,
731
66
        node_type: NodeType::Substrate,
732
66
        additional_info: Default::default(),
733
66
        assignment_request: ProviderRequest::Free,
734
66
    };
735

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

            
741
66
    DataPreservers::start_assignment(para_manager, profile_id, para_id, AssignerExtra::Free)
742
66
        .expect("assignement to work");
743

            
744
66
    assert!(
745
66
        pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
746
        "profile should be correctly assigned"
747
    );
748
66
}