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

            
39
pub use crate::{
40
    AccountId, AuthorNoting, AuthorityAssignment, AuthorityMapping, Balance, Balances,
41
    CollatorAssignment, Configuration, DataPreservers, InflationRewards, Initializer,
42
    Invulnerables, ParachainInfo, Proxy, ProxyType, Registrar, RewardsPortion, Runtime,
43
    RuntimeCall, ServicesPayment, Session, StreamPayment, System, TransactionPayment,
44
};
45

            
46
pub const UNIT: Balance = 1_000_000_000_000;
47

            
48
77
pub fn session_to_block(n: u32) -> u32 {
49
77
    let block_number = crate::Period::get() * n;
50
77

            
51
77
    // Add 1 because the block that emits the NewSession event cannot contain any extrinsics,
52
77
    // so this is the first block of the new session that can actually be used
53
77
    block_number + 1
54
77
}
55

            
56
#[derive(Debug, Clone, Eq, PartialEq)]
57
pub struct RunSummary {
58
    pub author_id: AccountId,
59
    pub inflation: Balance,
60
}
61

            
62
77
pub fn run_to_session(n: u32) {
63
77
    run_to_block(session_to_block(n));
64
77
}
65

            
66
/// Utility function that advances the chain to the desired block number.
67
///
68
/// After this function returns, the current block number will be `n`, and the block will be "open",
69
/// meaning that on_initialize has been executed, but on_finalize has not. To execute on_finalize as
70
/// well, for example to test a runtime api, manually call `end_block` after this, run the test, and
71
/// call `start_block` to ensure that this function keeps working as expected.
72
/// Extrinsics should always be executed before on_finalize.
73
123
pub fn run_to_block(n: u32) -> BTreeMap<u32, RunSummary> {
74
123
    let current_block_number = System::block_number();
75
123
    assert!(
76
123
        current_block_number < n,
77
        "run_to_block called with block {} when current block is {}",
78
        n,
79
        current_block_number
80
    );
81
123
    let mut summaries = BTreeMap::new();
82

            
83
1096
    while System::block_number() < n {
84
973
        let summary = run_block();
85
973
        let block_number = System::block_number();
86
973
        summaries.insert(block_number, summary);
87
973
    }
88

            
89
123
    summaries
90
123
}
91

            
92
1057
pub fn insert_authorities_and_slot_digests(slot: u64) {
93
1057
    let authorities =
94
1057
        Runtime::para_id_authorities(ParachainInfo::get()).expect("authorities should be set");
95
1057

            
96
1057
    let authority: NimbusId = authorities[slot as usize % authorities.len()].clone();
97
1057

            
98
1057
    let pre_digest = Digest {
99
1057
        logs: vec![
100
1057
            DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode()),
101
1057
            DigestItem::PreRuntime(NIMBUS_ENGINE_ID, authority.encode()),
102
1057
        ],
103
1057
    };
104
1057

            
105
1057
    System::reset_events();
106
1057
    System::initialize(
107
1057
        &(System::block_number() + 1),
108
1057
        &System::parent_hash(),
109
1057
        &pre_digest,
110
1057
    );
111
1057
}
112

            
113
// Used to create the next block inherent data
114
#[derive(Clone, Encode, Decode, Default, PartialEq, Debug, scale_info::TypeInfo, MaxEncodedLen)]
115
pub struct MockInherentData {
116
    pub random_seed: Option<[u8; 32]>,
117
}
118

            
119
1057
fn take_new_inherent_data() -> Option<MockInherentData> {
120
1057
    let data: Option<MockInherentData> =
121
1057
        frame_support::storage::unhashed::take(b"__mock_new_inherent_data");
122
1057

            
123
1057
    data
124
1057
}
125

            
126
#[derive(Clone, Encode, Decode, PartialEq, Debug, scale_info::TypeInfo, MaxEncodedLen)]
127
enum RunBlockState {
128
    Start(u32),
129
    End(u32),
130
}
131

            
132
impl RunBlockState {
133
2044
    fn assert_can_advance(&self, new_state: &RunBlockState) {
134
2044
        match self {
135
987
            RunBlockState::Start(n) => {
136
987
                assert_eq!(
137
987
                    new_state,
138
987
                    &RunBlockState::End(*n),
139
                    "expected a call to end_block({}), but user called {:?}",
140
                    *n,
141
                    new_state
142
                );
143
            }
144
1057
            RunBlockState::End(n) => {
145
1057
                assert_eq!(
146
1057
                    new_state,
147
1057
                    &RunBlockState::Start(*n + 1),
148
                    "expected a call to start_block({}), but user called {:?}",
149
                    *n + 1,
150
                    new_state
151
                )
152
            }
153
        }
154
2044
    }
155
}
156

            
157
2044
fn advance_block_state_machine(new_state: RunBlockState) {
158
2044
    if frame_support::storage::unhashed::exists(b"__mock_is_xcm_test") {
159
        // Disable this check in XCM tests, because the XCM emulator runs on_initialize and
160
        // on_finalize automatically
161
        return;
162
2044
    }
163
2044
    let old_state: RunBlockState =
164
2044
        frame_support::storage::unhashed::get(b"__mock_debug_block_state").unwrap_or(
165
2044
            // Initial state is expecting a call to start() with block number 1, so old state should be
166
2044
            // end of block 0
167
2044
            RunBlockState::End(0),
168
2044
        );
169
2044
    old_state.assert_can_advance(&new_state);
170
2044
    frame_support::storage::unhashed::put(b"__mock_debug_block_state", &new_state);
171
2044
}
172

            
173
1057
pub fn start_block() -> RunSummary {
174
1057
    let block_number = System::block_number();
175
1057
    advance_block_state_machine(RunBlockState::Start(block_number + 1));
176
1057
    let mut slot = current_slot() + 1;
177
1057
    if block_number == 0 {
178
71
        // Hack to avoid breaking all tests. When the current block is 1, the slot number should be
179
71
        // 1. But all of our tests assume it will be 0. So use slot number = block_number - 1.
180
71
        slot = 0;
181
986
    }
182

            
183
1057
    let maybe_mock_inherent = take_new_inherent_data();
184

            
185
1057
    if let Some(mock_inherent_data) = maybe_mock_inherent {
186
        set_parachain_inherent_data(mock_inherent_data);
187
1057
    }
188

            
189
1057
    insert_authorities_and_slot_digests(slot);
190
1057

            
191
1057
    // Initialize the new block
192
1057
    CollatorAssignment::on_initialize(System::block_number());
193
1057
    Session::on_initialize(System::block_number());
194
1057
    Initializer::on_initialize(System::block_number());
195
1057
    AuthorInherent::on_initialize(System::block_number());
196
1057

            
197
1057
    // `Initializer::on_finalize` needs to run at least one to have
198
1057
    // author mapping setup.
199
1057
    let author_id = current_author();
200
1057

            
201
1057
    let current_issuance = Balances::total_issuance();
202
1057
    InflationRewards::on_initialize(System::block_number());
203
1057
    let new_issuance = Balances::total_issuance();
204
1057

            
205
1057
    frame_support::storage::unhashed::put(
206
1057
        &frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
207
1057
        // TODO: this should be 0?
208
1057
        &(Slot::from(slot), 1),
209
1057
    );
210
1057

            
211
1057
    pallet_author_inherent::Pallet::<Runtime>::kick_off_authorship_validation(None.into())
212
1057
        .expect("author inherent to dispatch correctly");
213
1057

            
214
1057
    RunSummary {
215
1057
        author_id,
216
1057
        inflation: new_issuance - current_issuance,
217
1057
    }
218
1057
}
219

            
220
987
pub fn end_block() {
221
987
    let block_number = System::block_number();
222
987
    advance_block_state_machine(RunBlockState::End(block_number));
223
987
    // Finalize the block
224
987
    CollatorAssignment::on_finalize(System::block_number());
225
987
    Session::on_finalize(System::block_number());
226
987
    Initializer::on_finalize(System::block_number());
227
987
    AuthorInherent::on_finalize(System::block_number());
228
987
    TransactionPayment::on_finalize(System::block_number());
229
987
}
230

            
231
984
pub fn run_block() -> RunSummary {
232
984
    end_block();
233
984

            
234
984
    start_block()
235
984
}
236

            
237
/// Mock the inherent that sets validation data in ParachainSystem, which
238
/// contains the `relay_chain_block_number`, which is used in `collator-assignment` as a
239
/// source of randomness.
240
71
pub fn set_parachain_inherent_data(mock_inherent_data: MockInherentData) {
241
    use {
242
        cumulus_primitives_core::relay_chain::well_known_keys,
243
        cumulus_test_relay_sproof_builder::RelayStateSproofBuilder,
244
    };
245

            
246
71
    let relay_sproof = RelayStateSproofBuilder {
247
71
        para_id: 100u32.into(),
248
71
        included_para_head: Some(HeadData(vec![1, 2, 3])),
249
71
        current_slot: (current_slot()).into(),
250
71
        additional_key_values: if mock_inherent_data.random_seed.is_some() {
251
            vec![(
252
                well_known_keys::CURRENT_BLOCK_RANDOMNESS.to_vec(),
253
                Some(mock_inherent_data.random_seed).encode(),
254
            )]
255
        } else {
256
71
            vec![]
257
        },
258
71
        ..Default::default()
259
71
    };
260
71

            
261
71
    let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
262
71
    let vfp = PersistedValidationData {
263
71
        relay_parent_number: 1u32,
264
71
        relay_parent_storage_root,
265
71
        ..Default::default()
266
71
    };
267
71
    let parachain_inherent_data = ParachainInherentData {
268
71
        validation_data: vfp,
269
71
        relay_chain_state,
270
71
        downward_messages: Default::default(),
271
71
        horizontal_messages: Default::default(),
272
71
    };
273
71

            
274
71
    // Delete existing flag to avoid error
275
71
    // 'ValidationData must be updated only once in a block'
276
71
    // TODO: this is a hack
277
71
    frame_support::storage::unhashed::kill(&frame_support::storage::storage_prefix(
278
71
        b"ParachainSystem",
279
71
        b"ValidationData",
280
71
    ));
281
71

            
282
71
    assert_ok!(RuntimeCall::ParachainSystem(
283
71
        cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
284
71
            data: parachain_inherent_data
285
71
        }
286
71
    )
287
71
    .dispatch(inherent_origin()));
288
71
}
289

            
290
#[derive(Default, Clone)]
291
pub struct ParaRegistrationParams {
292
    pub para_id: u32,
293
    pub genesis_data: ContainerChainGenesisData,
294
    pub block_production_credits: u32,
295
    pub collator_assignment_credits: u32,
296
    pub parathread_params: Option<tp_traits::ParathreadParams>,
297
}
298

            
299
71
pub fn default_config() -> pallet_configuration::HostConfiguration {
300
71
    pallet_configuration::HostConfiguration {
301
71
        max_collators: 100,
302
71
        min_orchestrator_collators: 2,
303
71
        max_orchestrator_collators: 2,
304
71
        collators_per_container: 2,
305
71
        full_rotation_period: 0,
306
71
        ..Default::default()
307
71
    }
308
71
}
309

            
310
pub struct ExtBuilder {
311
    // endowed accounts with balances
312
    balances: Vec<(AccountId, Balance)>,
313
    // [collator, amount]
314
    collators: Vec<(AccountId, Balance)>,
315
    // sudo key
316
    sudo: Option<AccountId>,
317
    // list of registered para ids: para_id, genesis_data, boot_nodes, block_credits, session_credits
318
    para_ids: Vec<ParaRegistrationParams>,
319
    // configuration to apply
320
    config: pallet_configuration::HostConfiguration,
321
    own_para_id: Option<ParaId>,
322
}
323

            
324
impl Default for ExtBuilder {
325
71
    fn default() -> Self {
326
71
        Self {
327
71
            balances: vec![
328
71
                // Alice gets 10k extra tokens for her mapping deposit
329
71
                (AccountId::from(ALICE), 210_000 * UNIT),
330
71
                (AccountId::from(BOB), 100_000 * UNIT),
331
71
            ],
332
71
            collators: vec![
333
71
                (AccountId::from(ALICE), 210 * UNIT),
334
71
                (AccountId::from(BOB), 100 * UNIT),
335
71
            ],
336
71
            sudo: Default::default(),
337
71
            para_ids: Default::default(),
338
71
            config: default_config(),
339
71
            own_para_id: Default::default(),
340
71
        }
341
71
    }
342
}
343

            
344
impl ExtBuilder {
345
60
    pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
346
60
        self.balances = balances;
347
60
        self
348
60
    }
349

            
350
7
    pub fn with_sudo(mut self, sudo: AccountId) -> Self {
351
7
        self.sudo = Some(sudo);
352
7
        self
353
7
    }
354

            
355
39
    pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
356
39
        self.collators = collators;
357
39
        self
358
39
    }
359

            
360
2
    pub fn with_para_ids(mut self, para_ids: Vec<ParaRegistrationParams>) -> Self {
361
2
        self.para_ids = para_ids;
362
2
        self
363
2
    }
364

            
365
    /// Helper function like `with_para_ids` but registering parachains with an empty genesis data,
366
    /// and max amount of credits.
367
28
    pub fn with_empty_parachains(mut self, para_ids: Vec<u32>) -> Self {
368
28
        self.para_ids = para_ids
369
28
            .into_iter()
370
59
            .map(|para_id| ParaRegistrationParams {
371
59
                para_id,
372
59
                genesis_data: empty_genesis_data(),
373
59
                block_production_credits: u32::MAX,
374
59
                collator_assignment_credits: u32::MAX,
375
59
                parathread_params: None,
376
59
            })
377
28
            .collect();
378
28
        self
379
28
    }
380

            
381
2
    pub fn with_config(mut self, config: pallet_configuration::HostConfiguration) -> Self {
382
2
        self.config = config;
383
2
        self
384
2
    }
385

            
386
71
    pub fn build_storage(self) -> sp_core::storage::Storage {
387
71
        let mut t = frame_system::GenesisConfig::<Runtime>::default()
388
71
            .build_storage()
389
71
            .unwrap();
390
71

            
391
71
        pallet_balances::GenesisConfig::<Runtime> {
392
71
            balances: self.balances,
393
71
            ..Default::default()
394
71
        }
395
71
        .assimilate_storage(&mut t)
396
71
        .unwrap();
397
71

            
398
71
        // We need to initialize these pallets first. When initializing pallet-session,
399
71
        // these values will be taken into account for collator-assignment.
400
71

            
401
71
        pallet_registrar::GenesisConfig::<Runtime> {
402
71
            para_ids: self
403
71
                .para_ids
404
71
                .iter()
405
71
                .cloned()
406
71
                .map(|registered_para| {
407
62
                    (
408
62
                        registered_para.para_id.into(),
409
62
                        registered_para.genesis_data,
410
62
                        registered_para.parathread_params,
411
62
                    )
412
71
                })
413
71
                .collect(),
414
71
            phantom: Default::default(),
415
71
        }
416
71
        .assimilate_storage(&mut t)
417
71
        .unwrap();
418
71

            
419
71
        pallet_services_payment::GenesisConfig::<Runtime> {
420
71
            para_id_credits: self
421
71
                .para_ids
422
71
                .clone()
423
71
                .into_iter()
424
71
                .map(|registered_para| {
425
62
                    (
426
62
                        registered_para.para_id.into(),
427
62
                        registered_para.block_production_credits,
428
62
                        registered_para.collator_assignment_credits,
429
62
                    )
430
62
                        .into()
431
71
                })
432
71
                .collect(),
433
71
        }
434
71
        .assimilate_storage(&mut t)
435
71
        .unwrap();
436
71

            
437
71
        pallet_configuration::GenesisConfig::<Runtime> {
438
71
            config: self.config,
439
71
            ..Default::default()
440
71
        }
441
71
        .assimilate_storage(&mut t)
442
71
        .unwrap();
443

            
444
71
        if let Some(own_para_id) = self.own_para_id {
445
            parachain_info::GenesisConfig::<Runtime> {
446
                parachain_id: own_para_id,
447
                ..Default::default()
448
            }
449
            .assimilate_storage(&mut t)
450
            .unwrap();
451
71
        }
452

            
453
71
        if !self.collators.is_empty() {
454
71
            // We set invulnerables in pallet_invulnerables
455
71
            let invulnerables: Vec<AccountId> = self
456
71
                .collators
457
71
                .clone()
458
71
                .into_iter()
459
213
                .map(|(account, _balance)| account)
460
71
                .collect();
461
71

            
462
71
            pallet_invulnerables::GenesisConfig::<Runtime> {
463
71
                invulnerables: invulnerables.clone(),
464
71
            }
465
71
            .assimilate_storage(&mut t)
466
71
            .unwrap();
467
71

            
468
71
            // But we also initialize their keys in the session pallet
469
71
            let keys: Vec<_> = self
470
71
                .collators
471
71
                .into_iter()
472
213
                .map(|(account, _balance)| {
473
213
                    let nimbus_id = get_aura_id_from_seed(&account.to_string());
474
213
                    (
475
213
                        account.clone(),
476
213
                        account,
477
213
                        crate::SessionKeys { nimbus: nimbus_id },
478
213
                    )
479
213
                })
480
71
                .collect();
481
71
            pallet_session::GenesisConfig::<Runtime> {
482
71
                keys,
483
71
                ..Default::default()
484
71
            }
485
71
            .assimilate_storage(&mut t)
486
71
            .unwrap();
487
71
        }
488
71
        pallet_sudo::GenesisConfig::<Runtime> { key: self.sudo }
489
71
            .assimilate_storage(&mut t)
490
71
            .unwrap();
491
71
        t
492
71
    }
493

            
494
71
    pub fn build(self) -> sp_io::TestExternalities {
495
71
        let t = self.build_storage();
496
71
        let mut ext = sp_io::TestExternalities::new(t);
497
71

            
498
71
        ext.execute_with(|| {
499
71
            // Start block 1
500
71
            start_block();
501
71
            set_parachain_inherent_data(Default::default());
502
71
        });
503
71
        ext
504
71
    }
505
}
506

            
507
78
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
508
78
    <Runtime as frame_system::Config>::RuntimeOrigin::root()
509
78
}
510

            
511
118
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
512
118
    <Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
513
118
}
514

            
515
79
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
516
79
    <Runtime as frame_system::Config>::RuntimeOrigin::none()
517
79
}
518

            
519
/// Helper function to generate a crypto pair from seed
520
285
pub fn get_aura_id_from_seed(seed: &str) -> NimbusId {
521
285
    sp_core::sr25519::Pair::from_string(&format!("//{}", seed), None)
522
285
        .expect("static values are valid; qed")
523
285
        .public()
524
285
        .into()
525
285
}
526

            
527
/// Return the parachain that the given `AccountId` is collating for.
528
/// Returns `None` if the `AccountId` is not collating.
529
8
pub fn current_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
530
8
    let assigned_collators = CollatorAssignment::collator_container_chain();
531
8
    let self_para_id = ParachainInfo::get();
532
8

            
533
8
    assigned_collators.para_id_of(&account, self_para_id)
534
8
}
535

            
536
/// Return the parachain that the given `AccountId` will be collating for
537
/// in the next session change.
538
/// Returns `None` if the `AccountId` will not be collating.
539
6
pub fn future_collator_parachain_assignment(account: AccountId) -> Option<ParaId> {
540
6
    let assigned_collators = CollatorAssignment::pending_collator_container_chain();
541
6

            
542
6
    match assigned_collators {
543
4
        Some(assigned_collators) => {
544
4
            let self_para_id = ParachainInfo::get();
545
4

            
546
4
            assigned_collators.para_id_of(&account, self_para_id)
547
        }
548
2
        None => current_collator_parachain_assignment(account),
549
    }
550
6
}
551

            
552
/// Return the list of collators of the given `ParaId`.
553
/// Returns `None` if the `ParaId` is not in the registrar.
554
14
pub fn parachain_collators(para_id: ParaId) -> Option<Vec<AccountId>> {
555
14
    let assigned_collators = CollatorAssignment::collator_container_chain();
556
14
    let self_para_id = ParachainInfo::get();
557
14

            
558
14
    if para_id == self_para_id {
559
9
        Some(assigned_collators.orchestrator_chain)
560
    } else {
561
5
        assigned_collators.container_chains.get(&para_id).cloned()
562
    }
563
14
}
564

            
565
4
pub fn get_orchestrator_current_author() -> Option<AccountId> {
566
4
    let slot: u64 = current_slot();
567
4
    let orchestrator_collators = parachain_collators(ParachainInfo::get())?;
568
4
    let author_index = slot % orchestrator_collators.len() as u64;
569
4
    let account = orchestrator_collators.get(author_index as usize)?;
570
4
    Some(account.clone())
571
4
}
572
/// Mocks the author noting inherent to insert the data we
573
8
pub fn set_author_noting_inherent_data(builder: ParaHeaderSproofBuilder) {
574
8
    let (relay_storage_root, relay_storage_proof) = builder.into_state_root_and_proof();
575
8

            
576
8
    // For now we directly touch parachain_system storage to set the relay state root.
577
8
    // TODO: Properly set the parachain_system inherent, which require a sproof builder combining
578
8
    // what is required by parachain_system and author_noting.
579
8
    frame_support::storage::unhashed::put(
580
8
        &frame_support::storage::storage_prefix(b"ParachainSystem", b"ValidationData"),
581
8
        &PersistedValidationData {
582
8
            parent_head: HeadData(Default::default()),
583
8
            relay_parent_number: 0u32,
584
8
            relay_parent_storage_root: relay_storage_root,
585
8
            max_pov_size: 0u32,
586
8
        },
587
8
    );
588
8

            
589
8
    // But we also need to store the new proof submitted
590
8
    frame_support::storage::unhashed::put(
591
8
        &frame_support::storage::storage_prefix(b"ParachainSystem", b"RelayStateProof"),
592
8
        &relay_storage_proof,
593
8
    );
594
8

            
595
8
    assert_ok!(RuntimeCall::AuthorNoting(
596
8
        pallet_author_noting::Call::<Runtime>::set_latest_author_data {
597
8
            data: tp_author_noting_inherent::OwnParachainInherentData {
598
8
                relay_storage_proof,
599
8
            }
600
8
        }
601
8
    )
602
8
    .dispatch(inherent_origin()));
603
8
}
604

            
605
88
pub fn empty_genesis_data() -> ContainerChainGenesisData {
606
88
    ContainerChainGenesisData {
607
88
        storage: Default::default(),
608
88
        name: Default::default(),
609
88
        id: Default::default(),
610
88
        fork_id: Default::default(),
611
88
        extensions: Default::default(),
612
88
        properties: Default::default(),
613
88
    }
614
88
}
615

            
616
1155
pub fn current_slot() -> u64 {
617
1155
    u64::from(
618
1155
        pallet_async_backing::SlotInfo::<Runtime>::get()
619
1155
            .unwrap_or_default()
620
1155
            .0,
621
1155
    )
622
1155
}
623

            
624
31
pub fn authorities() -> Vec<NimbusId> {
625
31
    let session_index = Session::current_index();
626
31

            
627
31
    AuthorityAssignment::collator_container_chain(session_index)
628
31
        .expect("authorities should be set")
629
31
        .orchestrator_chain
630
31
}
631

            
632
1084
pub fn current_author() -> AccountId {
633
1084
    let current_session = Session::current_index();
634
1084
    let mapping =
635
1084
        pallet_authority_mapping::Pallet::<Runtime>::authority_id_mapping(current_session)
636
1084
            .expect("there is a mapping for the current session");
637
1084

            
638
1084
    let author = pallet_author_inherent::Author::<Runtime>::get()
639
1084
        .expect("there should be a registered author");
640
1084

            
641
1084
    mapping
642
1084
        .get(&author)
643
1084
        .expect("there is a mapping for the current author")
644
1084
        .clone()
645
1084
}
646

            
647
15
pub fn block_credits_to_required_balance(number_of_blocks: u32, para_id: ParaId) -> Balance {
648
15
    let block_cost = BlockProductionCost::block_cost(&para_id).0;
649
15
    u128::from(number_of_blocks).saturating_mul(block_cost)
650
15
}
651

            
652
4
pub fn collator_assignment_credits_to_required_balance(
653
4
    number_of_sessions: u32,
654
4
    para_id: ParaId,
655
4
) -> Balance {
656
4
    let collator_assignment_cost = CollatorAssignmentCost::collator_assignment_cost(&para_id).0;
657
4
    u128::from(number_of_sessions).saturating_mul(collator_assignment_cost)
658
4
}
659

            
660
pub const ALICE: [u8; 32] = [4u8; 32];
661
pub const BOB: [u8; 32] = [5u8; 32];
662
pub const CHARLIE: [u8; 32] = [6u8; 32];
663
pub const DAVE: [u8; 32] = [7u8; 32];
664
pub const EVE: [u8; 32] = [8u8; 32];
665
pub const FERDIE: [u8; 32] = [9u8; 32];