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
// Copyright (C) Moondance Labs Ltd.
17
// This file is part of Tanssi.
18

            
19
// Tanssi is free software: you can redistribute it and/or modify
20
// it under the terms of the GNU General Public License as published by
21
// the Free Software Foundation, either version 3 of the License, or
22
// (at your option) any later version.
23

            
24
// Tanssi is distributed in the hope that it will be useful,
25
// but WITHOUT ANY WARRANTY; without even the implied warranty of
26
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27
// GNU General Public License for more details.
28

            
29
// You should have received a copy of the GNU General Public License
30
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
31

            
32
//! # Migrations
33
//!
34
//! This module acts as a registry where each migration is defined. Each migration should implement
35
//! the "Migration" trait declared in the pallet-migrations crate.
36

            
37
extern crate alloc;
38

            
39
use {
40
    alloc::{boxed::Box, collections::btree_set::BTreeSet, vec, vec::Vec},
41
    core::marker::PhantomData,
42
    cumulus_primitives_core::ParaId,
43
    frame_support::{
44
        migration::{clear_storage_prefix, move_pallet, storage_key_iter},
45
        pallet_prelude::GetStorageVersion,
46
        parameter_types,
47
        traits::{
48
            fungible::MutateHold, OnRuntimeUpgrade, PalletInfoAccess, ReservableCurrency,
49
            StorageVersion,
50
        },
51
        weights::Weight,
52
        Blake2_128Concat, BoundedVec, StoragePrefixedMap,
53
    },
54
    pallet_configuration::{weights::WeightInfo as _, HostConfiguration},
55
    pallet_foreign_asset_creator::{AssetId, AssetIdToForeignAsset, ForeignAssetToAssetId},
56
    pallet_migrations::{GetMigrations, Migration},
57
    pallet_registrar::HoldReason,
58
    sp_core::Get,
59
    sp_runtime::Perbill,
60
};
61

            
62
#[cfg(feature = "try-runtime")]
63
use {frame_support::ensure, parity_scale_codec::DecodeAll};
64

            
65
#[derive(
66
    Default,
67
    Clone,
68
    parity_scale_codec::Encode,
69
    parity_scale_codec::Decode,
70
    PartialEq,
71
    sp_core::RuntimeDebug,
72
    scale_info::TypeInfo,
73
)]
74
pub struct HostConfigurationV3 {
75
    pub max_collators: u32,
76
    pub min_orchestrator_collators: u32,
77
    pub max_orchestrator_collators: u32,
78
    pub collators_per_container: u32,
79
    pub full_rotation_period: u32,
80
    pub collators_per_parathread: u32,
81
    pub parathreads_per_collator: u32,
82
    pub target_container_chain_fullness: Perbill,
83
    pub max_parachain_cores_percentage: Option<Perbill>,
84
}
85

            
86
pub struct MigrateConfigurationAddFullRotationMode<T>(pub PhantomData<T>);
87
impl<T> Migration for MigrateConfigurationAddFullRotationMode<T>
88
where
89
    T: pallet_configuration::Config,
90
{
91
    fn friendly_name(&self) -> &str {
92
        "TM_MigrateConfigurationAddFullRotationMode"
93
    }
94

            
95
3
    fn migrate(&self, _available_weight: Weight) -> Weight {
96
3
        let default_config = HostConfiguration::default();
97
3

            
98
3
        // Modify active config
99
3
        let old_config: HostConfigurationV3 = frame_support::storage::unhashed::get(
100
3
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
101
3
        )
102
3
        .expect("configuration.activeConfig should have value");
103
3
        let new_config = HostConfiguration {
104
3
            max_collators: old_config.max_collators,
105
3
            min_orchestrator_collators: old_config.min_orchestrator_collators,
106
3
            max_orchestrator_collators: old_config.max_orchestrator_collators,
107
3
            collators_per_container: old_config.collators_per_container,
108
3
            full_rotation_period: old_config.full_rotation_period,
109
3
            collators_per_parathread: old_config.collators_per_parathread,
110
3
            parathreads_per_collator: old_config.parathreads_per_collator,
111
3
            target_container_chain_fullness: old_config.target_container_chain_fullness,
112
3
            max_parachain_cores_percentage: old_config.max_parachain_cores_percentage,
113
3
            full_rotation_mode: default_config.full_rotation_mode.clone(),
114
3
        };
115
3
        frame_support::storage::unhashed::put(
116
3
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
117
3
            &new_config,
118
3
        );
119
3

            
120
3
        // Modify pending configs, if any
121
3
        let old_pending_configs: Vec<(u32, HostConfigurationV3)> =
122
3
            frame_support::storage::unhashed::get(
123
3
                &pallet_configuration::PendingConfigs::<T>::hashed_key(),
124
3
            )
125
3
            .unwrap_or_default();
126
3
        let mut new_pending_configs: Vec<(u32, HostConfiguration)> = vec![];
127

            
128
9
        for (session_index, old_config) in old_pending_configs {
129
6
            let new_config = HostConfiguration {
130
6
                max_collators: old_config.max_collators,
131
6
                min_orchestrator_collators: old_config.min_orchestrator_collators,
132
6
                max_orchestrator_collators: old_config.max_orchestrator_collators,
133
6
                collators_per_container: old_config.collators_per_container,
134
6
                full_rotation_period: old_config.full_rotation_period,
135
6
                collators_per_parathread: old_config.collators_per_parathread,
136
6
                parathreads_per_collator: old_config.parathreads_per_collator,
137
6
                target_container_chain_fullness: old_config.target_container_chain_fullness,
138
6
                max_parachain_cores_percentage: old_config.max_parachain_cores_percentage,
139
6
                full_rotation_mode: default_config.full_rotation_mode.clone(),
140
6
            };
141
6
            new_pending_configs.push((session_index, new_config));
142
6
        }
143

            
144
3
        if !new_pending_configs.is_empty() {
145
3
            frame_support::storage::unhashed::put(
146
3
                &pallet_configuration::PendingConfigs::<T>::hashed_key(),
147
3
                &new_pending_configs,
148
3
            );
149
3
        }
150

            
151
3
        <T as pallet_configuration::Config>::WeightInfo::set_config_with_u32()
152
3
    }
153

            
154
    /// Run a standard pre-runtime test. This works the same way as in a normal runtime upgrade.
155
    #[cfg(feature = "try-runtime")]
156
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
157
        log::info!(
158
            "hashed key {:?}",
159
            pallet_configuration::ActiveConfig::<T>::hashed_key()
160
        );
161
        let old_config_bytes = frame_support::storage::unhashed::get_raw(
162
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
163
        )
164
        .unwrap();
165
        let old_config: Result<HostConfigurationV3, _> =
166
            DecodeAll::decode_all(&mut old_config_bytes.as_ref());
167
        let new_config: Result<HostConfiguration, _> =
168
            DecodeAll::decode_all(&mut old_config_bytes.as_ref());
169

            
170
        assert!(old_config.is_ok());
171
        assert!(new_config.is_err());
172

            
173
        Ok(vec![])
174
    }
175

            
176
    /// Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
177
    #[cfg(feature = "try-runtime")]
178
    fn post_upgrade(
179
        &self,
180
        _number_of_invulnerables: Vec<u8>,
181
    ) -> Result<(), sp_runtime::DispatchError> {
182
        let new_config_bytes = frame_support::storage::unhashed::get_raw(
183
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
184
        )
185
        .unwrap();
186
        let old_config: Result<HostConfigurationV3, _> =
187
            DecodeAll::decode_all(&mut new_config_bytes.as_ref());
188
        let new_config: Result<HostConfiguration, _> =
189
            DecodeAll::decode_all(&mut new_config_bytes.as_ref());
190

            
191
        assert!(old_config.is_err());
192
        assert!(new_config.is_ok());
193

            
194
        let new_config = pallet_configuration::Pallet::<T>::config();
195
        let default_config = HostConfiguration::default();
196
        assert_eq!(
197
            new_config.full_rotation_mode,
198
            default_config.full_rotation_mode
199
        );
200
        Ok(())
201
    }
202
}
203

            
204
pub struct MigrateServicesPaymentAddCollatorAssignmentCredits<T>(pub PhantomData<T>);
205
impl<T> Migration for MigrateServicesPaymentAddCollatorAssignmentCredits<T>
206
where
207
    T: pallet_services_payment::Config + pallet_registrar::Config,
208
{
209
    fn friendly_name(&self) -> &str {
210
        "TM_MigrateServicesPaymentAddCollatorAssignmentCredits"
211
    }
212

            
213
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
214
2
        // For each parachain in pallet_registrar (active, pending or pending_verification),
215
2
        // insert `MaxCreditsStored` to pallet_services_payment,
216
2
        // and mark that parachain as "given_free_credits".
217
2
        let mut para_ids = BTreeSet::new();
218
2
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
219
2
        let pending = pallet_registrar::PendingParaIds::<T>::get();
220
2

            
221
2
        let paused = pallet_registrar::Paused::<T>::get();
222
2
        para_ids.extend(active);
223
2
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
224
2
        para_ids.extend(paused);
225
2

            
226
2
        let reads = 3 + 2 * para_ids.len() as u64;
227
2
        let writes = 2 * para_ids.len() as u64;
228

            
229
6
        for para_id in para_ids {
230
4
            // 2 reads 2 writes
231
4
            pallet_services_payment::Pallet::<T>::set_free_collator_assignment_credits(
232
4
                &para_id,
233
4
                T::FreeCollatorAssignmentCredits::get(),
234
4
            );
235
4
        }
236

            
237
2
        let db_weights = T::DbWeight::get();
238
2
        db_weights.reads_writes(reads, writes)
239
2
    }
240
    /// Run a standard pre-runtime test. This works the same way as in a normal runtime upgrade.
241
    #[cfg(feature = "try-runtime")]
242
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
243
        let mut para_ids = BTreeSet::new();
244
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
245
        let pending = pallet_registrar::PendingParaIds::<T>::get();
246
        let paused = pallet_registrar::Paused::<T>::get();
247
        para_ids.extend(active);
248
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
249
        para_ids.extend(paused);
250

            
251
        for para_id in para_ids {
252
            assert!(
253
                pallet_services_payment::CollatorAssignmentCredits::<T>::get(para_id).is_none()
254
            );
255
        }
256

            
257
        Ok(vec![])
258
    }
259

            
260
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
261
    #[cfg(feature = "try-runtime")]
262
    fn post_upgrade(&self, _result: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
263
        let mut para_ids = BTreeSet::new();
264
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
265
        let pending = pallet_registrar::PendingParaIds::<T>::get();
266
        let paused = pallet_registrar::Paused::<T>::get();
267
        para_ids.extend(active);
268
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
269
        para_ids.extend(paused);
270

            
271
        for para_id in para_ids {
272
            assert_eq!(
273
                pallet_services_payment::CollatorAssignmentCredits::<T>::get(para_id),
274
                Some(T::FreeCollatorAssignmentCredits::get())
275
            );
276
        }
277

            
278
        Ok(())
279
    }
280
}
281

            
282
pub struct PolkadotXcmMigrationFixVersion<T, PolkadotXcm>(pub PhantomData<(T, PolkadotXcm)>);
283
impl<T, PolkadotXcm> Migration for PolkadotXcmMigrationFixVersion<T, PolkadotXcm>
284
where
285
    PolkadotXcm: GetStorageVersion + PalletInfoAccess,
286
    T: cumulus_pallet_xcmp_queue::Config,
287
{
288
    fn friendly_name(&self) -> &str {
289
        "MM_PolkadotXcmMigrationFixVersion"
290
    }
291

            
292
    fn migrate(&self, _available_weight: Weight) -> Weight {
293
        if <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 0 {
294
            StorageVersion::new(1).put::<PolkadotXcm>();
295
            return T::DbWeight::get().writes(1);
296
        }
297
        Weight::default()
298
    }
299

            
300
    #[cfg(feature = "try-runtime")]
301
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
302
        ensure!(
303
            <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 0,
304
            "PolkadotXcm storage version should be 0"
305
        );
306
        Ok(vec![])
307
    }
308

            
309
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
310
    #[cfg(feature = "try-runtime")]
311
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
312
        ensure!(
313
            <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 1,
314
            "PolkadotXcm storage version should be 1"
315
        );
316
        Ok(())
317
    }
318
}
319

            
320
pub struct XcmpQueueMigrationFixVersion<T, XcmpQueue>(pub PhantomData<(T, XcmpQueue)>);
321
impl<T, XcmpQueue> Migration for XcmpQueueMigrationFixVersion<T, XcmpQueue>
322
where
323
    XcmpQueue: GetStorageVersion + PalletInfoAccess,
324
    T: cumulus_pallet_xcmp_queue::Config,
325
{
326
    fn friendly_name(&self) -> &str {
327
        "MM_XcmpQueueMigrationFixVersion"
328
    }
329

            
330
    fn migrate(&self, _available_weight: Weight) -> Weight {
331
        if <XcmpQueue as GetStorageVersion>::on_chain_storage_version() == 0 {
332
            StorageVersion::new(2).put::<XcmpQueue>();
333
            return T::DbWeight::get().writes(1);
334
        }
335
        Weight::default()
336
    }
337

            
338
    #[cfg(feature = "try-runtime")]
339
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
340
        ensure!(
341
            <XcmpQueue as GetStorageVersion>::on_chain_storage_version() == 0,
342
            "XcmpQueue storage version should be 0"
343
        );
344
        Ok(vec![])
345
    }
346

            
347
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
348
    #[cfg(feature = "try-runtime")]
349
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
350
        // Greater than because the post_upgrade is run after all the migrations, so
351
        // it can be greater if the following XcmpQueue migrations are applied in the
352
        // same runtime
353
        ensure!(
354
            <XcmpQueue as GetStorageVersion>::on_chain_storage_version() >= 2,
355
            "XcmpQueue storage version should be at least 2"
356
        );
357
        Ok(())
358
    }
359
}
360

            
361
pub struct XcmpQueueMigrationV3<T>(pub PhantomData<T>);
362
impl<T> Migration for XcmpQueueMigrationV3<T>
363
where
364
    T: cumulus_pallet_xcmp_queue::Config,
365
{
366
    fn friendly_name(&self) -> &str {
367
        "MM_XcmpQueueMigrationV3"
368
    }
369

            
370
    fn migrate(&self, _available_weight: Weight) -> Weight {
371
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::on_runtime_upgrade()
372
    }
373

            
374
    // #[cfg(feature = "try-runtime")]
375
    // let mut pre_upgrade_result: Vec<u8>;
376

            
377
    #[cfg(feature = "try-runtime")]
378
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
379
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::pre_upgrade()
380
    }
381

            
382
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
383
    #[cfg(feature = "try-runtime")]
384
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
385
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::post_upgrade(state)
386
    }
387
}
388

            
389
pub struct XcmpQueueMigrationV4<T>(pub PhantomData<T>);
390
impl<T> Migration for XcmpQueueMigrationV4<T>
391
where
392
    T: cumulus_pallet_xcmp_queue::Config,
393
{
394
    fn friendly_name(&self) -> &str {
395
        "MM_XcmpQueueMigrationV4"
396
    }
397

            
398
    fn migrate(&self, _available_weight: Weight) -> Weight {
399
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::on_runtime_upgrade()
400
    }
401

            
402
    #[cfg(feature = "try-runtime")]
403
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
404
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::pre_upgrade()
405
    }
406

            
407
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
408
    #[cfg(feature = "try-runtime")]
409
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
410
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::post_upgrade(state)
411
    }
412
}
413

            
414
pub struct RegistrarPendingVerificationValueToMap<T>(pub PhantomData<T>);
415
impl<T> Migration for RegistrarPendingVerificationValueToMap<T>
416
where
417
    T: pallet_registrar::Config,
418
{
419
    fn friendly_name(&self) -> &str {
420
        "TM_RegistrarPendingVerificationValueToMap"
421
    }
422

            
423
1
    fn migrate(&self, _available_weight: Weight) -> Weight {
424
1
        let para_ids: Vec<ParaId> = frame_support::storage::unhashed::take(
425
1
            &frame_support::storage::storage_prefix(b"Registrar", b"PendingVerification"),
426
1
        )
427
1
        .unwrap_or_default();
428
1

            
429
1
        let total_weight = T::DbWeight::get()
430
1
            .reads(1)
431
1
            .saturating_add(T::DbWeight::get().writes(1));
432

            
433
5
        for para_id in para_ids {
434
4
            total_weight.saturating_add(T::DbWeight::get().writes(1));
435
4
            pallet_registrar::PendingVerification::<T>::insert(para_id, ());
436
4
        }
437

            
438
1
        total_weight
439
1
    }
440

            
441
    #[cfg(feature = "try-runtime")]
442
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
443
        Ok(vec![])
444
    }
445

            
446
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
447
    #[cfg(feature = "try-runtime")]
448
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
449
        Ok(())
450
    }
451
}
452

            
453
pub struct RegistrarParaManagerMigration<T>(pub PhantomData<T>);
454
impl<T> Migration for RegistrarParaManagerMigration<T>
455
where
456
    T: pallet_registrar::Config,
457
{
458
    fn friendly_name(&self) -> &str {
459
        "TM_RegistrarParaManagerMigration"
460
    }
461

            
462
    fn migrate(&self, _available_weight: Weight) -> Weight {
463
        let mut total_weight = Weight::default();
464
        for (para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
465
            pallet_registrar::ParaManager::<T>::insert(para_id, deposit.creator);
466
            total_weight = total_weight.saturating_add(
467
                T::DbWeight::get()
468
                    .reads(1)
469
                    .saturating_add(T::DbWeight::get().writes(1)),
470
            );
471
        }
472

            
473
        total_weight
474
    }
475

            
476
    #[cfg(feature = "try-runtime")]
477
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
478
        Ok(vec![])
479
    }
480

            
481
    #[cfg(feature = "try-runtime")]
482
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
483
        Ok(())
484
    }
485
}
486

            
487
pub struct RegistrarReserveToHoldMigration<T>(pub PhantomData<T>);
488
impl<T> Migration for RegistrarReserveToHoldMigration<T>
489
where
490
    T: pallet_registrar::Config,
491
    T: pallet_balances::Config,
492
    <T as pallet_balances::Config>::RuntimeHoldReason: From<pallet_registrar::HoldReason>,
493
    <T as pallet_balances::Config>::Balance: From<
494
        <<T as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<
495
            T::AccountId,
496
        >>::Balance,
497
    >,
498
    <T as pallet_balances::Config>::Balance: From<u128>,
499
{
500
    fn friendly_name(&self) -> &str {
501
        "TM_RegistrarReserveToHoldMigration"
502
    }
503

            
504
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
505
2
        let mut total_weight = Weight::default();
506
4
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
507
2
            pallet_balances::Pallet::<T>::unreserve(&deposit.creator, deposit.deposit.into());
508
2
            let _ = pallet_balances::Pallet::<T>::hold(
509
2
                &HoldReason::RegistrarDeposit.into(),
510
2
                &deposit.creator,
511
2
                deposit.deposit.into(),
512
2
            );
513
2
            total_weight = total_weight.saturating_add(T::DbWeight::get().reads_writes(2, 2));
514
2
        }
515

            
516
2
        total_weight
517
2
    }
518

            
519
    #[cfg(feature = "try-runtime")]
520
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
521
        use frame_support::traits::fungible::InspectHold;
522

            
523
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
524
            ensure!(
525
                pallet_balances::Pallet::<T>::reserved_balance(&deposit.creator)
526
                    >= deposit.deposit.into(),
527
                "Reserved balanced cannot be less than deposit amount"
528
            );
529

            
530
            ensure!(
531
                pallet_balances::Pallet::<T>::balance_on_hold(
532
                    &HoldReason::RegistrarDeposit.into(),
533
                    &deposit.creator
534
                ) == 0u128.into(),
535
                "Balance on hold for RegistrarDeposit should be 0"
536
            );
537
        }
538
        Ok(vec![])
539
    }
540

            
541
    #[cfg(feature = "try-runtime")]
542
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
543
        use frame_support::traits::fungible::InspectHold;
544

            
545
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
546
            ensure!(
547
                pallet_balances::Pallet::<T>::balance_on_hold(
548
                    &HoldReason::RegistrarDeposit.into(),
549
                    &deposit.creator
550
                ) >= deposit.deposit.into(),
551
                "Balance on hold for RegistrarDeposit should be deposit"
552
            );
553
        }
554

            
555
        Ok(())
556
    }
557
}
558

            
559
pub struct MigrateSnowbridgeFeePerGasMigrationV0ToV1<T>(PhantomData<T>);
560
impl<T> Migration for MigrateSnowbridgeFeePerGasMigrationV0ToV1<T>
561
where
562
    T: snowbridge_pallet_system::Config,
563
{
564
162
    fn friendly_name(&self) -> &str {
565
162
        "MM_MigrateSnowbridgeFeePerGasMigrationV0ToV1"
566
162
    }
567

            
568
    fn migrate(&self, _available_weight: Weight) -> Weight {
569
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::on_runtime_upgrade()
570
    }
571

            
572
    #[cfg(feature = "try-runtime")]
573
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
574
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::pre_upgrade()
575
    }
576

            
577
    #[cfg(feature = "try-runtime")]
578
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
579
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::post_upgrade(state)
580
    }
581
}
582

            
583
pub struct MigratePalletSessionV0toV1<T>(PhantomData<T>);
584
impl<T: frame_system::Config + pallet_session::Config> Migration for MigratePalletSessionV0toV1<T>
585
where
586
    pallet_session::migrations::v1::MigrateV0ToV1<
587
        T,
588
        pallet_session::migrations::v1::InitOffenceSeverity<T>,
589
    >: frame_support::traits::OnRuntimeUpgrade,
590
{
591
786
    fn friendly_name(&self) -> &str {
592
786
        "MM_MigratePalletSessionV0ToV1"
593
786
    }
594

            
595
    fn migrate(&self, _available_weight: Weight) -> Weight {
596
        pallet_session::migrations::v1::MigrateV0ToV1::<
597
            T,
598
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
599
        >::on_runtime_upgrade()
600
    }
601

            
602
    #[cfg(feature = "try-runtime")]
603
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
604
        pallet_session::migrations::v1::MigrateV0ToV1::<
605
            T,
606
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
607
        >::pre_upgrade()
608
    }
609

            
610
    #[cfg(feature = "try-runtime")]
611
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
612
        pallet_session::migrations::v1::MigrateV0ToV1::<
613
            T,
614
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
615
        >::post_upgrade(state)
616
    }
617
}
618
pub struct MigrateToLatestXcmVersion<Runtime>(PhantomData<Runtime>);
619
impl<Runtime> Migration for MigrateToLatestXcmVersion<Runtime>
620
where
621
    pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>:
622
        frame_support::traits::OnRuntimeUpgrade,
623
{
624
    fn friendly_name(&self) -> &str {
625
        "MM_MigrateToLatestXcmVersion5"
626
    }
627

            
628
    fn migrate(&self, _available_weight: Weight) -> Weight {
629
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::on_runtime_upgrade()
630
    }
631

            
632
    #[cfg(feature = "try-runtime")]
633
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
634
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::pre_upgrade()
635
    }
636

            
637
    #[cfg(feature = "try-runtime")]
638
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
639
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::post_upgrade(state)
640
    }
641
}
642

            
643
pub struct DataPreserversAssignmentsMigration<T>(pub PhantomData<T>);
644
impl<T> Migration for DataPreserversAssignmentsMigration<T>
645
where
646
    T: pallet_data_preservers::Config + pallet_registrar::Config,
647
    T::AccountId: From<[u8; 32]>,
648
{
649
    fn friendly_name(&self) -> &str {
650
        "TM_DataPreserversAssignmentsMigration"
651
    }
652

            
653
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
654
        use {
655
            frame_support::BoundedBTreeSet,
656
            frame_system::RawOrigin,
657
            pallet_data_preservers::{AssignmentProcessor, ParaIdsFilter, Profile, ProfileMode},
658
        };
659

            
660
2
        let mut total_weight = Weight::default();
661
2

            
662
2
        let (request, _extra, witness) = T::AssignmentProcessor::free_variant_values()
663
2
            .expect("free variant values are necessary to perform migration");
664
2

            
665
2
        let dummy_profile_owner = T::AccountId::from([0u8; 32]);
666
2

            
667
2
        let pallet_prefix: &[u8] = b"DataPreservers";
668
2
        let storage_item_prefix: &[u8] = b"BootNodes";
669
2
        let bootnodes_storage: Vec<_> = storage_key_iter::<
670
2
            ParaId,
671
2
            BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
672
2
            Blake2_128Concat,
673
2
        >(pallet_prefix, storage_item_prefix)
674
2
        .collect();
675
2

            
676
2
        total_weight = total_weight.saturating_add(
677
2
            T::DbWeight::get()
678
2
                .reads(bootnodes_storage.len() as u64)
679
2
                .saturating_add(T::DbWeight::get().writes(bootnodes_storage.len() as u64)),
680
2
        );
681

            
682
6
        for (para_id, bootnodes) in bootnodes_storage {
683
12
            for bootnode_url in bootnodes {
684
8
                let profile = Profile {
685
8
                    url: bootnode_url,
686
8
                    para_ids: ParaIdsFilter::Whitelist({
687
8
                        let mut set = BoundedBTreeSet::new();
688
8
                        set.try_insert(para_id).expect("to be in bound");
689
8
                        set
690
8
                    }),
691
8
                    mode: ProfileMode::Bootnode,
692
8
                    assignment_request: request.clone(),
693
8
                };
694
8

            
695
8
                let profile_id = pallet_data_preservers::NextProfileId::<T>::get();
696

            
697
8
                if let Some(weight) = pallet_data_preservers::Pallet::<T>::force_create_profile(
698
8
                    RawOrigin::Root.into(),
699
8
                    profile,
700
8
                    dummy_profile_owner.clone(),
701
8
                )
702
8
                .expect("to create profile")
703
8
                .actual_weight
704
                {
705
                    total_weight = total_weight.saturating_add(weight);
706
8
                }
707

            
708
8
                if let Some(weight) = pallet_data_preservers::Pallet::<T>::force_start_assignment(
709
8
                    RawOrigin::Root.into(),
710
8
                    profile_id,
711
8
                    para_id,
712
8
                    witness.clone(),
713
8
                )
714
8
                .expect("to start assignment")
715
8
                .actual_weight
716
                {
717
                    total_weight = total_weight.saturating_add(weight);
718
8
                }
719
            }
720
        }
721

            
722
2
        let _ = clear_storage_prefix(pallet_prefix, storage_item_prefix, &[], None, None);
723
2

            
724
2
        total_weight
725
2
    }
726

            
727
    #[cfg(feature = "try-runtime")]
728
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
729
        use parity_scale_codec::Encode;
730

            
731
        let pallet_prefix: &[u8] = b"DataPreservers";
732
        let storage_item_prefix: &[u8] = b"BootNodes";
733
        let state: Vec<_> = storage_key_iter::<
734
            ParaId,
735
            BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
736
            Blake2_128Concat,
737
        >(pallet_prefix, storage_item_prefix)
738
        .collect();
739

            
740
        Ok(state.encode())
741
    }
742

            
743
    #[cfg(feature = "try-runtime")]
744
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
745
        use parity_scale_codec::Decode;
746

            
747
        let pallet_prefix: &[u8] = b"DataPreservers";
748
        let storage_item_prefix: &[u8] = b"BootNodes";
749

            
750
        let pre_state: Vec<(ParaId, Vec<Vec<u8>>)> =
751
            Decode::decode(&mut &state[..]).expect("state to be decoded properly");
752

            
753
        for (para_id, bootnodes) in pre_state {
754
            let assignments = pallet_data_preservers::Assignments::<T>::get(para_id);
755
            assert_eq!(assignments.len(), bootnodes.len());
756

            
757
            let profiles: Vec<_> =
758
                pallet_data_preservers::Pallet::<T>::assignments_profiles(para_id).collect();
759

            
760
            for bootnode in bootnodes {
761
                assert_eq!(
762
                    profiles
763
                        .iter()
764
                        .filter(|profile| profile.url == bootnode)
765
                        .count(),
766
                    1
767
                );
768
            }
769
        }
770

            
771
        assert_eq!(
772
            storage_key_iter::<
773
                ParaId,
774
                BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
775
                Blake2_128Concat,
776
            >(pallet_prefix, storage_item_prefix)
777
            .count(),
778
            0
779
        );
780

            
781
        Ok(())
782
    }
783
}
784

            
785
pub struct ForeignAssetCreatorMigration<Runtime>(pub PhantomData<Runtime>);
786

            
787
impl<Runtime> Migration for ForeignAssetCreatorMigration<Runtime>
788
where
789
    Runtime: pallet_foreign_asset_creator::Config,
790
    <Runtime as pallet_foreign_asset_creator::Config>::ForeignAsset:
791
        TryFrom<xcm::v3::MultiLocation>,
792
{
793
    fn friendly_name(&self) -> &str {
794
        "TM_ForeignAssetCreatorMigration"
795
    }
796

            
797
    fn migrate(&self, _available_weight: Weight) -> Weight {
798
        use frame_support::pallet_prelude::*;
799

            
800
        use xcm::v3::MultiLocation as OldLocation;
801

            
802
        let pallet_prefix = AssetIdToForeignAsset::<Runtime>::pallet_prefix();
803
        let asset_id_to_foreign_asset_storage_prefix =
804
            AssetIdToForeignAsset::<Runtime>::storage_prefix();
805
        let foreign_asset_to_asset_id_prefix = ForeignAssetToAssetId::<Runtime>::storage_prefix();
806

            
807
        // Data required to migrate ForeignAsset values
808
        // Read all the data into memory.
809
        let asset_id_to_foreign_asset_data: Vec<_> =
810
            storage_key_iter::<AssetId<Runtime>, OldLocation, Blake2_128Concat>(
811
                pallet_prefix,
812
                asset_id_to_foreign_asset_storage_prefix,
813
            )
814
            .drain()
815
            .collect();
816

            
817
        // Data required to migrate ForeignAsset keys
818
        let foreign_asset_to_asset_id_data: Vec<_> =
819
            storage_key_iter::<OldLocation, AssetId<Runtime>, Blake2_128Concat>(
820
                pallet_prefix,
821
                foreign_asset_to_asset_id_prefix,
822
            )
823
            .drain()
824
            .collect();
825

            
826
        let migrated_count = asset_id_to_foreign_asset_data
827
            .len()
828
            .saturating_add(foreign_asset_to_asset_id_data.len());
829

            
830
        log::info!("Migrating {:?} elements", migrated_count);
831

            
832
        // Write to the new storage with removed and added fields
833
        for (asset_id, old_location) in asset_id_to_foreign_asset_data {
834
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
835
                AssetIdToForeignAsset::<Runtime>::insert(asset_id, new_location);
836
            } else {
837
                log::warn!("Location could not be converted safely to xcmV4")
838
            }
839
        }
840

            
841
        for (old_location, asset_id) in foreign_asset_to_asset_id_data {
842
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
843
                ForeignAssetToAssetId::<Runtime>::insert(new_location, asset_id);
844
            } else {
845
                log::warn!("Location could not be converted safely to xcmV4")
846
            }
847
        }
848

            
849
        // One db read and one db write per element, plus the on-chain storage
850
        Runtime::DbWeight::get().reads_writes(migrated_count as u64, 2 * migrated_count as u64)
851
    }
852

            
853
    #[cfg(feature = "try-runtime")]
854
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
855
        Ok(vec![])
856
    }
857

            
858
    #[cfg(feature = "try-runtime")]
859
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
860
        Ok(())
861
    }
862
}
863

            
864
pub struct MigrateMMRLeafPallet<T>(pub PhantomData<T>);
865

            
866
impl<T: frame_system::Config> Migration for MigrateMMRLeafPallet<T> {
867
    fn friendly_name(&self) -> &str {
868
        "SM_MigrateMMRLeafPallet"
869
    }
870

            
871
2
    fn migrate(&self, available_weight: Weight) -> Weight {
872
2
        let new_name =
873
2
            <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<
874
2
                pallet_beefy_mmr::Pallet<T>,
875
2
            >()
876
2
            .expect("pallet_beefy_mmr must be part of dancelight before this migration");
877
2
        move_pallet(Self::old_pallet_name().as_bytes(), new_name.as_bytes());
878
2
        available_weight
879
2
    }
880

            
881
    #[cfg(feature = "try-runtime")]
882
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
883
        Ok(vec![])
884
    }
885

            
886
    #[cfg(feature = "try-runtime")]
887
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
888
        Ok(())
889
    }
890
}
891

            
892
impl<T> MigrateMMRLeafPallet<T> {
893
4
    pub fn old_pallet_name() -> &'static str {
894
4
        "MMRLeaf"
895
4
    }
896
}
897

            
898
pub mod snowbridge_system_migration {
899
    use super::*;
900
    use alloc::vec::Vec;
901
    use frame_support::pallet_prelude::*;
902
    use snowbridge_core::TokenId;
903
    use xcm::{
904
        self,
905
        v5::NetworkId::ByGenesis,
906
        v5::{Junction::GlobalConsensus, ROCOCO_GENESIS_HASH},
907
    };
908

            
909
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
910
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
911

            
912
    pub const TANSSI_GENESIS_HASH: [u8; 32] =
913
        hex_literal::hex!["dd6d086f75ec041b66e20c4186d327b23c8af244c534a2418de6574e8c041a60"];
914

            
915
    parameter_types! {
916
        pub DancelightLocation: xcm::v5::Location = xcm::v5::Location::new(
917
            1,
918
            [GlobalConsensus(ByGenesis(DANCELIGHT_GENESIS_HASH))],
919
        );
920
        pub StarlightLocation: xcm::v5::Location = xcm::v5::Location::new(
921
            1,
922
            [GlobalConsensus(ByGenesis(TANSSI_GENESIS_HASH))],
923
        );
924
    }
925

            
926
    // Important: this cannot be called OldNativeToForeignId because that will be a different storage
927
    // item. Polkadot has a bug here.
928
8
    #[frame_support::storage_alias]
929
    pub type NativeToForeignId<T: snowbridge_pallet_system::Config> = StorageMap<
930
        snowbridge_pallet_system::Pallet<T>,
931
        Blake2_128Concat,
932
        xcm::v5::Location,
933
        TokenId,
934
        OptionQuery,
935
    >;
936

            
937
    /// One shot migration to change the genesis hash of NetworkId::ByGenesis()
938
    pub struct MigrationForGenesisHashes<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>(
939
        core::marker::PhantomData<(T, L)>,
940
    );
941
    impl<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>
942
        frame_support::traits::OnRuntimeUpgrade for MigrationForGenesisHashes<T, L>
943
    {
944
2
        fn on_runtime_upgrade() -> Weight {
945
2
            let mut weight = T::DbWeight::get().reads(1);
946
2
            let mut len_map1 = 0;
947
2
            let mut len_map2 = 0;
948
2

            
949
2
            let translate_genesis_hashes = |pre: xcm::v5::Location| -> Option<xcm::v5::Location> {
950
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
951
2
                len_map1 += 1;
952
2
                let new_location: Option<xcm::v5::Location> = match pre.unpack() {
953
2
                    (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
954
                    _ => None,
955
                };
956
2
                Some(new_location.expect("valid location"))
957
2
            };
958
2
            snowbridge_pallet_system::ForeignToNativeId::<T>::translate_values(
959
2
                translate_genesis_hashes,
960
2
            );
961
2

            
962
2
            let old_keys = NativeToForeignId::<T>::iter_keys().collect::<Vec<_>>();
963

            
964
4
            for old_key in old_keys {
965
2
                if let Some(old_val) = NativeToForeignId::<T>::get(&old_key) {
966
2
                    let new_location: Option<xcm::v5::Location> = match old_key.unpack() {
967
2
                        (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
968
                        _ => None,
969
                    };
970
2
                    snowbridge_pallet_system::NativeToForeignId::<T>::insert(
971
2
                        new_location.expect("valid location"),
972
2
                        old_val,
973
2
                    );
974
                }
975
2
                NativeToForeignId::<T>::remove(old_key);
976
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
977
2
                len_map2 += 1;
978
            }
979

            
980
            // Additional sanity check that both mappings have the same number of elements
981
2
            assert_eq!(len_map1, len_map2);
982

            
983
2
            weight
984
2
        }
985
    }
986
}
987

            
988
pub struct MigrateEthSystemGenesisHashes<Runtime, Location>(pub PhantomData<(Runtime, Location)>);
989

            
990
impl<Runtime, Location> Migration for MigrateEthSystemGenesisHashes<Runtime, Location>
991
where
992
    Runtime: snowbridge_pallet_system::Config,
993
    Location: Get<xcm::v5::Location>,
994
{
995
162
    fn friendly_name(&self) -> &str {
996
162
        "TM_MigrateEthSystemGenesisHashes"
997
162
    }
998

            
999
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
2
        snowbridge_system_migration::MigrationForGenesisHashes::<Runtime, Location>::on_runtime_upgrade()
2
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        Ok(vec![])
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        Ok(())
    }
}
pub struct MigrateParaSchedulerToV3<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateParaSchedulerToV3<Runtime>
where
    Runtime: runtime_parachains::scheduler::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateParaSchedulerToV3"
    }
    fn migrate(&self, _available_weight: Weight) -> Weight {
        runtime_parachains::scheduler::migration::MigrateV2ToV3::<Runtime>::on_runtime_upgrade()
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        Ok(vec![])
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        Ok(())
    }
}
pub struct MigrateParaSharedToV1<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateParaSharedToV1<Runtime>
where
    Runtime: runtime_parachains::shared::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateParaSharedToV1"
    }
    fn migrate(&self, _available_weight: Weight) -> Weight {
        runtime_parachains::shared::migration::MigrateToV1::<Runtime>::on_runtime_upgrade()
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        Ok(vec![])
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        Ok(())
    }
}
pub struct MigrateStreamPaymentNewConfigFields<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateStreamPaymentNewConfigFields<Runtime>
where
    Runtime: pallet_stream_payment::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateStreamPaymentNewConfigFields"
    }
2
    fn migrate(&self, available_weight: Weight) -> Weight {
2
        pallet_stream_payment::migrations::migrate_stream_payment_new_config_fields::<Runtime>(
2
            available_weight,
2
        )
2
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        use pallet_stream_payment::migrations::OldStreamOf;
        use parity_scale_codec::Encode;
        let Some(stream_id) = pallet_stream_payment::Streams::<Runtime>::iter_keys().next() else {
            return Ok(vec![]);
        };
        let old_stream: OldStreamOf<Runtime> = frame_support::storage::unhashed::get(
            &pallet_stream_payment::Streams::<Runtime>::hashed_key_for(stream_id),
        )
        .expect("key was found so entry must exist");
        Ok((stream_id, old_stream).encode())
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        use pallet_stream_payment::{migrations::OldStreamOf, ChangeRequest, Stream, StreamConfig};
        use parity_scale_codec::Decode;
        if state.is_empty() {
            // there were no streams
            return Ok(());
        }
        let (stream_id, old_stream) =
            <(Runtime::StreamId, OldStreamOf<Runtime>)>::decode(&mut &state[..])
                .expect("to decode properly");
        let new_stream = pallet_stream_payment::Streams::<Runtime>::get(stream_id)
            .expect("entry should still exist");
        let mut expected = Stream {
            source: old_stream.source,
            target: old_stream.target,
            deposit: old_stream.deposit,
            last_time_updated: old_stream.last_time_updated,
            request_nonce: old_stream.request_nonce,
            pending_request: None, // will be replaced below
            opening_deposit: old_stream.opening_deposit,
            config: StreamConfig {
                time_unit: old_stream.config.time_unit,
                asset_id: old_stream.config.asset_id,
                rate: old_stream.config.rate,
                minimum_request_deadline_delay: 0u32.into(),
                soft_minimum_deposit: 0u32.into(),
            },
        };
        if let Some(pending_request) = old_stream.pending_request {
            expected.pending_request = Some(ChangeRequest {
                requester: pending_request.requester,
                kind: pending_request.kind,
                deposit_change: pending_request.deposit_change,
                new_config: StreamConfig {
                    time_unit: pending_request.new_config.time_unit,
                    asset_id: pending_request.new_config.asset_id,
                    rate: pending_request.new_config.rate,
                    minimum_request_deadline_delay: 0u32.into(),
                    soft_minimum_deposit: 0u32.into(),
                },
            });
        }
        assert_eq!(
            new_stream, expected,
            "Migrated stream don't match expected value"
        );
        Ok(())
    }
}
pub struct FlashboxMigrations<Runtime>(PhantomData<Runtime>);
impl<Runtime> GetMigrations for FlashboxMigrations<Runtime>
where
    Runtime: pallet_balances::Config,
    Runtime: pallet_configuration::Config,
    Runtime: pallet_registrar::Config,
    Runtime: pallet_session::Config,
    Runtime: pallet_services_payment::Config,
    Runtime: pallet_data_preservers::Config,
    Runtime: pallet_stream_payment::Config,
    Runtime::AccountId: From<[u8; 32]>,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason: From<pallet_registrar::HoldReason>,
    <Runtime as pallet_balances::Config>::Balance: From<<<Runtime as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<Runtime::AccountId>>::Balance>,
    <Runtime as pallet_balances::Config>::Balance: From<u128>,
{
1
    fn get_migrations() -> Vec<Box<dyn Migration>> {
1
        //let migrate_services_payment =
1
        //    MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
1
        //let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
1
        //let migrate_config_parathread_params =
1
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
1

            
1
        //let migrate_add_collator_assignment_credits =
1
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
1
        //let migrate_registrar_pending_verification =
1
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
1
        //let migrate_registrar_manager =
1
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
1
        //let migrate_data_preservers_assignments =
1
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
1
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
1
        //let migrate_config_max_parachain_percentage = MigrateConfigurationAddParachainPercentage::<Runtime>(Default::default());
1
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
1
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
1
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
1

            
1
        vec![
1
            // Applied in runtime 400
1
            //Box::new(migrate_services_payment),
1
            // Applied in runtime 400
1
            //Box::new(migrate_boot_nodes),
1
            // Applied in runtime 400
1
            //Box::new(migrate_config_parathread_params),
1
            // Applied in runtime 500
1
            //Box::new(migrate_add_collator_assignment_credits),
1
            // Applied in runtime 700
1
            //Box::new(migrate_registrar_pending_verification),
1
            // Applied in runtime 700
1
            //Box::new(migrate_registrar_manager),
1
            // Applied in runtime 700
1
            //Box::new(migrate_data_preservers_assignments),
1
            // Applied in runtime 800
1
            //Box::new(migrate_registrar_reserves),
1
            // Applied in runtime 900
1
            //Box::new(migrate_config_max_parachain_percentage),
1
            // Applied in runtime 1100
1
            //Box::new(migrate_config_full_rotation_mode),
1
            // Applied in runtime 1200
1
            //Box::new(migrate_stream_payment_new_config_items),
1
            Box::new(migrate_pallet_session_v0_to_v1),
1
        ]
1
    }
}
pub struct DanceboxMigrations<Runtime>(PhantomData<Runtime>);
impl<Runtime> GetMigrations for DanceboxMigrations<Runtime>
where
    Runtime: pallet_pooled_staking::Config,
    Runtime: pallet_session::Config,
    Runtime: pallet_registrar::Config,
    Runtime: pallet_balances::Config,
    Runtime: pallet_configuration::Config,
    Runtime: pallet_services_payment::Config,
    Runtime: cumulus_pallet_xcmp_queue::Config,
    Runtime: pallet_data_preservers::Config,
    Runtime: pallet_xcm::Config,
    Runtime: pallet_stream_payment::Config,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason:
        From<pallet_pooled_staking::HoldReason>,
    Runtime: pallet_foreign_asset_creator::Config,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason:
        From<pallet_registrar::HoldReason>,
    Runtime::AccountId: From<[u8; 32]>,
    <Runtime as pallet_balances::Config>::Balance: From<<<Runtime as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<Runtime::AccountId>>::Balance>,
    <Runtime as pallet_balances::Config>::Balance: From<u128>,
{
623
    fn get_migrations() -> Vec<Box<dyn Migration>> {
623
        // let migrate_invulnerables = MigrateInvulnerables::<Runtime>(Default::default());
623
        // let migrate_holds = MigrateHoldReason::<Runtime>(Default::default());
623
        // let migrate_config = MigrateConfigurationFullRotationPeriod::<Runtime>(Default::default());
623
        // let migrate_xcm = PolkadotXcmMigration::<Runtime>(Default::default());
623
        // let migrate_xcmp_queue = XcmpQueueMigration::<Runtime>(Default::default());
623
        // let migrate_services_payment =
623
        //     MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
623
        // let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
623
        // let migrate_hold_reason_runtime_enum =
623
        //     MigrateHoldReasonRuntimeEnum::<Runtime>(Default::default());
623

            
623
        //let migrate_config_parathread_params =
623
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
623
        //let migrate_add_collator_assignment_credits =
623
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
623
        //let migrate_xcmp_queue_v4 = XcmpQueueMigrationV4::<Runtime>(Default::default());
623
        //let migrate_registrar_pending_verification =
623
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
623
        //let migrate_registrar_manager =
623
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
623
        //let migrate_data_preservers_assignments =
623
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
623

            
623
        //let migrate_pallet_xcm_v4 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
623
        //let foreign_asset_creator_migration =
623
        //    ForeignAssetCreatorMigration::<Runtime>(Default::default());
623
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
623
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
623
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
623
        //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
623
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
623

            
623
        vec![
623
            // Applied in runtime 200
623
            //Box::new(migrate_invulnerables),
623
            // Applied in runtime 200
623
            //Box::new(migrate_holds),
623
            // Applied in runtime 300
623
            //Box::new(migrate_config),
623
            // Applied in runtime 300
623
            //Box::new(migrate_xcm),
623
            // Applied in runtime 300
623
            //Box::new(migrate_xcmp_queue),
623
            // Applied in runtime 400
623
            //Box::new(migrate_services_payment),
623
            // Applied in runtime 400
623
            //Box::new(migrate_hold_reason_runtime_enum),
623
            // Applied in runtime 400
623
            //Box::new(migrate_boot_nodes),
623
            // Applied in runtime 500
623
            //Box::new(migrate_config_parathread_params),
623
            // Applied in runtime 500
623
            //Box::new(migrate_add_collator_assignment_credits),
623
            // Applied in runtime 500
623
            //Box::new(migrate_xcmp_queue_v4),
623
            // Applied in runtime 700
623
            //Box::new(migrate_registrar_pending_verification),
623
            // Applied in runtime 700
623
            //Box::new(migrate_registrar_manager),
623
            // Applied in runtime 700
623
            //Box::new(migrate_pallet_xcm_v4),
623
            // Applied in runtime 700
623
            //Box::new(foreign_asset_creator_migration),
623
            // Applied in runtime 700
623
            //Box::new(migrate_data_preservers_assignments),
623
            // Applied in runtime 800
623
            //Box::new(migrate_registrar_reserves),
623
            // Applied in runtime 900
623
            //Box::new(migrate_config_max_parachain_percentage),
623
            // Applied in runtime 1100
623
            //Box::new(migrate_config_full_rotation_mode),
623
            // Applied in runtime 1200
623
            //Box::new(migrate_stream_payment_new_config_items),
623
            // Applied in runtime 1200
623
            //Box::new(migrate_pallet_xcm_v5),
623
            Box::new(migrate_pallet_session_v0_to_v1),
623
        ]
623
    }
}
#[cfg(feature = "relay")]
pub use relay::*;
#[cfg(feature = "relay")]
mod relay {
    use super::*;
    pub struct ExternalValidatorsInitialMigration<Runtime>(pub PhantomData<Runtime>);
    impl<Runtime> Migration for ExternalValidatorsInitialMigration<Runtime>
    where
        Runtime: pallet_external_validators::Config,
        Runtime: pallet_session::Config<
            ValidatorId = <Runtime as pallet_external_validators::Config>::ValidatorId,
        >,
    {
        fn friendly_name(&self) -> &str {
            "TM_ExternalValidatorsInitialMigration"
        }
2
        fn migrate(&self, _available_weight: Weight) -> Weight {
            use frame_support::pallet_prelude::*;
            // Set initial WhitelistedValidators to current validators from pallet session
2
            let session_keys = pallet_session::QueuedKeys::<Runtime>::get();
2
            let session_validators = BoundedVec::truncate_from(
2
                session_keys
2
                    .into_iter()
4
                    .map(|(validator, _keys)| validator)
2
                    .collect(),
2
            );
2
            pallet_external_validators::WhitelistedValidators::<Runtime>::put(session_validators);
2

            
2
            // Kill storage of ValidatorManager pallet
2
            let pallet_prefix: &[u8] = b"ValidatorManager";
2
            let _ = clear_storage_prefix(pallet_prefix, b"", b"", None, None);
2

            
2
            // One db read and one db write per element, plus the on-chain storage
2
            Runtime::DbWeight::get().reads_writes(1, 1)
2
        }
        #[cfg(feature = "try-runtime")]
        fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
            Ok(vec![])
        }
        #[cfg(feature = "try-runtime")]
        fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
            Ok(())
        }
    }
    pub struct BondedErasTimestampMigration<Runtime>(pub PhantomData<Runtime>);
    impl<Runtime> Migration for BondedErasTimestampMigration<Runtime>
    where
        Runtime: pallet_external_validator_slashes::Config,
    {
        fn friendly_name(&self) -> &str {
            "TM_ExternalValidatorSlashesBondedErasTimestampMigration"
        }
2
        fn migrate(&self, _available_weight: Weight) -> Weight {
            use frame_support::pallet_prelude::*;
2
            let bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
2
                frame_support::storage::unhashed::get(
2
                    &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
2
                )
2
                .unwrap_or_default();
2
            let new_eras = bonded_eras
2
                .iter()
6
                .map(|(era, session)| (*era, *session, 0u64))
2
                .collect();
2
            pallet_external_validator_slashes::BondedEras::<Runtime>::set(new_eras);
2

            
2
            // One db read and one db write per element, plus the on-chain storage
2
            Runtime::DbWeight::get().reads_writes(1, 1)
2
        }
        #[cfg(feature = "try-runtime")]
        fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
            use frame_support::pallet_prelude::*;
            let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
                frame_support::storage::unhashed::get(
                    &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
                )
                .unwrap_or_default();
            Ok(previous_bonded_eras.encode())
        }
        #[cfg(feature = "try-runtime")]
        fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
            use parity_scale_codec::Decode;
            let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
                Decode::decode(&mut &state[..]).expect("state to be decoded properly");
            let new_eras = pallet_external_validator_slashes::BondedEras::<Runtime>::get();
            for (i, bonded) in new_eras.iter().enumerate() {
                assert_eq!(previous_bonded_eras[i].0, bonded.0);
                assert_eq!(previous_bonded_eras[i].1, bonded.1);
                assert_eq!(bonded.2, 0u64);
            }
            Ok(())
        }
    }
    pub struct DancelightMigrations<Runtime>(PhantomData<Runtime>);
    impl<Runtime> GetMigrations for DancelightMigrations<Runtime>
    where
        Runtime: frame_system::Config,
        Runtime: pallet_external_validators::Config,
        Runtime: pallet_configuration::Config,
        Runtime: pallet_session::Config<
            ValidatorId = <Runtime as pallet_external_validators::Config>::ValidatorId,
        >,
        Runtime: pallet_external_validator_slashes::Config,
        Runtime: snowbridge_pallet_system::Config,
        Runtime: runtime_parachains::scheduler::Config,
        Runtime: runtime_parachains::shared::Config,
        Runtime: pallet_xcm::Config,
    {
81
        fn get_migrations() -> Vec<Box<dyn Migration>> {
81
            /*let migrate_config_full_rotation_mode =
81
            MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());*/
81
            /*let external_validator_slashes_bonded_eras_timestamp =
81
            BondedErasTimestampMigration::<Runtime>(Default::default());*/
81
            /*let snowbridge_ethereum_system_xcm_v5 =
81
            SnowbridgeEthereumSystemXcmV5::<Runtime>(Default::default());*/
81
            //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
81
            //let para_shared_v1_migration = MigrateParaSharedToV1::<Runtime>(Default::default());
81
            //let para_scheduler_v3_migration = MigrateParaSchedulerToV3::<Runtime>(Default::default());
81
            let migrate_pallet_session_v0_to_v1 =
81
                MigratePalletSessionV0toV1::<Runtime>(Default::default());
81
            let migrate_snowbridge_fee_per_gas_migration_v0_to_v1 =
81
                MigrateSnowbridgeFeePerGasMigrationV0ToV1::<Runtime>(Default::default());
81
            let eth_system_genesis_hashes = MigrateEthSystemGenesisHashes::<
81
                Runtime,
81
                snowbridge_system_migration::DancelightLocation,
81
            >(Default::default());
81

            
81
            vec![
81
                // Applied in runtime 1000
81
                //Box::new(migrate_mmr_leaf_pallet),
81
                // Applied in runtime 900
81
                //Box::new(migrate_external_validators),
81
                // Applied in runtime 1100
81
                //Box::new(migrate_config_full_rotation_mode),
81
                // Applied in runtime  1100
81
                //Box::new(external_validator_slashes_bonded_eras_timestamp),
81
                // Applied in runtime 1200
81
                //Box::new(snowbridge_ethereum_system_xcm_v5),
81
                // Applied in runtime 1200
81
                //Box::new(migrate_pallet_xcm_v5),
81
                // Apllied in runtime 1200
81
                // Box::new(para_shared_v1_migration),
81
                // Applied in runtime 1200
81
                //Box::new(para_scheduler_v3_migration),
81
                Box::new(migrate_pallet_session_v0_to_v1),
81
                Box::new(migrate_snowbridge_fee_per_gas_migration_v0_to_v1),
81
                Box::new(eth_system_genesis_hashes),
81
            ]
81
        }
    }
    pub struct StarlightMigrations<Runtime>(PhantomData<Runtime>);
    impl<Runtime> GetMigrations for StarlightMigrations<Runtime>
    where
        Runtime: frame_system::Config,
        Runtime: pallet_session::Config,
        Runtime: snowbridge_pallet_system::Config,
    {
81
        fn get_migrations() -> Vec<Box<dyn Migration>> {
81
            let migrate_pallet_session_v0_to_v1 =
81
                MigratePalletSessionV0toV1::<Runtime>(Default::default());
81
            let migrate_snowbridge_fee_per_gas_migration_v0_to_v1 =
81
                MigrateSnowbridgeFeePerGasMigrationV0ToV1::<Runtime>(Default::default());
81
            let eth_system_genesis_hashes = MigrateEthSystemGenesisHashes::<
81
                Runtime,
81
                snowbridge_system_migration::StarlightLocation,
81
            >(Default::default());
81
            vec![
81
                Box::new(migrate_pallet_session_v0_to_v1),
81
                Box::new(migrate_snowbridge_fee_per_gas_migration_v0_to_v1),
81
                Box::new(eth_system_genesis_hashes),
81
            ]
81
        }
    }
}