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
#![cfg(test)]
18

            
19
use {
20
    crate::{tests::common::*, RuntimeOrigin, StreamPaymentAssetId, TimeUnit},
21
    cumulus_primitives_core::{ParaId, Weight},
22
    dp_consensus::runtime_decl_for_tanssi_authority_assignment_api::TanssiAuthorityAssignmentApiV1,
23
    dp_core::well_known_keys,
24
    frame_support::{assert_noop, assert_ok, BoundedVec},
25
    frame_system::ConsumedWeight,
26
    nimbus_primitives::NIMBUS_KEY_ID,
27
    pallet_author_noting_runtime_api::runtime_decl_for_author_noting_api::AuthorNotingApi,
28
    pallet_collator_assignment_runtime_api::runtime_decl_for_collator_assignment_api::CollatorAssignmentApi,
29
    pallet_migrations::Migration,
30
    pallet_registrar_runtime_api::{
31
        runtime_decl_for_registrar_api::RegistrarApi, ContainerChainGenesisData,
32
    },
33
    parity_scale_codec::Encode,
34
    sp_consensus_aura::AURA_ENGINE_ID,
35
    sp_core::Get,
36
    sp_runtime::{
37
        traits::{BadOrigin, BlakeTwo256, Dispatchable, OpaqueKeys},
38
        DigestItem,
39
    },
40
    sp_std::vec,
41
    tanssi_runtime_common::migrations::MigrateServicesPaymentAddCollatorAssignmentCredits,
42
    test_relay_sproof_builder::{HeaderAs, ParaHeaderSproofBuilder, ParaHeaderSproofBuilderItem},
43
    tp_traits::{ContainerChainBlockInfo, SlotFrequency},
44
};
45

            
46
20
fn set_dummy_boot_node(para_manager: RuntimeOrigin, para_id: ParaId) {
47
    use {
48
        crate::{PreserversAssignementPaymentExtra, PreserversAssignementPaymentRequest},
49
        pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode},
50
    };
51

            
52
20
    let profile = Profile {
53
20
        url:
54
20
            b"/ip4/127.0.0.1/tcp/33049/ws/p2p/12D3KooWHVMhQDHBpj9vQmssgyfspYecgV6e3hH1dQVDUkUbCYC9"
55
20
                .to_vec()
56
20
                .try_into()
57
20
                .expect("to fit in BoundedVec"),
58
20
        para_ids: ParaIdsFilter::AnyParaId,
59
20
        mode: ProfileMode::Bootnode,
60
20
        assignment_request: PreserversAssignementPaymentRequest::Free,
61
20
    };
62
20

            
63
20
    let profile_id = pallet_data_preservers::NextProfileId::<Runtime>::get();
64
20
    let profile_owner = AccountId::new([1u8; 32]);
65
20
    DataPreservers::force_create_profile(RuntimeOrigin::root(), profile, profile_owner)
66
20
        .expect("profile create to succeed");
67
20

            
68
20
    DataPreservers::start_assignment(
69
20
        para_manager,
70
20
        profile_id,
71
20
        para_id,
72
20
        PreserversAssignementPaymentExtra::Free,
73
20
    )
74
20
    .expect("assignement to work");
75
20

            
76
20
    assert!(
77
20
        pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id),
78
        "profile should be correctly assigned"
79
    );
80
20
}
81

            
82
#[test]
83
1
fn genesis_balances() {
84
1
    ExtBuilder::default()
85
1
        .with_balances(vec![
86
1
            // Alice gets 10k extra tokens for her mapping deposit
87
1
            (AccountId::from(ALICE), 210_000 * UNIT),
88
1
            (AccountId::from(BOB), 100_000 * UNIT),
89
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
90
1
            (AccountId::from(DAVE), 100_000 * UNIT),
91
1
        ])
92
1
        .with_collators(vec![
93
1
            // Remove ALICE and BOB from collators
94
1
            (AccountId::from(CHARLIE), 100 * UNIT),
95
1
            (AccountId::from(DAVE), 100 * UNIT),
96
1
        ])
97
1
        .build()
98
1
        .execute_with(|| {
99
1
            assert_eq!(
100
1
                Balances::usable_balance(AccountId::from(ALICE)),
101
1
                210_000 * UNIT,
102
1
            );
103
1
            assert_eq!(
104
1
                Balances::usable_balance(AccountId::from(BOB)),
105
1
                100_000 * UNIT,
106
1
            );
107
1
        });
108
1
}
109

            
110
#[test]
111
1
fn genesis_para_registrar() {
112
1
    ExtBuilder::default()
113
1
        .with_empty_parachains(vec![1001, 1002])
114
1
        .build()
115
1
        .execute_with(|| {
116
1
            assert_eq!(
117
1
                Registrar::registered_para_ids(),
118
1
                vec![1001.into(), 1002.into()]
119
1
            );
120
1
        });
121
1
}
122

            
123
#[test]
124
1
fn genesis_para_registrar_deregister() {
125
1
    ExtBuilder::default()
126
1
        .with_empty_parachains(vec![1001, 1002])
127
1
        .build()
128
1
        .execute_with(|| {
129
1
            assert_eq!(
130
1
                Registrar::registered_para_ids(),
131
1
                vec![1001.into(), 1002.into()]
132
1
            );
133

            
134
1
            run_to_block(2);
135
1
            assert_ok!(Registrar::deregister(root_origin(), 1002.into()), ());
136

            
137
            // Pending
138
1
            assert_eq!(
139
1
                Registrar::pending_registered_para_ids(),
140
1
                vec![(2u32, BoundedVec::try_from(vec![1001u32.into()]).unwrap())]
141
1
            );
142

            
143
1
            run_to_session(1);
144
1
            assert_eq!(
145
1
                Registrar::pending_registered_para_ids(),
146
1
                vec![(2u32, BoundedVec::try_from(vec![1001u32.into()]).unwrap())]
147
1
            );
148
1
            assert_eq!(
149
1
                Registrar::registered_para_ids(),
150
1
                vec![1001.into(), 1002.into()]
151
1
            );
152

            
153
1
            run_to_session(2);
154
1
            assert_eq!(Registrar::pending_registered_para_ids(), vec![]);
155
1
            assert_eq!(Registrar::registered_para_ids(), vec![1001.into()]);
156
1
        });
157
1
}
158

            
159
#[test]
160
1
fn genesis_para_registrar_runtime_api() {
161
1
    ExtBuilder::default()
162
1
        .with_empty_parachains(vec![1001, 1002])
163
1
        .build()
164
1
        .execute_with(|| {
165
1
            assert_eq!(
166
1
                Registrar::registered_para_ids(),
167
1
                vec![1001.into(), 1002.into()]
168
1
            );
169
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
170

            
171
1
            run_to_block(2);
172
1
            assert_ok!(Registrar::deregister(root_origin(), 1002.into()), ());
173
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
174

            
175
1
            run_to_session(1);
176
1
            assert_eq!(
177
1
                Registrar::registered_para_ids(),
178
1
                vec![1001.into(), 1002.into()]
179
1
            );
180
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
181

            
182
1
            run_to_session(2);
183
1
            assert_eq!(Registrar::registered_para_ids(), vec![1001.into()]);
184
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into()]);
185
1
        });
186
1
}
187

            
188
#[test]
189
1
fn genesis_para_registrar_container_chain_genesis_data_runtime_api() {
190
1
    let genesis_data_1001 = empty_genesis_data();
191
1
    let genesis_data_1002 = ContainerChainGenesisData {
192
1
        storage: vec![(b"key".to_vec(), b"value".to_vec()).into()],
193
1
        name: Default::default(),
194
1
        id: Default::default(),
195
1
        fork_id: Default::default(),
196
1
        extensions: vec![],
197
1
        properties: Default::default(),
198
1
    };
199
1
    ExtBuilder::default()
200
1
        .with_para_ids(vec![
201
1
            ParaRegistrationParams {
202
1
                para_id: 1001,
203
1
                genesis_data: genesis_data_1001.clone(),
204
1
                block_production_credits: u32::MAX,
205
1
                collator_assignment_credits: u32::MAX,
206
1
                parathread_params: None,
207
1
            },ParaRegistrationParams {
208
1
                para_id: 1002,
209
1
                genesis_data: genesis_data_1002.clone(),
210
1
                block_production_credits: u32::MAX,
211
1
                collator_assignment_credits: u32::MAX,
212
1
                parathread_params: None,
213
1
            },        ])
214
1
        .build()
215
1
        .execute_with(|| {
216
1
            assert_eq!(
217
1
                Registrar::registered_para_ids(),
218
1
                vec![1001.into(), 1002.into()]
219
1
            );
220
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
221

            
222
1
            assert_eq!(
223
1
                Runtime::genesis_data(1001.into()).as_ref(),
224
1
                Some(&genesis_data_1001)
225
1
            );
226
1
            assert_eq!(
227
1
                Runtime::genesis_data(1002.into()).as_ref(),
228
1
                Some(&genesis_data_1002)
229
1
            );
230
1
            assert_eq!(Runtime::genesis_data(1003.into()).as_ref(), None);
231

            
232
            // This API cannot be used to get the genesis data of the orchestrator chain,
233
            // with id 100
234
            // TODO: where is that 100 defined?
235
1
            assert_eq!(Runtime::genesis_data(100.into()).as_ref(), None);
236

            
237
1
            run_to_block(2);
238
1
            assert_ok!(Registrar::deregister(root_origin(), 1002.into()), ());
239

            
240
1
            assert_eq!(Runtime::genesis_data(1002.into()).as_ref(), Some(&genesis_data_1002), "Deregistered container chain genesis data should not be removed until after 2 sessions");
241

            
242
1
            let genesis_data_1003 = ContainerChainGenesisData {
243
1
                storage: vec![(b"key3".to_vec(), b"value3".to_vec()).into()],
244
1
                name: Default::default(),
245
1
                id: Default::default(),
246
1
                fork_id: Default::default(),
247
1
                extensions: vec![],
248
1
                properties: Default::default(),
249
1
            };
250
1
            assert_ok!(
251
1
                Registrar::register(
252
1
                    origin_of(ALICE.into()),
253
1
                    1003.into(),
254
1
                    genesis_data_1003.clone(),
255
1
                    None
256
1
                ),
257
1
                ()
258
1
            );
259

            
260
            // Registered container chains are inserted immediately
261
1
            assert_eq!(
262
1
                Runtime::genesis_data(1003.into()).as_ref(),
263
1
                Some(&genesis_data_1003)
264
1
            );
265

            
266
            // Deregistered container chain genesis data is removed after 2 sessions
267
1
            run_to_session(2u32);
268
1
            assert_eq!(Runtime::genesis_data(1002.into()).as_ref(), None);
269
1
        });
270
1
}
271

            
272
#[test]
273
1
fn test_author_collation_aura() {
274
1
    ExtBuilder::default()
275
1
        .with_empty_parachains(vec![1001, 1002])
276
1
        .build()
277
1
        .execute_with(|| {
278
1
            run_to_block(5);
279
1
            // Assert current slot gets updated
280
1
            assert_eq!(current_slot(), 4u64);
281
            // slot 4, alice
282
1
            assert!(current_author() == AccountId::from(ALICE));
283

            
284
1
            run_to_block(6);
285
1

            
286
1
            assert_eq!(current_slot(), 5u64);
287
            // slot 5, bob
288
1
            assert!(current_author() == AccountId::from(BOB));
289
1
        });
290
1
}
291

            
292
#[test]
293
1
fn test_author_collation_aura_change_of_authorities_on_session() {
294
1
    ExtBuilder::default()
295
1
        .with_balances(vec![
296
1
            // Alice gets 10k extra tokens for her mapping deposit
297
1
            (AccountId::from(ALICE), 210_000 * UNIT),
298
1
            (AccountId::from(BOB), 100_000 * UNIT),
299
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
300
1
            (AccountId::from(DAVE), 100_000 * UNIT),
301
1
        ])
302
1
        .with_empty_parachains(vec![1001, 1002])
303
1
        .build()
304
1
        .execute_with(|| {
305
1
            run_to_block(2);
306
1
            // Assert current slot gets updated
307
1
            assert_eq!(current_slot(), 1u64);
308
1
            assert!(current_author() == AccountId::from(BOB));
309

            
310
            // We change invulnerables
311
            // We first need to set the keys
312
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
313
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
314
1

            
315
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
316
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
317
1

            
318
1
            // Set CHARLIE and DAVE keys
319
1
            assert_ok!(Session::set_keys(
320
1
                origin_of(CHARLIE.into()),
321
1
                crate::SessionKeys {
322
1
                    nimbus: charlie_id.clone(),
323
1
                },
324
1
                vec![]
325
1
            ));
326
1
            assert_ok!(Session::set_keys(
327
1
                origin_of(DAVE.into()),
328
1
                crate::SessionKeys {
329
1
                    nimbus: dave_id.clone(),
330
1
                },
331
1
                vec![]
332
1
            ));
333

            
334
            // Change invulnerables
335
1
            assert_ok!(Invulnerables::remove_invulnerable(
336
1
                root_origin(),
337
1
                ALICE.into()
338
1
            ));
339
1
            assert_ok!(Invulnerables::remove_invulnerable(
340
1
                root_origin(),
341
1
                BOB.into()
342
1
            ));
343
1
            assert_ok!(Invulnerables::add_invulnerable(
344
1
                root_origin(),
345
1
                CHARLIE.into()
346
1
            ));
347
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
348

            
349
            // SESSION CHANGE. First session. it takes 2 sessions to see the change
350
1
            run_to_session(1u32);
351
1
            let author = get_orchestrator_current_author().unwrap();
352
1

            
353
1
            assert_eq!(current_author(), author);
354
1
            assert!(authorities() == vec![alice_id.clone(), bob_id.clone()]);
355

            
356
            // Invulnerables should have triggered on new session authorities change
357
1
            run_to_session(2u32);
358
1
            let author_after_changes = get_orchestrator_current_author().unwrap();
359
1

            
360
1
            assert_eq!(current_author(), author_after_changes);
361
1
            assert_eq!(authorities(), vec![charlie_id, dave_id]);
362
1
        });
363
1
}
364

            
365
#[test]
366
1
fn test_author_collation_aura_add_assigned_to_paras() {
367
1
    ExtBuilder::default()
368
1
        .with_balances(vec![
369
1
            // Alice gets 10k extra tokens for her mapping deposit
370
1
            (AccountId::from(ALICE), 210_000 * UNIT),
371
1
            (AccountId::from(BOB), 100_000 * UNIT),
372
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
373
1
            (AccountId::from(DAVE), 100_000 * UNIT),
374
1
        ])
375
1
        .with_empty_parachains(vec![1001, 1002])
376
1
        .build()
377
1
        .execute_with(|| {
378
1
            run_to_block(2);
379
1
            // Assert current slot gets updated
380
1
            assert_eq!(current_slot(), 1u64);
381
1
            assert!(current_author() == AccountId::from(BOB));
382

            
383
            // We change invulnerables
384
            // We first need to set the keys
385
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
386
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
387
1

            
388
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
389
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
390
1

            
391
1
            // Set CHARLIE and DAVE keys
392
1
            assert_ok!(Session::set_keys(
393
1
                origin_of(CHARLIE.into()),
394
1
                crate::SessionKeys { nimbus: charlie_id },
395
1
                vec![]
396
1
            ));
397
1
            assert_ok!(Session::set_keys(
398
1
                origin_of(DAVE.into()),
399
1
                crate::SessionKeys { nimbus: dave_id },
400
1
                vec![]
401
1
            ));
402

            
403
            // Add new invulnerables
404
1
            assert_ok!(Invulnerables::add_invulnerable(
405
1
                root_origin(),
406
1
                CHARLIE.into()
407
1
            ));
408
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
409

            
410
            // SESSION CHANGE. First session. it takes 2 sessions to see the change
411
1
            run_to_session(1u32);
412
1
            let author = get_orchestrator_current_author().unwrap();
413
1

            
414
1
            assert_eq!(current_author(), author);
415
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
416

            
417
            // Invulnerables should have triggered on new session authorities change
418
            // However charlie and dave should have gone to one para (1001)
419
1
            run_to_session(2u32);
420
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
421
1
            let assignment = CollatorAssignment::collator_container_chain();
422
1
            assert_eq!(
423
1
                assignment.container_chains[&1001u32.into()],
424
1
                vec![CHARLIE.into(), DAVE.into()]
425
1
            );
426
1
        });
427
1
}
428

            
429
#[test]
430
1
fn test_authors_without_paras() {
431
1
    ExtBuilder::default()
432
1
        .with_balances(vec![
433
1
            // Alice gets 10k extra tokens for her mapping deposit
434
1
            (AccountId::from(ALICE), 210_000 * UNIT),
435
1
            (AccountId::from(BOB), 100_000 * UNIT),
436
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
437
1
            (AccountId::from(DAVE), 100_000 * UNIT),
438
1
        ])
439
1
        .with_collators(vec![
440
1
            (AccountId::from(ALICE), 210 * UNIT),
441
1
            (AccountId::from(BOB), 100 * UNIT),
442
1
            (AccountId::from(CHARLIE), 100 * UNIT),
443
1
            (AccountId::from(DAVE), 100 * UNIT),
444
1
        ])
445
1
        .build()
446
1
        .execute_with(|| {
447
1
            run_to_block(2);
448
1
            // Assert current slot gets updated
449
1
            assert_eq!(current_slot(), 1u64);
450
1
            assert!(current_author() == AccountId::from(BOB));
451

            
452
            // Only Alice and Bob collate for our chain
453
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
454
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
455
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
456
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
457
1

            
458
1
            // It does not matter if we insert more collators, only two will be assigned
459
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
460

            
461
            // Set moondance collators to min 2 max 5
462
1
            assert_ok!(
463
1
                Configuration::set_min_orchestrator_collators(root_origin(), 2),
464
1
                ()
465
1
            );
466
1
            assert_ok!(
467
1
                Configuration::set_max_orchestrator_collators(root_origin(), 5),
468
1
                ()
469
1
            );
470

            
471
1
            run_to_session(2);
472
1
            assert_eq!(authorities(), vec![alice_id, bob_id, charlie_id, dave_id]);
473
1
        });
474
1
}
475

            
476
#[test]
477
1
fn test_authors_paras_inserted_a_posteriori() {
478
1
    ExtBuilder::default()
479
1
        .with_balances(vec![
480
1
            // Alice gets 10k extra tokens for her mapping deposit
481
1
            (AccountId::from(ALICE), 210_000 * UNIT),
482
1
            (AccountId::from(BOB), 100_000 * UNIT),
483
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
484
1
            (AccountId::from(DAVE), 100_000 * UNIT),
485
1
        ])
486
1
        .with_collators(vec![
487
1
            (AccountId::from(ALICE), 210 * UNIT),
488
1
            (AccountId::from(BOB), 100 * UNIT),
489
1
            (AccountId::from(CHARLIE), 100 * UNIT),
490
1
            (AccountId::from(DAVE), 100 * UNIT),
491
1
        ])
492
1
        .build()
493
1
        .execute_with(|| {
494
1
            run_to_block(2);
495
1
            // Assert current slot gets updated
496
1
            assert_eq!(current_slot(), 1u64);
497
1
            assert!(current_author() == AccountId::from(BOB));
498

            
499
            // Alice and Bob collate in our chain
500
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
501
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
502
1

            
503
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
504

            
505
1
            assert_ok!(Registrar::register(
506
1
                origin_of(ALICE.into()),
507
1
                1001.into(),
508
1
                empty_genesis_data(),
509
1
                None
510
1
            ));
511
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
512
1
            assert_ok!(Registrar::mark_valid_for_collating(
513
1
                root_origin(),
514
1
                1001.into()
515
1
            ));
516
1
            assert_ok!(ServicesPayment::purchase_credits(
517
1
                origin_of(ALICE.into()),
518
1
                1001.into(),
519
1
                block_credits_to_required_balance(1000, 1001.into())
520
1
            ));
521
1
            assert_ok!(Registrar::register(
522
1
                origin_of(ALICE.into()),
523
1
                1002.into(),
524
1
                empty_genesis_data(),
525
1
                None
526
1
            ));
527
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1002.into());
528
1
            assert_ok!(Registrar::mark_valid_for_collating(
529
1
                root_origin(),
530
1
                1002.into()
531
1
            ));
532
1
            assert_ok!(ServicesPayment::purchase_credits(
533
1
                origin_of(ALICE.into()),
534
1
                1002.into(),
535
1
                block_credits_to_required_balance(1000, 1002.into())
536
1
            ));
537

            
538
            // Assignment should happen after 2 sessions
539
1
            run_to_session(1u32);
540
1
            let assignment = CollatorAssignment::collator_container_chain();
541
1
            assert!(assignment.container_chains.is_empty());
542
1
            run_to_session(2u32);
543
1

            
544
1
            // Charlie and Dave should be assigned to para 1001
545
1
            let assignment = CollatorAssignment::collator_container_chain();
546
1
            assert_eq!(
547
1
                assignment.container_chains[&1001u32.into()],
548
1
                vec![CHARLIE.into(), DAVE.into()]
549
1
            );
550
1
        });
551
1
}
552

            
553
#[test]
554
1
fn test_authors_paras_inserted_a_posteriori_with_collators_already_assigned() {
555
1
    ExtBuilder::default()
556
1
        .with_balances(vec![
557
1
            // Alice gets 10k extra tokens for her mapping deposit
558
1
            (AccountId::from(ALICE), 210_000 * UNIT),
559
1
            (AccountId::from(BOB), 100_000 * UNIT),
560
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
561
1
            (AccountId::from(DAVE), 100_000 * UNIT),
562
1
        ])
563
1
        .with_collators(vec![
564
1
            (AccountId::from(ALICE), 210 * UNIT),
565
1
            (AccountId::from(BOB), 100 * UNIT),
566
1
            (AccountId::from(CHARLIE), 100 * UNIT),
567
1
            (AccountId::from(DAVE), 100 * UNIT),
568
1
        ])
569
1
        .with_config(pallet_configuration::HostConfiguration {
570
1
            max_collators: 100,
571
1
            min_orchestrator_collators: 2,
572
1
            max_orchestrator_collators: 5,
573
1
            collators_per_container: 2,
574
1
            full_rotation_period: 0,
575
1
            ..Default::default()
576
1
        })
577
1
        .build()
578
1
        .execute_with(|| {
579
1
            run_to_block(2);
580
1
            // Assert current slot gets updated
581
1
            assert_eq!(current_slot(), 1u64);
582
1
            assert!(current_author() == AccountId::from(BOB));
583

            
584
            // Alice and Bob collate in our chain
585
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
586
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
587
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
588
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
589
1

            
590
1
            assert_eq!(authorities(), vec![alice_id, bob_id, charlie_id, dave_id]);
591

            
592
1
            assert_ok!(Registrar::register(
593
1
                origin_of(ALICE.into()),
594
1
                1001.into(),
595
1
                empty_genesis_data(),
596
1
                None
597
1
            ));
598
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
599
1
            assert_ok!(Registrar::mark_valid_for_collating(
600
1
                root_origin(),
601
1
                1001.into()
602
1
            ));
603
1
            assert_ok!(ServicesPayment::purchase_credits(
604
1
                origin_of(ALICE.into()),
605
1
                1001.into(),
606
1
                block_credits_to_required_balance(1000, 1001.into())
607
1
            ));
608

            
609
            // Assignment should happen after 2 sessions
610
1
            run_to_session(1u32);
611
1
            let assignment = CollatorAssignment::collator_container_chain();
612
1
            assert!(assignment.container_chains.is_empty());
613
1
            run_to_session(2u32);
614
1

            
615
1
            // Charlie and Dave are now assigned to para 1001
616
1
            let assignment = CollatorAssignment::collator_container_chain();
617
1
            assert_eq!(
618
1
                assignment.container_chains[&1001u32.into()],
619
1
                vec![CHARLIE.into(), DAVE.into()]
620
1
            );
621
1
            assert_eq!(
622
1
                assignment.orchestrator_chain,
623
1
                vec![ALICE.into(), BOB.into()]
624
1
            );
625
1
        });
626
1
}
627

            
628
#[test]
629
1
fn test_paras_registered_but_zero_credits() {
630
1
    ExtBuilder::default()
631
1
        .with_balances(vec![
632
1
            // Alice gets 10k extra tokens for her mapping deposit
633
1
            (AccountId::from(ALICE), 210_000 * UNIT),
634
1
            (AccountId::from(BOB), 100_000 * UNIT),
635
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
636
1
            (AccountId::from(DAVE), 100_000 * UNIT),
637
1
        ])
638
1
        .with_collators(vec![
639
1
            (AccountId::from(ALICE), 210 * UNIT),
640
1
            (AccountId::from(BOB), 100 * UNIT),
641
1
            (AccountId::from(CHARLIE), 100 * UNIT),
642
1
            (AccountId::from(DAVE), 100 * UNIT),
643
1
        ])
644
1
        .build()
645
1
        .execute_with(|| {
646
1
            run_to_block(2);
647
1
            // Assert current slot gets updated
648
1
            assert_eq!(current_slot(), 1u64);
649
1
            assert!(current_author() == AccountId::from(BOB));
650

            
651
            // Alice and Bob collate in our chain
652
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
653
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
654
1

            
655
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
656

            
657
1
            assert_ok!(Registrar::register(
658
1
                origin_of(ALICE.into()),
659
1
                1001.into(),
660
1
                empty_genesis_data(),
661
1
                None
662
1
            ));
663
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
664
1
            assert_ok!(Registrar::mark_valid_for_collating(
665
1
                root_origin(),
666
1
                1001.into()
667
1
            ));
668
            // Need to reset credits to 0 because now parachains are given free credits on register
669
1
            assert_ok!(ServicesPayment::set_block_production_credits(
670
1
                root_origin(),
671
1
                1001.into(),
672
1
                0
673
1
            ));
674

            
675
            // Assignment should happen after 2 sessions
676
1
            run_to_session(1u32);
677
1
            let assignment = CollatorAssignment::collator_container_chain();
678
1
            assert!(assignment.container_chains.is_empty());
679
1
            run_to_session(2u32);
680
1

            
681
1
            // Nobody should be assigned to para 1001
682
1
            let assignment = CollatorAssignment::collator_container_chain();
683
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None);
684
1
        });
685
1
}
686

            
687
#[test]
688
1
fn test_paras_registered_but_not_enough_credits() {
689
1
    ExtBuilder::default()
690
1
        .with_balances(vec![
691
1
            // Alice gets 10k extra tokens for her mapping deposit
692
1
            (AccountId::from(ALICE), 210_000 * UNIT),
693
1
            (AccountId::from(BOB), 100_000 * UNIT),
694
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
695
1
            (AccountId::from(DAVE), 100_000 * UNIT),
696
1
        ])
697
1
        .with_collators(vec![
698
1
            (AccountId::from(ALICE), 210 * UNIT),
699
1
            (AccountId::from(BOB), 100 * UNIT),
700
1
            (AccountId::from(CHARLIE), 100 * UNIT),
701
1
            (AccountId::from(DAVE), 100 * UNIT),
702
1
        ])
703
1
        .build()
704
1
        .execute_with(|| {
705
1
            run_to_block(2);
706
1
            // Assert current slot gets updated
707
1
            assert_eq!(current_slot(), 1u64);
708
1
            assert!(current_author() == AccountId::from(BOB));
709

            
710
            // Alice and Bob collate in our chain
711
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
712
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
713
1

            
714
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
715

            
716
1
            assert_ok!(Registrar::register(
717
1
                origin_of(ALICE.into()),
718
1
                1001.into(),
719
1
                empty_genesis_data(),
720
1
                None
721
1
            ));
722
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
723
1
            assert_ok!(Registrar::mark_valid_for_collating(
724
1
                root_origin(),
725
1
                1001.into()
726
1
            ));
727
            // Need to reset credits to 0 because now parachains are given free credits on register
728
1
            assert_ok!(ServicesPayment::set_block_production_credits(
729
1
                root_origin(),
730
1
                1001.into(),
731
1
                0
732
1
            ));
733
            // Purchase 1 credit less that what is needed
734
1
            let credits_1001 = crate::Period::get() - 1;
735
1
            assert_ok!(ServicesPayment::set_block_production_credits(
736
1
                root_origin(),
737
1
                1001.into(),
738
1
                credits_1001
739
1
            ));
740

            
741
            // Assignment should happen after 2 sessions
742
1
            run_to_session(1u32);
743
1
            let assignment = CollatorAssignment::collator_container_chain();
744
1
            assert!(assignment.container_chains.is_empty());
745
1
            run_to_session(2u32);
746
1
            // Nobody should be assigned to para 1001
747
1
            let assignment = CollatorAssignment::collator_container_chain();
748
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None);
749

            
750
            // Now purchase the missing block credit
751
1
            assert_ok!(ServicesPayment::set_block_production_credits(
752
1
                root_origin(),
753
1
                1001.into(),
754
1
                credits_1001 + 1
755
1
            ));
756

            
757
1
            run_to_session(4u32);
758
1
            // Charlie and Dave should be assigned to para 1001
759
1
            let assignment = CollatorAssignment::collator_container_chain();
760
1
            assert_eq!(
761
1
                assignment.container_chains[&1001u32.into()],
762
1
                vec![CHARLIE.into(), DAVE.into()]
763
1
            );
764
1
        });
765
1
}
766

            
767
#[test]
768
1
fn test_paras_registered_but_only_credits_for_1_session() {
769
1
    ExtBuilder::default()
770
1
        .with_balances(vec![
771
1
            // Alice gets 10k extra tokens for her mapping deposit
772
1
            (AccountId::from(ALICE), 210_000 * UNIT),
773
1
            (AccountId::from(BOB), 100_000 * UNIT),
774
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
775
1
            (AccountId::from(DAVE), 100_000 * UNIT),
776
1
        ])
777
1
        .with_collators(vec![
778
1
            (AccountId::from(ALICE), 210 * UNIT),
779
1
            (AccountId::from(BOB), 100 * UNIT),
780
1
            (AccountId::from(CHARLIE), 100 * UNIT),
781
1
            (AccountId::from(DAVE), 100 * UNIT),
782
1
        ])
783
1
        .build()
784
1
        .execute_with(|| {
785
1
            run_to_block(2);
786
1
            // Assert current slot gets updated
787
1
            assert_eq!(current_slot(), 1u64);
788
1
            assert!(current_author() == AccountId::from(BOB));
789

            
790
            // Alice and Bob collate in our chain
791
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
792
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
793
1

            
794
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
795

            
796
1
            assert_ok!(Registrar::register(
797
1
                origin_of(ALICE.into()),
798
1
                1001.into(),
799
1
                empty_genesis_data(),
800
1
                None
801
1
            ));
802
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
803
1
            assert_ok!(Registrar::mark_valid_for_collating(
804
1
                root_origin(),
805
1
                1001.into()
806
1
            ));
807
            // Need to reset credits to 0 because now parachains are given free credits on register
808
1
            assert_ok!(ServicesPayment::set_block_production_credits(
809
1
                root_origin(),
810
1
                1001.into(),
811
1
                0
812
1
            ));
813
            // Purchase only enough credits for 1 session
814
1
            let credits_1001 = crate::Period::get();
815
1
            assert_ok!(ServicesPayment::set_block_production_credits(
816
1
                root_origin(),
817
1
                1001.into(),
818
1
                credits_1001
819
1
            ));
820

            
821
            // Assignment should happen after 2 sessions
822
1
            run_to_session(1u32);
823
1
            let assignment = CollatorAssignment::collator_container_chain();
824
1
            assert!(assignment.container_chains.is_empty());
825
1
            run_to_session(2u32);
826
1
            // Charlie and Dave should be assigned to para 1001
827
1
            let assignment = CollatorAssignment::collator_container_chain();
828
1
            assert_eq!(
829
1
                assignment.container_chains[&1001u32.into()],
830
1
                vec![CHARLIE.into(), DAVE.into()]
831
1
            );
832

            
833
            // No credits are consumed if the container chain is not producing blocks
834
1
            run_block();
835
1
            let credits =
836
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
837
1
                    .unwrap_or_default();
838
1
            assert_eq!(credits, credits_1001);
839

            
840
            // Simulate block inclusion from container chain 1001
841
1
            let mut sproof = ParaHeaderSproofBuilder::default();
842
1
            let slot: u64 = 5;
843
1
            let s = ParaHeaderSproofBuilderItem {
844
1
                para_id: 1001.into(),
845
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
846
1
                    parent_hash: Default::default(),
847
1
                    number: 1,
848
1
                    state_root: Default::default(),
849
1
                    extrinsics_root: Default::default(),
850
1
                    digest: sp_runtime::generic::Digest {
851
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
852
1
                    },
853
1
                }),
854
1
            };
855
1
            sproof.items.push(s);
856
1
            set_author_noting_inherent_data(sproof);
857
1

            
858
1
            run_block();
859
1
            let credits =
860
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
861
1
                    .unwrap_or_default();
862
1
            assert_eq!(credits, credits_1001 - 1);
863

            
864
1
            run_to_session(4u32);
865
1
            // Nobody should be assigned to para 1001
866
1
            let assignment = CollatorAssignment::collator_container_chain();
867
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
868

            
869
            // The container chain only produced one block, so it only consumed one block credit.
870
            // (it could have produced more blocks, but at most it would have consumed `Period::get()` credits)
871
1
            let credits =
872
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
873
1
                    .unwrap_or_default();
874
1
            assert_eq!(credits, credits_1001 - 1);
875
1
        });
876
1
}
877

            
878
#[test]
879
1
fn test_parachains_deregister_collators_re_assigned() {
880
1
    ExtBuilder::default()
881
1
        .with_balances(vec![
882
1
            // Alice gets 10k extra tokens for her mapping deposit
883
1
            (AccountId::from(ALICE), 210_000 * UNIT),
884
1
            (AccountId::from(BOB), 100_000 * UNIT),
885
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
886
1
            (AccountId::from(DAVE), 100_000 * UNIT),
887
1
        ])
888
1
        .with_collators(vec![
889
1
            (AccountId::from(ALICE), 210 * UNIT),
890
1
            (AccountId::from(BOB), 100 * UNIT),
891
1
            (AccountId::from(CHARLIE), 100 * UNIT),
892
1
            (AccountId::from(DAVE), 100 * UNIT),
893
1
        ])
894
1
        .with_empty_parachains(vec![1001, 1002])
895
1
        .build()
896
1
        .execute_with(|| {
897
1
            run_to_block(2);
898
1
            // Assert current slot gets updated
899
1
            assert_eq!(current_slot(), 1u64);
900
1
            assert!(current_author() == AccountId::from(BOB));
901

            
902
            // Alice and Bob are authorities
903
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
904
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
905
1

            
906
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
907

            
908
            // Charlie and Dave to 1001
909
1
            let assignment = CollatorAssignment::collator_container_chain();
910
1
            assert_eq!(
911
1
                assignment.container_chains[&1001u32.into()],
912
1
                vec![CHARLIE.into(), DAVE.into()]
913
1
            );
914

            
915
1
            assert_ok!(Registrar::deregister(root_origin(), 1001.into()), ());
916

            
917
            // Assignment should happen after 2 sessions
918
1
            run_to_session(1u32);
919
1

            
920
1
            let assignment = CollatorAssignment::collator_container_chain();
921
1
            assert_eq!(
922
1
                assignment.container_chains[&1001u32.into()],
923
1
                vec![CHARLIE.into(), DAVE.into()]
924
1
            );
925

            
926
1
            run_to_session(2u32);
927
1

            
928
1
            // Charlie and Dave should be assigne dot para 1002 this time
929
1
            let assignment = CollatorAssignment::collator_container_chain();
930
1
            assert_eq!(
931
1
                assignment.container_chains[&1002u32.into()],
932
1
                vec![CHARLIE.into(), DAVE.into()]
933
1
            );
934
1
        });
935
1
}
936

            
937
#[test]
938
1
fn test_parachains_deregister_collators_config_change_reassigned() {
939
1
    ExtBuilder::default()
940
1
        .with_balances(vec![
941
1
            // Alice gets 10k extra tokens for her mapping deposit
942
1
            (AccountId::from(ALICE), 210_000 * UNIT),
943
1
            (AccountId::from(BOB), 100_000 * UNIT),
944
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
945
1
            (AccountId::from(DAVE), 100_000 * UNIT),
946
1
        ])
947
1
        .with_collators(vec![
948
1
            (AccountId::from(ALICE), 210 * UNIT),
949
1
            (AccountId::from(BOB), 100 * UNIT),
950
1
            (AccountId::from(CHARLIE), 100 * UNIT),
951
1
            (AccountId::from(DAVE), 100 * UNIT),
952
1
        ])
953
1
        .with_empty_parachains(vec![1001, 1002])
954
1
        .build()
955
1
        .execute_with(|| {
956
1
            run_to_block(2);
957
1
            // Assert current slot gets updated
958
1
            assert_eq!(current_slot(), 1u64);
959
1
            assert!(current_author() == AccountId::from(BOB));
960

            
961
            // Alice and Bob are authorities
962
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
963
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
964
1

            
965
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
966

            
967
            // Set orchestrator collators to 1
968
1
            assert_ok!(
969
1
                Configuration::set_max_orchestrator_collators(root_origin(), 1),
970
1
                ()
971
1
            );
972

            
973
            // Set container chain collators to 3
974
1
            assert_ok!(
975
1
                Configuration::set_collators_per_container(root_origin(), 3),
976
1
                ()
977
1
            );
978

            
979
            // Charlie and Dave to 1001
980
1
            let assignment = CollatorAssignment::collator_container_chain();
981
1
            assert_eq!(
982
1
                assignment.container_chains[&1001u32.into()],
983
1
                vec![CHARLIE.into(), DAVE.into()]
984
1
            );
985

            
986
            // Assignment should happen after 2 sessions
987
1
            run_to_session(1u32);
988
1

            
989
1
            let assignment = CollatorAssignment::collator_container_chain();
990
1
            assert_eq!(
991
1
                assignment.container_chains[&1001u32.into()],
992
1
                vec![CHARLIE.into(), DAVE.into()]
993
1
            );
994

            
995
1
            run_to_session(2u32);
996
1

            
997
1
            // Charlie, Dave and BOB should be assigne dot para 1001 this time
998
1
            let assignment = CollatorAssignment::collator_container_chain();
999
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into(), BOB.into()]
1
            );
1
            assert_eq!(assignment.orchestrator_chain, vec![ALICE.into()]);
1
        });
1
}
#[test]
1
fn test_orchestrator_collators_with_non_sufficient_collators() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
        ])
1
        .with_collators(vec![(AccountId::from(ALICE), 210 * UNIT)])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(ALICE));
            // Alice and Bob are authorities
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id]);
1
        });
1
}
#[test]
1
fn test_configuration_on_session_change() {
1
    ExtBuilder::default().build().execute_with(|| {
1
        assert_eq!(Configuration::config().max_collators, 100);
1
        assert_eq!(Configuration::config().min_orchestrator_collators, 2);
1
        assert_eq!(Configuration::config().collators_per_container, 2);
1
        assert_ok!(Configuration::set_max_collators(root_origin(), 50), ());
1
        run_to_session(1u32);
1

            
1
        assert_ok!(
1
            Configuration::set_min_orchestrator_collators(root_origin(), 20),
1
            ()
1
        );
1
        assert_eq!(Configuration::config().max_collators, 100);
1
        assert_eq!(Configuration::config().min_orchestrator_collators, 2);
1
        assert_eq!(Configuration::config().collators_per_container, 2);
1
        run_to_session(2u32);
1
        assert_ok!(
1
            Configuration::set_collators_per_container(root_origin(), 10),
1
            ()
1
        );
1
        assert_eq!(Configuration::config().max_collators, 50);
1
        assert_eq!(Configuration::config().min_orchestrator_collators, 2);
1
        assert_eq!(Configuration::config().collators_per_container, 2);
1
        run_to_session(3u32);
1

            
1
        assert_eq!(Configuration::config().max_collators, 50);
1
        assert_eq!(Configuration::config().min_orchestrator_collators, 20);
1
        assert_eq!(Configuration::config().collators_per_container, 2);
1
        run_to_session(4u32);
1

            
1
        assert_eq!(Configuration::config().max_collators, 50);
1
        assert_eq!(Configuration::config().min_orchestrator_collators, 20);
1
        assert_eq!(Configuration::config().collators_per_container, 10);
1
    });
1
}
#[test]
1
fn test_author_collation_aura_add_assigned_to_paras_runtime_api() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
1
            assert_eq!(
1
                Runtime::parachain_collators(100.into()),
1
                Some(vec![ALICE.into(), BOB.into()])
1
            );
1
            assert_eq!(Runtime::parachain_collators(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(ALICE.into()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(ALICE.into()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(CHARLIE.into()),
1
                None
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(CHARLIE.into()),
1
                None
1
            );
            // We change invulnerables
            // We first need to set the keys
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
1

            
1
            // Set CHARLIE and DAVE keys
1
            assert_ok!(Session::set_keys(
1
                origin_of(CHARLIE.into()),
1
                crate::SessionKeys { nimbus: charlie_id },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(DAVE.into()),
1
                crate::SessionKeys { nimbus: dave_id },
1
                vec![]
1
            ));
            // Set new invulnerables
1
            assert_ok!(Invulnerables::add_invulnerable(
1
                root_origin(),
1
                CHARLIE.into()
1
            ));
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
            // SESSION CHANGE. First session. it takes 2 sessions to see the change
1
            run_to_session(1u32);
1
            let author = get_orchestrator_current_author().unwrap();
1

            
1
            assert_eq!(current_author(), author);
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
1
            assert_eq!(
1
                Runtime::parachain_collators(100.into()),
1
                Some(vec![ALICE.into(), BOB.into()])
1
            );
1
            assert_eq!(Runtime::parachain_collators(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(CHARLIE.into()),
1
                None
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(CHARLIE.into()),
1
                Some(1001.into())
1
            );
            // Invulnerables should have triggered on new session authorities change
            // However charlie and dave shoudl have gone to one para (1001)
1
            run_to_session(2u32);
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
1
            assert_eq!(
1
                Runtime::parachain_collators(100.into()),
1
                Some(vec![ALICE.into(), BOB.into()])
1
            );
1
            assert_eq!(
1
                Runtime::parachain_collators(1001.into()),
1
                Some(vec![CHARLIE.into(), DAVE.into()])
1
            );
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(CHARLIE.into()),
1
                Some(1001.into())
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(CHARLIE.into()),
1
                Some(1001.into())
1
            );
            // Remove BOB
1
            assert_ok!(Invulnerables::remove_invulnerable(
1
                root_origin(),
1
                BOB.into()
1
            ));
1
            run_to_session(3u32);
1
            assert_eq!(
1
                Runtime::parachain_collators(100.into()),
1
                Some(vec![ALICE.into(), BOB.into()])
1
            );
1
            assert_eq!(
1
                Runtime::parachain_collators(1001.into()),
1
                Some(vec![CHARLIE.into(), DAVE.into()])
1
            );
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(BOB.into()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(BOB.into()),
1
                None
1
            );
1
            run_to_session(4u32);
1
            assert_eq!(
1
                Runtime::parachain_collators(100.into()),
1
                Some(vec![ALICE.into(), CHARLIE.into()])
1
            );
1
            assert_eq!(Runtime::parachain_collators(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::current_collator_parachain_assignment(BOB.into()),
1
                None
1
            );
1
            assert_eq!(
1
                Runtime::future_collator_parachain_assignment(BOB.into()),
1
                None
1
            );
1
        });
1
}
#[test]
1
fn test_consensus_runtime_api() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
1

            
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(Runtime::para_id_authorities(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(charlie_id.clone()), None);
1
            assert_eq!(Runtime::check_para_id_assignment(dave_id.clone()), None);
            // Set CHARLIE and DAVE keys
1
            assert_ok!(Session::set_keys(
1
                origin_of(CHARLIE.into()),
1
                crate::SessionKeys {
1
                    nimbus: charlie_id.clone(),
1
                },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(DAVE.into()),
1
                crate::SessionKeys {
1
                    nimbus: dave_id.clone(),
1
                },
1
                vec![]
1
            ));
            // Set new invulnerables
1
            assert_ok!(Invulnerables::add_invulnerable(
1
                root_origin(),
1
                CHARLIE.into()
1
            ));
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
1
            run_to_session(2u32);
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::para_id_authorities(1001.into()),
1
                Some(vec![charlie_id.clone(), dave_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(bob_id), Some(100.into()));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(charlie_id),
1
                Some(1001.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(dave_id),
1
                Some(1001.into())
1
            );
1
        });
1
}
#[test]
1
fn test_consensus_runtime_api_session_changes() {
1
    // The test shoul return always the assiignment on the next epoch
1
    // Meaning that we need to see before the session change block
1
    // if we can predict correctly
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
1

            
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(Runtime::para_id_authorities(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(charlie_id.clone()), None);
1
            assert_eq!(Runtime::check_para_id_assignment(dave_id.clone()), None);
            // Set CHARLIE and DAVE keys
1
            assert_ok!(Session::set_keys(
1
                origin_of(CHARLIE.into()),
1
                crate::SessionKeys {
1
                    nimbus: charlie_id.clone(),
1
                },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(DAVE.into()),
1
                crate::SessionKeys {
1
                    nimbus: dave_id.clone(),
1
                },
1
                vec![]
1
            ));
            // Set new invulnerables
1
            assert_ok!(Invulnerables::add_invulnerable(
1
                root_origin(),
1
                CHARLIE.into()
1
            ));
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
1
            let session_two_edge = crate::Period::get() * 2;
1
            // Let's run just 2 blocks before the session 2 change first
1
            // Prediction should still be identical, as we are not in the
1
            // edge of a session change
1
            run_to_block(session_two_edge - 2);
1

            
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(Runtime::para_id_authorities(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(charlie_id.clone()), None);
1
            assert_eq!(Runtime::check_para_id_assignment(dave_id.clone()), None);
            // Now we run to session edge -1. Here we should predict already with
            // authorities of the next block!
1
            run_to_block(session_two_edge - 1);
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::para_id_authorities(1001.into()),
1
                Some(vec![charlie_id.clone(), dave_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(bob_id), Some(100.into()));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(charlie_id),
1
                Some(1001.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(dave_id),
1
                Some(1001.into())
1
            );
1
        });
1
}
#[test]
1
fn test_consensus_runtime_api_next_session() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            let charlie_id = get_aura_id_from_seed(&AccountId::from(CHARLIE).to_string());
1
            let dave_id = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
1

            
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(Runtime::para_id_authorities(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(charlie_id.clone()), None);
1
            assert_eq!(Runtime::check_para_id_assignment(dave_id.clone()), None);
            // In the next session the assignment will not change
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(charlie_id.clone()),
1
                None,
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(dave_id.clone()),
1
                None,
1
            );
            // Set CHARLIE and DAVE keys
1
            assert_ok!(Session::set_keys(
1
                origin_of(CHARLIE.into()),
1
                crate::SessionKeys {
1
                    nimbus: charlie_id.clone(),
1
                },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(DAVE.into()),
1
                crate::SessionKeys {
1
                    nimbus: dave_id.clone(),
1
                },
1
                vec![]
1
            ));
            // Set new invulnerables
1
            assert_ok!(Invulnerables::add_invulnerable(
1
                root_origin(),
1
                CHARLIE.into()
1
            ));
1
            assert_ok!(Invulnerables::add_invulnerable(root_origin(), DAVE.into()));
1
            let session_two_edge = crate::Period::get() * 2;
1
            // Let's run just 2 blocks before the session 2 change first
1
            // Prediction should still be identical, as we are not in the
1
            // edge of a session change
1
            run_to_block(session_two_edge - 2);
1

            
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(Runtime::para_id_authorities(1001.into()), Some(vec![]));
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(Runtime::check_para_id_assignment(charlie_id.clone()), None);
1
            assert_eq!(Runtime::check_para_id_assignment(dave_id.clone()), None);
            // But in the next session the assignment will change, so future api returns different value
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(charlie_id.clone()),
1
                Some(1001.into()),
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(dave_id.clone()),
1
                Some(1001.into()),
1
            );
            // Now we run to session edge -1. Here we should predict already with
            // authorities of the next block!
1
            run_to_block(session_two_edge - 1);
1
            assert_eq!(
1
                Runtime::para_id_authorities(100.into()),
1
                Some(vec![alice_id.clone(), bob_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::para_id_authorities(1001.into()),
1
                Some(vec![charlie_id.clone(), dave_id.clone()])
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(alice_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(bob_id.clone()),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(charlie_id.clone()),
1
                Some(1001.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment(dave_id.clone()),
1
                Some(1001.into())
1
            );
            // check_para_id_assignment_next_session returns the same value as check_para_id_assignment
            // because we are on a session boundary
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(alice_id),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(bob_id),
1
                Some(100.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(charlie_id),
1
                Some(1001.into())
1
            );
1
            assert_eq!(
1
                Runtime::check_para_id_assignment_next_session(dave_id),
1
                Some(1001.into())
1
            );
1
        });
1
}
#[test]
1
fn test_author_noting_self_para_id_not_noting() {
1
    ExtBuilder::default().build().execute_with(|| {
1
        let mut sproof = ParaHeaderSproofBuilder::default();
1
        let slot: u64 = 5;
1
        let self_para = parachain_info::Pallet::<Runtime>::get();
1
        let s = ParaHeaderSproofBuilderItem {
1
            para_id: self_para,
1
            author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                parent_hash: Default::default(),
1
                number: Default::default(),
1
                state_root: Default::default(),
1
                extrinsics_root: Default::default(),
1
                digest: sp_runtime::generic::Digest {
1
                    logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                },
1
            }),
1
        };
1
        sproof.items.push(s);
1

            
1
        set_author_noting_inherent_data(sproof);
1

            
1
        assert_eq!(AuthorNoting::latest_author(self_para), None);
1
    });
1
}
#[test]
1
fn test_author_noting_not_self_para() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            let mut sproof = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let other_para: ParaId = 1001u32.into();
1

            
1
            // Charlie and Dave to 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: other_para,
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1
            sproof.items.push(s);
1

            
1
            set_author_noting_inherent_data(sproof);
1

            
1
            assert_eq!(
1
                AuthorNoting::latest_author(other_para),
1
                Some(ContainerChainBlockInfo {
1
                    block_number: 1,
1
                    author: AccountId::from(DAVE),
1
                    latest_slot_number: 0.into(),
1
                })
1
            );
1
        });
1
}
#[test]
1
fn test_author_noting_set_author_and_kill_author_data() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            let other_para: ParaId = 1001u32.into();
1

            
1
            assert_ok!(AuthorNoting::set_author(
1
                root_origin(),
1
                other_para,
1
                1,
1
                AccountId::from(DAVE),
1
                1.into()
1
            ));
1
            assert_eq!(
1
                AuthorNoting::latest_author(other_para),
1
                Some(ContainerChainBlockInfo {
1
                    block_number: 1,
1
                    author: AccountId::from(DAVE),
1
                    latest_slot_number: 1.into(),
1
                })
1
            );
1
            assert_ok!(AuthorNoting::kill_author_data(root_origin(), other_para));
1
            assert_eq!(AuthorNoting::latest_author(other_para), None);
1
        });
1
}
#[test]
1
fn test_author_noting_set_author_and_kill_author_data_bad_origin() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            let other_para: ParaId = 1001u32.into();
1

            
1
            assert_noop!(
1
                AuthorNoting::set_author(
1
                    origin_of(ALICE.into()),
1
                    other_para,
1
                    1,
1
                    AccountId::from(DAVE),
1
                    1.into()
1
                ),
1
                BadOrigin
1
            );
1
            assert_noop!(
1
                AuthorNoting::kill_author_data(origin_of(ALICE.into()), other_para),
1
                BadOrigin
1
            );
1
        });
1
}
#[test]
1
fn test_author_noting_runtime_api() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            let mut sproof = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let other_para: ParaId = 1001u32.into();
1

            
1
            // Charlie and Dave to 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: other_para,
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1
            sproof.items.push(s);
1

            
1
            set_author_noting_inherent_data(sproof);
1

            
1
            assert_eq!(
1
                AuthorNoting::latest_author(other_para),
1
                Some(ContainerChainBlockInfo {
1
                    block_number: 1,
1
                    author: AccountId::from(DAVE),
1
                    latest_slot_number: 0.into(),
1
                })
1
            );
1
            assert_eq!(
1
                Runtime::latest_author(other_para),
1
                Some(AccountId::from(DAVE))
1
            );
1
            assert_eq!(Runtime::latest_block_number(other_para), Some(1));
1
        });
1
}
#[test]
1
fn session_keys_key_type_id() {
1
    assert_eq!(crate::SessionKeys::key_ids(), vec![NIMBUS_KEY_ID]);
1
}
#[test]
1
fn test_session_keys_with_authority_mapping() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            let key_mapping_session_0 = AuthorityMapping::authority_id_mapping(0).unwrap();
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1
            let alice_id_2 = get_aura_id_from_seed("ALICE2");
1
            let bob_id_2 = get_aura_id_from_seed("BOB2");
1

            
1
            assert_eq!(key_mapping_session_0.len(), 2);
1
            assert_eq!(key_mapping_session_0.get(&alice_id), Some(&ALICE.into()));
1
            assert_eq!(key_mapping_session_0.get(&bob_id), Some(&BOB.into()));
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
            // Change Alice and Bob keys to something different
            // for now lets change it to alice_2 and bob_2
1
            assert_ok!(Session::set_keys(
1
                origin_of(ALICE.into()),
1
                crate::SessionKeys {
1
                    nimbus: alice_id_2.clone(),
1
                },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(BOB.into()),
1
                crate::SessionKeys {
1
                    nimbus: bob_id_2.clone(),
1
                },
1
                vec![]
1
            ));
1
            run_to_session(1u32);
1
            let key_mapping_session_0 = AuthorityMapping::authority_id_mapping(0).unwrap();
1
            assert_eq!(key_mapping_session_0.len(), 2);
1
            assert_eq!(key_mapping_session_0.get(&alice_id), Some(&ALICE.into()));
1
            assert_eq!(key_mapping_session_0.get(&bob_id), Some(&BOB.into()));
1
            let key_mapping_session_1 = AuthorityMapping::authority_id_mapping(1).unwrap();
1
            assert_eq!(key_mapping_session_1.len(), 2);
1
            assert_eq!(key_mapping_session_1.get(&alice_id), Some(&ALICE.into()));
1
            assert_eq!(key_mapping_session_1.get(&bob_id), Some(&BOB.into()));
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
            //
1
            run_to_session(2u32);
1
            assert!(AuthorityMapping::authority_id_mapping(0).is_none());
1
            let key_mapping_session_1 = AuthorityMapping::authority_id_mapping(1).unwrap();
1
            assert_eq!(key_mapping_session_1.len(), 2);
1
            assert_eq!(key_mapping_session_1.get(&alice_id), Some(&ALICE.into()));
1
            assert_eq!(key_mapping_session_1.get(&bob_id), Some(&BOB.into()));
1
            let key_mapping_session_2 = AuthorityMapping::authority_id_mapping(2).unwrap();
1
            assert_eq!(key_mapping_session_2.len(), 2);
1
            assert_eq!(key_mapping_session_2.get(&alice_id_2), Some(&ALICE.into()));
1
            assert_eq!(key_mapping_session_2.get(&bob_id_2), Some(&BOB.into()));
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id_2, bob_id_2]);
1
        });
1
}
#[test]
1
fn test_session_keys_with_authority_assignment() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1
            let alice_id_2 = get_aura_id_from_seed("ALICE2");
1
            let bob_id_2 = get_aura_id_from_seed("BOB2");
1

            
1
            let key_mapping_session_0 = AuthorityAssignment::collator_container_chain(0).unwrap();
1
            assert_eq!(
1
                key_mapping_session_0.orchestrator_chain,
1
                vec![alice_id.clone(), bob_id.clone()],
1
            );
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().orchestrator_chain,
1
                vec![AccountId::from(ALICE), AccountId::from(BOB)],
1
            );
1
            let key_mapping_session_1 = AuthorityAssignment::collator_container_chain(1).unwrap();
1
            assert_eq!(key_mapping_session_1, key_mapping_session_0,);
1
            let old_assignment_session_1 =
1
                CollatorAssignment::pending_collator_container_chain().unwrap();
1
            assert_eq!(
1
                old_assignment_session_1,
1
                CollatorAssignment::collator_container_chain(),
1
            );
1
            let key_mapping_session_2 = AuthorityAssignment::collator_container_chain(2);
1
            assert!(key_mapping_session_2.is_none());
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id.clone(), bob_id.clone()]);
            // Change Alice and Bob keys to something different
            // for now lets change it to alice_2 and bob_2
1
            assert_ok!(Session::set_keys(
1
                origin_of(ALICE.into()),
1
                crate::SessionKeys {
1
                    nimbus: alice_id_2.clone(),
1
                },
1
                vec![]
1
            ));
1
            assert_ok!(Session::set_keys(
1
                origin_of(BOB.into()),
1
                crate::SessionKeys {
1
                    nimbus: bob_id_2.clone(),
1
                },
1
                vec![]
1
            ));
1
            run_to_session(1u32);
1
            let old_key_mapping_session_1 = key_mapping_session_1;
1

            
1
            // Session 0 got removed
1
            let key_mapping_session_0 = AuthorityAssignment::collator_container_chain(0);
1
            assert!(key_mapping_session_0.is_none());
            // The values at session 1 did not change
1
            let key_mapping_session_1 = AuthorityAssignment::collator_container_chain(1).unwrap();
1
            assert_eq!(key_mapping_session_1, old_key_mapping_session_1,);
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain(),
1
                old_assignment_session_1,
1
            );
            // Session 2 uses the new keys
1
            let key_mapping_session_2 = AuthorityAssignment::collator_container_chain(2).unwrap();
1
            assert_eq!(
1
                key_mapping_session_2.orchestrator_chain,
1
                vec![alice_id_2.clone(), bob_id_2.clone()],
1
            );
1
            assert_eq!(CollatorAssignment::pending_collator_container_chain(), None);
1
            let key_mapping_session_3 = AuthorityAssignment::collator_container_chain(3);
1
            assert!(key_mapping_session_3.is_none());
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            run_to_session(2u32);
1

            
1
            // Session 1 got removed
1
            let key_mapping_session_1 = AuthorityAssignment::collator_container_chain(1);
1
            assert!(key_mapping_session_1.is_none());
            // Session 2 uses the new keys
1
            let key_mapping_session_2 = AuthorityAssignment::collator_container_chain(2).unwrap();
1
            assert_eq!(
1
                key_mapping_session_2.orchestrator_chain,
1
                vec![alice_id_2.clone(), bob_id_2.clone()],
1
            );
1
            assert_eq!(
1
                old_assignment_session_1,
1
                CollatorAssignment::collator_container_chain(),
1
            );
            // Session 3 uses the new keys
1
            let key_mapping_session_3 = AuthorityAssignment::collator_container_chain(3).unwrap();
1
            assert_eq!(
1
                key_mapping_session_3.orchestrator_chain,
1
                vec![alice_id_2.clone(), bob_id_2.clone()],
1
            );
1
            assert_eq!(CollatorAssignment::pending_collator_container_chain(), None);
1
            let key_mapping_session_4 = AuthorityAssignment::collator_container_chain(4);
1
            assert!(key_mapping_session_4.is_none());
            // Everything should match to aura
1
            assert_eq!(authorities(), vec![alice_id_2, bob_id_2]);
1
        });
1
}
2
fn call_transfer(
2
    dest: sp_runtime::MultiAddress<sp_runtime::AccountId32, ()>,
2
    value: u128,
2
) -> RuntimeCall {
2
    RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { dest, value })
2
}
#[test]
1
fn test_proxy_any() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            let delay = 0;
1
            assert_ok!(Proxy::add_proxy(
1
                origin_of(ALICE.into()),
1
                AccountId::from(BOB).into(),
1
                ProxyType::Any,
1
                delay
1
            ));
1
            let balance_before = System::account(AccountId::from(BOB)).data.free;
1
            let call = Box::new(call_transfer(AccountId::from(BOB).into(), 200_000));
1
            assert_ok!(Proxy::proxy(
1
                origin_of(BOB.into()),
1
                AccountId::from(ALICE).into(),
1
                None,
1
                call
1
            ));
1
            let balance_after = System::account(AccountId::from(BOB)).data.free;
1

            
1
            assert_eq!(balance_after, balance_before + 200_000);
1
        });
1
}
#[test]
1
fn test_proxy_non_transfer() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            let delay = 0;
1
            assert_ok!(Proxy::add_proxy(
1
                origin_of(ALICE.into()),
1
                AccountId::from(BOB).into(),
1
                ProxyType::NonTransfer,
1
                delay
1
            ));
1
            let balance_before = System::account(AccountId::from(BOB)).data.free;
1
            let call = Box::new(call_transfer(AccountId::from(BOB).into(), 200_000));
1
            // The extrinsic succeeds but the call is filtered, so no transfer is actually done
1
            assert_ok!(Proxy::proxy(
1
                origin_of(BOB.into()),
1
                AccountId::from(ALICE).into(),
1
                None,
1
                call
1
            ));
1
            let balance_after = System::account(AccountId::from(BOB)).data.free;
1

            
1
            assert_eq!(balance_after, balance_before);
1
        });
1
}
#[test]
1
fn test_proxy_utility() {
1
    // All proxy types should be able to use Utility pallet, but we ensure
1
    // subcalls don't allow to circumvent filters.
1

            
1
    // Dummy match to ensure we update this test when adding new proxy types.
1
    match ProxyType::Any {
        ProxyType::Any
        | ProxyType::NonTransfer
        | ProxyType::Governance
        | ProxyType::Staking
        | ProxyType::CancelProxy
        | ProxyType::Balances
        | ProxyType::Registrar
1
        | ProxyType::SudoRegistrar => (),
1
    };
1

            
1
    // All except for any
1
    let proxy_types = &[
1
        ProxyType::NonTransfer,
1
        ProxyType::Governance,
1
        ProxyType::Staking,
1
        ProxyType::CancelProxy,
1
        ProxyType::Balances,
1
        ProxyType::Registrar,
1
        ProxyType::SudoRegistrar,
1
    ];
8
    for &proxy_type in proxy_types {
7
        ExtBuilder::default()
7
            .with_balances(vec![
7
                // Alice gets 10k extra tokens for her mapping deposit
7
                (AccountId::from(ALICE), 210_000 * UNIT),
7
                (AccountId::from(BOB), 100_000 * UNIT),
7
                (AccountId::from(CHARLIE), 100_000 * UNIT),
7
                (AccountId::from(DAVE), 100_000 * UNIT),
7
            ])
7
            .with_sudo(AccountId::from(ALICE))
7
            .build()
7
            .execute_with(|| {
7
                assert_ok!(Proxy::add_proxy(
7
                    origin_of(ALICE.into()),
7
                    AccountId::from(BOB).into(),
7
                    proxy_type,
7
                    0
7
                ));
7
                let free_balance = Balances::free_balance(AccountId::from(BOB));
7

            
7
                assert_ok!(Proxy::proxy(
7
                    origin_of(BOB.into()),
7
                    AccountId::from(ALICE).into(),
7
                    None,
7
                    Box::new(
7
                        pallet_sudo::Call::sudo {
7
                            call: Box::new(
7
                                pallet_utility::Call::batch {
7
                                    calls: vec![pallet_balances::Call::force_set_balance {
7
                                        who: AccountId::from(BOB).into(),
7
                                        new_free: 42424242424242
7
                                    }
7
                                    .into()]
7
                                }
7
                                .into()
7
                            )
7
                        }
7
                        .into()
7
                    )
7
                ));
7
                assert_eq!(Balances::free_balance(AccountId::from(BOB)), free_balance);
7
            });
7
    }
1
}
#[test]
1
fn check_well_known_keys() {
    use frame_support::traits::PalletInfo;
    // Pallet is named "Paras" in Polkadot.
1
    assert_eq!(
1
        well_known_keys::PARAS_HEADS_INDEX,
1
        frame_support::storage::storage_prefix(b"Paras", b"Heads")
1
    );
    // Tanssi storage. Since we cannot access the storages themselves,
    // we test the pallet prefix matches and then compute manually the full prefix.
1
    assert_eq!(
1
        crate::PalletInfo::name::<AuthorityAssignment>(),
1
        Some("AuthorityAssignment")
1
    );
1
    assert_eq!(
1
        well_known_keys::AUTHORITY_ASSIGNMENT_PREFIX,
1
        frame_support::storage::storage_prefix(b"AuthorityAssignment", b"CollatorContainerChain")
1
    );
1
    assert_eq!(crate::PalletInfo::name::<Session>(), Some("Session"));
1
    assert_eq!(
1
        well_known_keys::SESSION_INDEX,
1
        frame_support::storage::storage_prefix(b"Session", b"CurrentIndex")
1
    );
1
}
#[test]
1
fn test_reward_to_invulnerable() {
1
    // Alice, Bob, Charlie are invulnerables
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            // We make delegations to ALICE so that she is an elligible candidate.
1
            // However since she is an invulnerable she should get all the
1
            // rewards.
1

            
1
            // wait for next session so that ALICE is elected
1
            run_to_session(4u32);
1

            
1
            let account: AccountId = ALICE.into();
1
            let balance_before = System::account(account.clone()).data.free;
1

            
1
            let summary = (0..100)
2
                .find_map(|_| {
2
                    let summary = run_block();
2
                    if summary.author_id == ALICE.into() {
1
                        Some(summary)
                    } else {
1
                        None
                    }
2
                })
1
                .unwrap_or_else(|| panic!("ALICE doesn't seem to author any blocks"));
1

            
1
            let balance_after = System::account(account).data.free;
1

            
1
            let all_rewards = RewardsPortion::get() * summary.inflation;
1
            // rewards are shared between orchestrator and registered paras
1
            let orchestrator_rewards = all_rewards / 3;
1
            assert_eq!(
1
                orchestrator_rewards,
1
                balance_after - balance_before,
                "alice should get the correct reward portion"
            );
1
        });
1
}
#[test]
1
fn test_reward_to_invulnerable_with_key_change() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![(AccountId::from(ALICE), 210 * UNIT)])
1
        .with_empty_parachains(vec![1001, 1002])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            run_to_session(2u32);
1

            
1
            // change key, this should be reflected 2 sessions afterward
1
            let alice_new_key = get_aura_id_from_seed(&AccountId::from(DAVE).to_string());
1
            assert_ok!(Session::set_keys(
1
                origin_of(ALICE.into()),
1
                crate::SessionKeys {
1
                    nimbus: alice_new_key,
1
                },
1
                vec![]
1
            ));
1
            run_to_session(4u32);
1

            
1
            let account: AccountId = ALICE.into();
1
            let balance_before = System::account(account.clone()).data.free;
1

            
1
            let summary = run_block();
1
            assert_eq!(summary.author_id, ALICE.into());
1
            let balance_after = System::account(account).data.free;
1

            
1
            let all_rewards = RewardsPortion::get() * summary.inflation;
1
            // rewards are shared between orchestrator and registered paras
1
            let orchestrator_rewards = all_rewards / 3;
1
            assert_eq!(
1
                orchestrator_rewards,
1
                balance_after - balance_before,
                "alice should get the correct reward portion"
            );
1
        });
1
}
#[test]
1
fn test_can_buy_credits_before_registering_para() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            // Try to buy the maximum amount of credits
1
            let balance_before = System::account(AccountId::from(ALICE)).data.free;
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                block_credits_to_required_balance(u32::MAX, 1001.into())
1
            ));
1
            let balance_after = System::account(AccountId::from(ALICE)).data.free;
1

            
1
            // Now parachain tank should have this amount
1
            let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into()))
1
                .data
1
                .free;
1

            
1
            assert_eq!(
1
                balance_tank,
1
                block_credits_to_required_balance(u32::MAX, 1001.into())
1
            );
1
            let expected_cost = block_credits_to_required_balance(u32::MAX, 1001.into());
1
            assert_eq!(balance_before - balance_after, expected_cost);
1
        });
1
}
#[test]
1
fn test_cannot_mark_valid_para_with_no_bootnodes() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            assert_noop!(
1
                Registrar::mark_valid_for_collating(root_origin(), 1001.into()),
1
                pallet_data_preservers::Error::<Runtime>::NoBootNodes,
1
            );
1
        });
1
}
#[test]
1
fn test_can_buy_credits_before_registering_para_and_receive_free_credits() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            // Try to buy (FreeBlockProductionCredits - 1) credits
1
            let balance_before = System::account(AccountId::from(ALICE)).data.free;
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                block_credits_to_required_balance(
1
                    crate::FreeBlockProductionCredits::get() - 1,
1
                    1001.into()
1
                )
1
            ));
1
            let balance_after = System::account(AccountId::from(ALICE)).data.free;
1

            
1
            // Now parachain tank should have this amount
1
            let balance_tank = System::account(ServicesPayment::parachain_tank(1001.into()))
1
                .data
1
                .free;
1

            
1
            assert_eq!(
1
                balance_tank,
1
                block_credits_to_required_balance(
1
                    crate::FreeBlockProductionCredits::get() - 1,
1
                    1001.into()
1
                )
1
            );
1
            let expected_cost = block_credits_to_required_balance(
1
                crate::FreeBlockProductionCredits::get() - 1,
1
                1001.into(),
1
            );
1
            assert_eq!(balance_before - balance_after, expected_cost);
            // Now register para
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // We received aññ free credits, because we cannot have more than FreeBlockProductionCredits
1
            let credits =
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
1
                    .unwrap_or_default();
1
            assert_eq!(credits, crate::FreeBlockProductionCredits::get());
1
        });
1
}
#[test]
1
fn test_deregister_and_register_again_does_not_give_free_credits() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            // Register
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ),);
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ),);
            // We received free credits
1
            let credits =
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
1
                    .unwrap_or_default();
1
            assert_eq!(credits, crate::FreeBlockProductionCredits::get());
            // Deregister after 1 session
1
            run_to_session(1);
1
            assert_ok!(Registrar::deregister(root_origin(), 1001.into()), ());
1
            run_to_session(3);
1
            let credits_before_2nd_register =
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
1
                    .unwrap_or_default();
1
            // We spent some credits because this container chain had collators for 1 session
1
            assert_ne!(
1
                credits_before_2nd_register,
1
                crate::FreeBlockProductionCredits::get()
1
            );
            // Register again
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ),);
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ),);
            // No more free credits
1
            let credits =
1
                pallet_services_payment::BlockProductionCredits::<Runtime>::get(ParaId::from(1001))
1
                    .unwrap_or_default();
1
            assert_eq!(credits, credits_before_2nd_register);
1
        });
1
}
#[test]
1
fn test_register_parathread_not_allowed() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            assert_noop!(
1
                RuntimeCall::Registrar(pallet_registrar::Call::<Runtime>::register_parathread {
1
                    para_id: 3001.into(),
1
                    slot_frequency: SlotFrequency { min: 1, max: 1 },
1
                    genesis_data: empty_genesis_data(),
1
                    head_data: None
1
                })
1
                .dispatch(
1
                    <Runtime as frame_system::Config>::RuntimeOrigin::signed(AccountId::from(
1
                        ALICE
1
                    ))
1
                ),
1
                frame_system::Error::<Runtime>::CallFiltered
1
            );
1
        });
1
}
#[test]
1
fn test_register_parathread_genesis() {
1
    let parathread_params = tp_traits::ParathreadParams {
1
        slot_frequency: SlotFrequency { min: 1, max: 1 },
1
    };
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_para_ids(vec![ParaRegistrationParams {
1
            para_id: 3001,
1
            genesis_data: empty_genesis_data(),
1
            block_production_credits: u32::MAX,
1
            collator_assignment_credits: u32::MAX,
1
            parathread_params: Some(parathread_params.clone()),
1
        }])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            assert_eq!(Registrar::registered_para_ids(), vec![3001.into()]);
1
            assert_eq!(
1
                pallet_registrar::ParathreadParams::<Runtime>::get(ParaId::from(3001)),
1
                Some(parathread_params)
1
            );
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&ParaId::from(3001)],
1
                vec![CHARLIE.into()]
1
            );
1
        });
1
}
#[test]
1
fn test_ed_plus_block_credit_session_purchase_works() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            let credits_1001 = block_credits_to_required_balance(crate::Period::get(), 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // Simulate block inclusion from container chain 1001
1
            let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: 1001.into(),
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1

            
1
            sproof.items.push(s);
1
            set_author_noting_inherent_data(sproof);
1

            
1
            run_block();
1

            
1
            // After this it should not be assigned anymore, since credits are not payable
1
            run_to_session(3u32);
1
            // Nobody should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_ed_plus_block_credit_session_minus_1_purchase_fails() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            let credits_1001 = block_credits_to_required_balance(crate::Period::get(), 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT
1
                - 1;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should not be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_reassignment_ed_plus_two_block_credit_session_purchase_works() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
            // On reassignment the blocks credits needed should be enough for the current session and the next one
1
            let credits_1001 =
1
                block_credits_to_required_balance(crate::Period::get() * 2, 1001.into())
1
                    + crate::EXISTENTIAL_DEPOSIT;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // Simulate block inclusion from container chain 1001
1
            let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: 1001.into(),
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1

            
1
            sproof.items.push(s);
1
            set_author_noting_inherent_data(sproof);
1

            
1
            run_block();
1

            
1
            // Session 3 should still be assigned
1
            run_to_session(3u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // After this it should not be assigned anymore, since credits are not payable
1
            run_to_session(4u32);
1
            // Nobody should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_reassignment_ed_plus_two_block_credit_session_minus_1_purchase_fails() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            let credits_1001 =
1
                block_credits_to_required_balance(crate::Period::get() * 2, 1001.into())
1
                    + crate::EXISTENTIAL_DEPOSIT
1
                    - 1;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // Simulate block inclusion from container chain 1001
1
            let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: 1001.into(),
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1

            
1
            sproof.items.push(s);
1
            set_author_noting_inherent_data(sproof);
1

            
1
            run_block();
1

            
1
            // After this it should not be assigned anymore, since credits are not payable
1
            run_to_session(3u32);
1
            // Nobody should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_credits_with_purchase_can_be_combined() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Set 1 session of free credits and purchase 1 session of credits
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                crate::Period::get()
1
            ));
1
            let credits_1001 = block_credits_to_required_balance(crate::Period::get(), 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
1
        });
1
}
#[test]
1
fn stream_payment_works() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 100_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
            use pallet_stream_payment::{ChangeKind, StreamConfig};
1
            assert_ok!(StreamPayment::open_stream(
1
                origin_of(ALICE.into()),
1
                BOB.into(),
1
                StreamConfig {
1
                    rate: 2 * UNIT,
1
                    asset_id: StreamPaymentAssetId::Native,
1
                    time_unit: TimeUnit::BlockNumber,
1
                },
1
                1_000 * UNIT,
1
            ));
1
            run_block();
1

            
1
            assert_ok!(StreamPayment::perform_payment(origin_of(CHARLIE.into()), 0));
1
            assert_eq!(
1
                Balances::free_balance(AccountId::from(BOB)),
1
                100_000 * UNIT + 2 * UNIT
1
            );
1
            assert_ok!(StreamPayment::request_change(
1
                origin_of(ALICE.into()),
1
                0,
1
                ChangeKind::Suggestion,
1
                StreamConfig {
1
                    rate: 1 * UNIT,
1
                    asset_id: StreamPaymentAssetId::Native,
1
                    time_unit: TimeUnit::BlockNumber,
1
                },
1
                None,
1
            ));
1
            assert_ok!(StreamPayment::accept_requested_change(
1
                origin_of(BOB.into()),
1
                0,
1
                1, // nonce
1
                None,
1
            ));
1
            run_block();
1

            
1
            assert_ok!(StreamPayment::close_stream(origin_of(BOB.into()), 0));
1
            assert_eq!(
1
                Balances::free_balance(AccountId::from(BOB)),
1
                100_000 * UNIT + 3 * UNIT
1
            );
1
            assert_eq!(
1
                Balances::free_balance(AccountId::from(ALICE)),
1
                100_000 * UNIT - 3 * UNIT
1
            );
1
        });
1
}
#[test]
1
fn test_ed_plus_collator_assignment_session_purchase_works() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            let credits_1001 = collator_assignment_credits_to_required_balance(1, 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // Simulate block inclusion from container chain 1001
1
            let mut sproof: ParaHeaderSproofBuilder = ParaHeaderSproofBuilder::default();
1
            let slot: u64 = 5;
1
            let s = ParaHeaderSproofBuilderItem {
1
                para_id: 1001.into(),
1
                author_id: HeaderAs::NonEncoded(sp_runtime::generic::Header::<u32, BlakeTwo256> {
1
                    parent_hash: Default::default(),
1
                    number: 1,
1
                    state_root: Default::default(),
1
                    extrinsics_root: Default::default(),
1
                    digest: sp_runtime::generic::Digest {
1
                        logs: vec![DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())],
1
                    },
1
                }),
1
            };
1
            sproof.items.push(s);
1
            set_author_noting_inherent_data(sproof);
1

            
1
            run_block();
1

            
1
            // After this it should not be assigned anymore, since credits are not payable
1
            run_to_session(4u32);
1
            // Nobody should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_ed_plus_collator_assignment_credit_session_minus_1_purchase_fails() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // Need to reset credits to 0 because now parachains are given free credits on register
1
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            let credits_1001 = collator_assignment_credits_to_required_balance(1, 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT
1
                - 1;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should not be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_collator_assignment_credits_with_purchase_can_be_combined() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // We assign one session to free credits
1
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
                root_origin(),
1
                1001.into(),
1
                1
1
            ));
            // We buy another session through the tank
1
            let credits_1001 = collator_assignment_credits_to_required_balance(1, 1001.into())
1
                + crate::EXISTENTIAL_DEPOSIT;
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                credits_1001
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
1
        });
1
}
#[test]
1
fn test_block_credits_and_collator_assignation_credits_through_tank() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1
            // Assert current slot gets updated
1
            assert_eq!(current_slot(), 1u64);
1
            assert!(current_author() == AccountId::from(BOB));
            // Alice and Bob collate in our chain
1
            let alice_id = get_aura_id_from_seed(&AccountId::from(ALICE).to_string());
1
            let bob_id = get_aura_id_from_seed(&AccountId::from(BOB).to_string());
1

            
1
            assert_eq!(authorities(), vec![alice_id, bob_id]);
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                empty_genesis_data(),
1
                None
1
            ));
1
            set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
            assert_ok!(Registrar::mark_valid_for_collating(
1
                root_origin(),
1
                1001.into()
1
            ));
            // We make all free credits 0
1
            assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
1
            assert_ok!(ServicesPayment::set_block_production_credits(
1
                root_origin(),
1
                1001.into(),
1
                0
1
            ));
            // We buy 2 sessions through tank
1
            let collator_assignation_credits =
1
                collator_assignment_credits_to_required_balance(2, 1001.into());
1
            let block_production_credits =
1
                block_credits_to_required_balance(crate::Period::get() * 2, 1001.into());
1

            
1
            // Fill the tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                1001.into(),
1
                collator_assignation_credits
1
                    + block_production_credits
1
                    + crate::EXISTENTIAL_DEPOSIT
1
            ));
            // Assignment should happen after 2 sessions
1
            run_to_session(1u32);
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert!(assignment.container_chains.is_empty());
1
            run_to_session(2u32);
1
            // Charlie and Dave should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(
1
                assignment.container_chains[&1001u32.into()],
1
                vec![CHARLIE.into(), DAVE.into()]
1
            );
            // After this it should not be assigned anymore, since credits are not payable
1
            run_to_session(4u32);
1
            // Nobody should be assigned to para 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains.get(&1001u32.into()), None,);
1
        });
1
}
#[test]
1
fn test_migration_services_collator_assignment_payment() {
1
    ExtBuilder::default().build().execute_with(|| {
1
        // Register a new parachain with no credits
1
        assert_ok!(Registrar::register(
1
            origin_of(ALICE.into()),
1
            1001.into(),
1
            empty_genesis_data(),
1
            None
1
        ));
1
        set_dummy_boot_node(origin_of(ALICE.into()), 1001.into());
1
        assert_ok!(Registrar::mark_valid_for_collating(
1
            root_origin(),
1
            1001.into()
1
        ));
        // Register another parachain with no credits, do not mark this as valid for collation
1
        assert_ok!(Registrar::register(
1
            origin_of(ALICE.into()),
1
            1002.into(),
1
            empty_genesis_data(),
1
            None
1
        ));
1
        set_dummy_boot_node(origin_of(ALICE.into()), 1002.into());
1
        assert_ok!(Registrar::mark_valid_for_collating(
1
            root_origin(),
1
            1002.into()
1
        ));
        // Need to reset credits to 0 because now parachains are given free credits on register
1
        assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
            root_origin(),
1
            1001.into(),
1
            0
1
        ));
1
        assert_ok!(ServicesPayment::set_collator_assignment_credits(
1
            root_origin(),
1
            1002.into(),
1
            0
1
        ));
1
        let credits_1001 =
1
            pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(ParaId::from(1001))
1
                .unwrap_or_default();
1
        assert_eq!(credits_1001, 0);
1
        let credits_1002 =
1
            pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(ParaId::from(1002))
1
                .unwrap_or_default();
1
        assert_eq!(credits_1002, 0);
        // Apply migration
1
        let migration =
1
            MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
1
        migration.migrate(Default::default());
1

            
1
        // Both parachains have been given credits
1
        let credits_1001 =
1
            pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(ParaId::from(1001))
1
                .unwrap_or_default();
1
        assert_eq!(credits_1001, crate::FreeCollatorAssignmentCredits::get());
1
        let credits_1002 =
1
            pallet_services_payment::CollatorAssignmentCredits::<Runtime>::get(ParaId::from(1002))
1
                .unwrap_or_default();
1
        assert_eq!(credits_1002, crate::FreeCollatorAssignmentCredits::get());
1
    });
1
}
#[test]
1
fn test_max_collators_uses_pending_value() {
1
    // Start with max_collators = 100, and collators_per_container = 2
1
    // Set max_collators = 2, and collators_per_container = 3
1
    // It should be impossible to have more than 2 collators per container at any point in time
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            // Alice gets 10k extra tokens for her mapping deposit
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001])
1
        .with_config(pallet_configuration::HostConfiguration {
1
            max_collators: 100,
1
            min_orchestrator_collators: 1,
1
            max_orchestrator_collators: 1,
1
            collators_per_container: 2,
1
            full_rotation_period: 24,
1
            ..Default::default()
1
        })
1
        .build()
1
        .execute_with(|| {
1
            run_to_block(2);
1

            
1
            // Initial assignment: 1 collator in orchestrator chain and 2 collators in container 1001
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains[&1001u32.into()].len(), 2);
1
            assert_eq!(assignment.orchestrator_chain.len(), 1);
1
            assert_ok!(Configuration::set_max_collators(root_origin(), 2));
1
            assert_ok!(Configuration::set_collators_per_container(root_origin(), 3));
            // Check invariant for all intermediate assignments. We set collators_per_container = 3
            // but we also set max_collators = 2, so no collators will be assigned to container
            // chains after the change is applied.
5
            for session in 1..=4 {
4
                run_to_session(session);
4

            
4
                let assignment = CollatorAssignment::collator_container_chain();
4
                assert!(
4
                    assignment.container_chains[&1001u32.into()].len() <= 2,
                    "session {}: {} collators assigned to container chain 1001",
                    session,
                    assignment.container_chains[&1001u32.into()].len()
                );
            }
            // Final assignment: because max_collators = 2, there are only 2 collators, one in
            // orchestrator chain, and the other one idle
1
            let assignment = CollatorAssignment::collator_container_chain();
1
            assert_eq!(assignment.container_chains[&1001u32.into()].len(), 0);
1
            assert_eq!(assignment.orchestrator_chain.len(), 1);
1
        });
1
}
#[test]
1
fn test_slow_adjusting_multiplier_changes_in_response_to_consumed_weight() {
1
    ExtBuilder::default()
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
1
            end_block();
1
            // If the block is full, the multiplier increases
1
            let before_multiplier = TransactionPayment::next_fee_multiplier();
1
            start_block();
1
            let max_block_weights = crate::RuntimeBlockWeights::get();
1
            frame_support::storage::unhashed::put(
1
                &frame_support::storage::storage_prefix(b"System", b"BlockWeight"),
3
                &ConsumedWeight::new(|class| {
3
                    max_block_weights
3
                        .get(class)
3
                        .max_total
3
                        .unwrap_or(Weight::MAX)
3
                }),
1
            );
1
            end_block();
1
            let current_multiplier = TransactionPayment::next_fee_multiplier();
1
            assert!(current_multiplier > before_multiplier);
            // If the block is empty, the multiplier decreases
1
            let before_multiplier = TransactionPayment::next_fee_multiplier();
1
            start_block();
1
            frame_support::storage::unhashed::put(
1
                &frame_support::storage::storage_prefix(b"System", b"BlockWeight"),
3
                &ConsumedWeight::new(|_class| Weight::zero()),
1
            );
1
            end_block();
1
            let current_multiplier = TransactionPayment::next_fee_multiplier();
1
            assert!(current_multiplier < before_multiplier);
1
        });
1
}
#[test]
1
fn test_collator_assignment_tip_priority_on_congestion() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002, 1003])
1
        .build()
1
        .execute_with(|| {
1
            let para_id = 1003u32;
1
            let tank_funds = 100 * UNIT;
1
            let max_tip = 1 * UNIT;
1

            
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().container_chains[&1003u32.into()]
1
                    .len(),
1
                0
1
            );
            // Send funds to tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id.into(),
1
                tank_funds,
1
            ));
            // Set tip for 1003
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id.into(),
1
                Some(max_tip),
1
            ));
1
            run_to_session(2);
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().container_chains[&para_id.into()]
1
                    .len(),
1
                2,
1
            );
1
        });
1
}
#[test]
1
fn test_collator_assignment_tip_charged_on_congestion() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002, 1003])
1
        .build()
1
        .execute_with(|| {
1
            let tank_funds = 100 * UNIT;
1
            let max_tip = 1 * UNIT;
1
            let para_id = 1003u32;
1

            
1
            // Send funds to tank
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id.into(),
1
                tank_funds,
1
            ));
            // Set tip for para_id
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id.into(),
1
                Some(max_tip),
1
            ));
1
            run_to_session(1);
1
            assert_eq!(
1
                Balances::usable_balance(ServicesPayment::parachain_tank(para_id.into())),
1
                tank_funds - max_tip,
1
            );
1
        });
1
}
#[test]
1
fn test_collator_assignment_tip_not_assigned_on_insufficient_balance() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002, 1003])
1
        .build()
1
        .execute_with(|| {
1
            let tank_funds = 1 * UNIT;
1
            let max_tip = 1 * UNIT;
1
            let para_id = 1003u32;
1

            
1
            // Send insufficient funds to tank for tip for 2 sessions
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id.into(),
1
                tank_funds,
1
            ));
            // Set tip for para_id
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id.into(),
1
                Some(max_tip),
1
            ));
1
            run_to_session(1);
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().container_chains[&para_id.into()]
1
                    .len(),
1
                0
1
            );
1
        });
1
}
#[test]
1
fn test_collator_assignment_tip_only_charge_willing_paras() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
            (AccountId::from(EVE), 100_000 * UNIT),
1
            (AccountId::from(FERDIE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
            (AccountId::from(EVE), 100 * UNIT),
1
            (AccountId::from(FERDIE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002, 1003])
1
        .build()
1
        .execute_with(|| {
1
            let tank_funds = 100 * UNIT;
1
            let max_tip = 1 * UNIT;
1
            let para_id_with_tip = 1003u32;
1
            let para_id_without_tip = 1001u32;
1

            
1
            // Send funds to tank to both paras
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id_with_tip.into(),
1
                tank_funds,
1
            ));
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id_without_tip.into(),
1
                tank_funds,
1
            ));
            // Only set tip for 1003
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id_with_tip.into(),
1
                Some(max_tip),
1
            ));
1
            run_to_session(2);
1

            
1
            let assignment = CollatorAssignment::collator_container_chain().container_chains;
1

            
1
            // 2 out of the 3 paras should have collators assigned, with one paying tip to get
1
            // prioritized, and the other selected at random that should not be charged any tips
1
            assert_eq!(assignment[&para_id_with_tip.into()].len(), 2);
1
            assert_eq!(
1
                Balances::usable_balance(ServicesPayment::parachain_tank(para_id_with_tip.into())),
1
                tank_funds - max_tip * 2,
1
            );
1
            assert_eq!(assignment[&para_id_without_tip.into()].len(), 2);
1
            assert_eq!(
1
                Balances::usable_balance(ServicesPayment::parachain_tank(
1
                    para_id_without_tip.into()
1
                )),
1
                tank_funds,
1
            );
1
        });
1
}
#[test]
1
fn test_collator_assignment_tip_withdraw_min_tip() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
1
            (AccountId::from(DAVE), 100_000 * UNIT),
1
            (AccountId::from(EVE), 100_000 * UNIT),
1
            (AccountId::from(FERDIE), 100_000 * UNIT),
1
        ])
1
        .with_collators(vec![
1
            (AccountId::from(ALICE), 210 * UNIT),
1
            (AccountId::from(BOB), 100 * UNIT),
1
            (AccountId::from(CHARLIE), 100 * UNIT),
1
            (AccountId::from(DAVE), 100 * UNIT),
1
            (AccountId::from(EVE), 100 * UNIT),
1
            (AccountId::from(FERDIE), 100 * UNIT),
1
        ])
1
        .with_empty_parachains(vec![1001, 1002, 1003])
1
        .build()
1
        .execute_with(|| {
1
            let tank_funds = 100 * UNIT;
1
            let max_tip_1003 = 3 * UNIT;
1
            let max_tip_1002 = 2 * UNIT;
1
            let para_id_1003 = 1003u32;
1
            let para_id_1002 = 1002u32;
1

            
1
            // Send funds to tank to both paras
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id_1003.into(),
1
                tank_funds,
1
            ));
1
            assert_ok!(ServicesPayment::purchase_credits(
1
                origin_of(ALICE.into()),
1
                para_id_1002.into(),
1
                tank_funds,
1
            ));
            // Set tips
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id_1003.into(),
1
                Some(max_tip_1003),
1
            ));
1
            assert_ok!(ServicesPayment::set_max_tip(
1
                root_origin(),
1
                para_id_1002.into(),
1
                Some(max_tip_1002),
1
            ));
1
            run_to_session(2);
1

            
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().container_chains
1
                    [&para_id_1003.into()]
1
                    .len(),
1
                2
1
            );
1
            assert_eq!(
1
                CollatorAssignment::collator_container_chain().container_chains
1
                    [&para_id_1002.into()]
1
                    .len(),
1
                2
1
            );
            // Should have withdrawn the lowest tip from both paras
1
            assert_eq!(
1
                Balances::usable_balance(ServicesPayment::parachain_tank(para_id_1003.into())),
1
                tank_funds - max_tip_1002 * 2,
1
            );
1
            assert_eq!(
1
                Balances::usable_balance(ServicesPayment::parachain_tank(para_id_1002.into())),
1
                tank_funds - max_tip_1002 * 2,
1
            );
1
        });
1
}
#[test]
1
fn test_migration_data_preservers_assignments() {
1
    ExtBuilder::default().build().execute_with(|| {
        use {
            crate::{MaxAssignmentsPerParaId, MaxNodeUrlLen},
            frame_support::{
                migration::{have_storage_value, put_storage_value},
                Blake2_128Concat, StorageHasher,
            },
            pallet_data_preservers::{ParaIdsFilter, Profile, ProfileMode, RegisteredProfile},
            sp_runtime::BoundedBTreeSet,
            sp_std::collections::btree_set::BTreeSet,
            tanssi_runtime_common::migrations::DataPreserversAssignmentsMigration,
        };
        macro_rules! bset {
            ( $($value:expr),* $(,)? ) => {
                {
                    let mut set = BoundedBTreeSet::new();
                    $(
                        set.try_insert($value).expect("max bound reached");
                    )*
                    set
                }
            }
        }
        macro_rules! set {
            ( $($value:expr),* $(,)? ) => {
                {
                    let mut set = BTreeSet::new();
                    $(
                        set.insert($value);
                    )*
                    set
                }
            }
        }
1
        let account = AccountId::from([0u8; 32]);
1
        let free_request = crate::PreserversAssignementPaymentRequest::Free;
1
        let free_witness = crate::PreserversAssignementPaymentWitness::Free;
1

            
1
        let pallet_prefix: &[u8] = b"DataPreservers";
1
        let storage_item_prefix: &[u8] = b"BootNodes";
1

            
1
        // Register 2 parachains
1
        assert_ok!(Registrar::register(
1
            origin_of(ALICE.into()),
1
            1001.into(),
1
            empty_genesis_data(),
1
            None
1
        ));
1
        assert_ok!(Registrar::register(
1
            origin_of(BOB.into()),
1
            1002.into(),
1
            empty_genesis_data(),
1
            None
1
        ));
        // Set bootnodes in old storage
1
        let bootnodes: BoundedVec<BoundedVec<u8, MaxNodeUrlLen>, MaxAssignmentsPerParaId> = vec![
1
            b"alpha".to_vec().try_into().unwrap(),
1
            b"beta".to_vec().try_into().unwrap(),
1
        ]
1
        .try_into()
1
        .unwrap();
1
        put_storage_value(
1
            pallet_prefix,
1
            storage_item_prefix,
1
            &Blake2_128Concat::hash(&ParaId::from(1001).encode()),
1
            bootnodes,
1
        );
1

            
1
        let bootnodes: BoundedVec<BoundedVec<u8, MaxNodeUrlLen>, MaxAssignmentsPerParaId> = vec![
1
            b"delta".to_vec().try_into().unwrap(),
1
            b"gamma".to_vec().try_into().unwrap(),
1
        ]
1
        .try_into()
1
        .unwrap();
1
        put_storage_value(
1
            pallet_prefix,
1
            storage_item_prefix,
1
            &Blake2_128Concat::hash(&ParaId::from(1002).encode()),
1
            bootnodes,
1
        );
1

            
1
        // Apply migration
1
        let migration = DataPreserversAssignmentsMigration::<Runtime>(Default::default());
1
        migration.migrate(Default::default());
1

            
1
        // Check old storage is empty
1
        assert!(!have_storage_value(
1
            pallet_prefix,
1
            storage_item_prefix,
1
            &Blake2_128Concat::hash(&ParaId::from(1001).encode())
1
        ));
1
        assert!(!have_storage_value(
1
            pallet_prefix,
1
            storage_item_prefix,
1
            &Blake2_128Concat::hash(&ParaId::from(1002).encode())
1
        ));
        // Check new storage
1
        assert_eq!(
1
            pallet_data_preservers::Assignments::<Runtime>::get(ParaId::from(1001)).into_inner(),
1
            set![0, 1]
1
        );
1
        assert_eq!(
1
            pallet_data_preservers::Assignments::<Runtime>::get(ParaId::from(1002)).into_inner(),
1
            set![2, 3]
1
        );
1
        assert_eq!(pallet_data_preservers::NextProfileId::<Runtime>::get(), 4);
1
        assert_eq!(
1
            pallet_data_preservers::Profiles::<Runtime>::get(0),
1
            Some(RegisteredProfile {
1
                account: account.clone(),
1
                deposit: 0,
1
                assignment: Some((1001.into(), free_witness)),
1
                profile: Profile {
1
                    url: b"alpha".to_vec().try_into().unwrap(),
1
                    para_ids: ParaIdsFilter::Whitelist(bset![1001.into()]),
1
                    mode: ProfileMode::Bootnode,
1
                    assignment_request: free_request,
1
                }
1
            })
1
        );
1
        assert_eq!(
1
            pallet_data_preservers::Profiles::<Runtime>::get(1),
1
            Some(RegisteredProfile {
1
                account: account.clone(),
1
                deposit: 0,
1
                assignment: Some((1001.into(), free_witness)),
1
                profile: Profile {
1
                    url: b"beta".to_vec().try_into().unwrap(),
1
                    para_ids: ParaIdsFilter::Whitelist(bset![1001.into()]),
1
                    mode: ProfileMode::Bootnode,
1
                    assignment_request: free_request,
1
                }
1
            })
1
        );
1
        assert_eq!(
1
            pallet_data_preservers::Profiles::<Runtime>::get(2),
1
            Some(RegisteredProfile {
1
                account: account.clone(),
1
                deposit: 0,
1
                assignment: Some((1002.into(), free_witness)),
1
                profile: Profile {
1
                    url: b"delta".to_vec().try_into().unwrap(),
1
                    para_ids: ParaIdsFilter::Whitelist(bset![1002.into()]),
1
                    mode: ProfileMode::Bootnode,
1
                    assignment_request: free_request,
1
                }
1
            })
1
        );
1
        assert_eq!(
1
            pallet_data_preservers::Profiles::<Runtime>::get(3),
1
            Some(RegisteredProfile {
1
                account: account.clone(),
1
                deposit: 0,
1
                assignment: Some((1002.into(), free_witness)),
1
                profile: Profile {
1
                    url: b"gamma".to_vec().try_into().unwrap(),
1
                    para_ids: ParaIdsFilter::Whitelist(bset![1002.into()]),
1
                    mode: ProfileMode::Bootnode,
1
                    assignment_request: free_request,
1
                }
1
            })
1
        );
1
    })
1
}
#[test]
1
fn test_migration_registrar_reserves_to_hold() {
1
    ExtBuilder::default()
1
        .with_balances(vec![(AccountId::from(DAVE), 100_000 * UNIT)])
1
        .build()
1
        .execute_with(|| {
            use {
                frame_support::traits::{fungible::InspectHold, ReservableCurrency},
                pallet_registrar::DepositInfo,
                tanssi_runtime_common::migrations::RegistrarReserveToHoldMigration,
            };
1
            let deposit: Balance = 100 * UNIT;
1
            let account: AccountId = DAVE.into();
1

            
1
            assert_ok!(Balances::reserve(&account, deposit));
1
            pallet_registrar::RegistrarDeposit::<Runtime>::insert(
1
                ParaId::from(1001),
1
                DepositInfo {
1
                    creator: account.clone(),
1
                    deposit,
1
                },
1
            );
1
            assert_eq!(Balances::reserved_balance(&account), deposit.clone(),);
            // Apply migration
1
            let migration = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
1
            migration.migrate(Default::default());
1

            
1
            // Holds also count as reserved balance, so the total reserved amount
1
            // shouldn't change after the migration
1
            assert_eq!(Balances::reserved_balance(&account), deposit.clone(),);
1
            assert_eq!(
1
                Balances::balance_on_hold(
1
                    &pallet_registrar::HoldReason::RegistrarDeposit.into(),
1
                    &account
1
                ),
1
                deposit
1
            );
1
        })
1
}
#[test]
1
fn test_container_deregister_unassign_data_preserver() {
1
    ExtBuilder::default()
1
        .with_balances(vec![
1
            (AccountId::from(ALICE), 210_000 * UNIT),
1
            (AccountId::from(BOB), 100_000 * UNIT),
1
        ])
1
        .build()
1
        .execute_with(|| {
            use pallet_data_preservers::{
                AssignerParameterOf, ParaIdsFilter, Profile, ProfileMode, ProviderRequestOf,
            };
1
            let profile = Profile {
1
                url: b"test".to_vec().try_into().unwrap(),
1
                para_ids: ParaIdsFilter::AnyParaId,
1
                mode: ProfileMode::Bootnode,
1
                assignment_request: ProviderRequestOf::<Runtime>::Free,
1
            };
1

            
1
            let para_id = ParaId::from(1002);
1
            let profile_id = 0u64;
1

            
1
            assert_ok!(Registrar::register(
1
                origin_of(ALICE.into()),
1
                para_id,
1
                empty_genesis_data(),
1
                None
1
            ));
1
            assert_ok!(DataPreservers::create_profile(
1
                origin_of(BOB.into()),
1
                profile.clone(),
1
            ));
            // Start assignment
1
            assert_ok!(DataPreservers::start_assignment(
1
                origin_of(ALICE.into()),
1
                profile_id,
1
                para_id,
1
                AssignerParameterOf::<Runtime>::Free
1
            ));
1
            assert!(pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&0u64));
            // Deregister from Registrar
1
            assert_ok!(Registrar::deregister(root_origin(), para_id), ());
            // Check DataPreserver assignment has been cleared
1
            assert!(pallet_data_preservers::Assignments::<Runtime>::get(para_id).is_empty());
1
        });
1
}