1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

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

            
17
use crate::xcm_config::UniversalLocation;
18
use crate::EthereumLocation;
19
use snowbridge_core::TokenIdOf;
20
use xcm::latest::Junction::GlobalConsensus;
21
use xcm::latest::Junctions::Here;
22
use xcm::latest::Junctions::X1;
23
use xcm::latest::NetworkId;
24
use xcm::latest::{Location, Reanchorable};
25
use xcm::v5::ROCOCO_GENESIS_HASH;
26
use xcm_executor::traits::ConvertLocation;
27
use {
28
    crate::{
29
        tests::common::ExtBuilder, BeefyMmrLeaf, CollatorConfiguration, ExternalValidators,
30
        PalletInfo, Runtime, Session,
31
    },
32
    beefy_primitives::mmr::BeefyAuthoritySet,
33
    frame_support::{migration::clear_storage_prefix, storage::unhashed, traits::PalletInfo as _},
34
    pallet_migrations::Migration,
35
    parity_scale_codec::Encode,
36
    sp_arithmetic::Perbill,
37
    tanssi_runtime_common::migrations::{
38
        snowbridge_system_migration::StarlightLocation, BondedErasTimestampMigration,
39
        ExternalValidatorsInitialMigration, HostConfigurationV3,
40
        MigrateConfigurationAddFullRotationMode, MigrateEthSystemGenesisHashes,
41
        MigrateMMRLeafPallet,
42
    },
43
    xcm::v3::Weight,
44
};
45

            
46
#[test]
47
1
fn test_migration_mmr_leaf_pallet_renaming() {
48
1
    ExtBuilder::default().build().execute_with(|| {
49
1
        let migrate_mmr_leaf_pallet = MigrateMMRLeafPallet::<Runtime>(Default::default());
50
1
        let old_pallet_name = MigrateMMRLeafPallet::<Runtime>::old_pallet_name();
51
1
        let old_storage_1 = frame_support::storage::storage_prefix(
52
1
            old_pallet_name.as_bytes(),
53
1
            b"example_storage_1",
54
1
        );
55
1
        let new_storage_1 = frame_support::storage::storage_prefix(
56
1
            PalletInfo::name::<BeefyMmrLeaf>()
57
1
                .expect("BeefyMMRLeaf pallet must be part of the runtime")
58
1
                .as_bytes(),
59
1
            b"example_storage_1",
60
1
        );
61
1
        unhashed::put(&old_storage_1, &1u64);
62
1

            
63
1
        let beefy_authority_set: BeefyAuthoritySet<()> = BeefyAuthoritySet {
64
1
            len: 5,
65
1
            ..Default::default()
66
1
        };
67
1
        let old_storage_2 = frame_support::storage::storage_prefix(
68
1
            old_pallet_name.as_bytes(),
69
1
            b"example_storage_2",
70
1
        );
71
1
        let new_storage_2 = frame_support::storage::storage_prefix(
72
1
            PalletInfo::name::<BeefyMmrLeaf>()
73
1
                .expect("BeefyMMRLeaf pallet must be part of the runtime")
74
1
                .as_bytes(),
75
1
            b"example_storage_2",
76
1
        );
77
1
        unhashed::put(&old_storage_2, &beefy_authority_set);
78
1

            
79
1
        let used_weight = migrate_mmr_leaf_pallet.migrate(Weight::MAX);
80
1
        assert_eq!(used_weight, Weight::MAX);
81

            
82
1
        assert_eq!(unhashed::get::<u64>(&old_storage_1), None);
83
1
        assert_eq!(unhashed::get::<BeefyAuthoritySet<()>>(&old_storage_2), None);
84

            
85
1
        assert_eq!(unhashed::get::<u64>(&new_storage_1), Some(1u64));
86
1
        assert_eq!(
87
1
            unhashed::get::<BeefyAuthoritySet<()>>(&new_storage_2),
88
1
            Some(BeefyAuthoritySet {
89
1
                len: 5,
90
1
                ..Default::default()
91
1
            })
92
1
        );
93
1
    });
94
1
}
95

            
96
#[test]
97
1
fn test_migration_external_validators_pallet() {
98
1
    ExtBuilder::default().build().execute_with(|| {
99
1
        let migrate_external_validators =
100
1
            ExternalValidatorsInitialMigration::<Runtime>(Default::default());
101
1
        let old_pallet_name = b"ValidatorManager";
102
1

            
103
1
        // Kill storage of ExternalValidators pallet, because this migration will initialize this pallet
104
1
        let _ = clear_storage_prefix(b"ExternalValidators", b"", b"", None, None);
105
1

            
106
1
        // Simulate adding data to the old pallet storage
107
1
        // The value is not used for anything, we only care that it is removed by the migration.
108
1
        let old_storage_key =
109
1
            frame_support::storage::storage_prefix(old_pallet_name, b"ValidatorsToAdd");
110
1
        let expected_validators: Vec<u64> = vec![5, 6];
111
1
        unhashed::put(&old_storage_key, &expected_validators);
112
1

            
113
1
        // Run migration
114
1
        let _used_weight = migrate_external_validators.migrate(Weight::MAX);
115
1

            
116
1
        // Assert that ValidatorManager pallet prefix is empty after migration
117
1
        let old_pallet_key = frame_support::storage::storage_prefix(old_pallet_name, b"");
118
1
        let old_storage_exists = unhashed::contains_prefixed_key(&old_pallet_key);
119
1
        assert!(
120
1
            !old_storage_exists,
121
            "Old pallet storage should be cleared after migration"
122
        );
123

            
124
        // Assert that ExternalValidators has the validators from ValidatorManager
125
1
        let migrated_validators = ExternalValidators::validators();
126
1
        let empty = vec![];
127
1
        assert_ne!(
128
            migrated_validators, empty,
129
            "ExternalValidators should not be empty after migration"
130
        );
131

            
132
        // ExternalValidators should be equal to validators from Session::queued_keys
133
2
        let expected_validators: Vec<_> = Session::queued_keys().into_iter().map(|x| x.0).collect();
134
1
        assert_eq!(migrated_validators, expected_validators);
135
1
    });
136
1
}
137

            
138
#[test]
139
1
fn test_migration_config_add_full_rotation_mode() {
140
1
    ExtBuilder::default().build().execute_with(|| {
141
        const CONFIGURATION_ACTIVE_CONFIG_KEY: &[u8] =
142
            &hex_literal::hex!("86e86c1d728ee2b18f76dd0e04d96cdbb4b49d95320d9021994c850f25b8e385");
143
        const CONFIGURATION_PENDING_CONFIGS_KEY: &[u8] =
144
            &hex_literal::hex!("86e86c1d728ee2b18f76dd0e04d96cdb53b4123b2e186e07fb7bad5dda5f55c0");
145

            
146
        // Modify active config
147
1
        frame_support::storage::unhashed::put_raw(
148
1
            CONFIGURATION_ACTIVE_CONFIG_KEY,
149
1
            &HostConfigurationV3 {
150
1
                max_collators: 5,
151
1
                min_orchestrator_collators: 2,
152
1
                max_orchestrator_collators: 1,
153
1
                collators_per_container: 3,
154
1
                full_rotation_period: 4,
155
1
                collators_per_parathread: 2,
156
1
                parathreads_per_collator: 1,
157
1
                target_container_chain_fullness: Perbill::from_percent(45),
158
1
                max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
159
1
            }
160
1
            .encode(),
161
1
        );
162
1
        // Modify pending configs
163
1
        frame_support::storage::unhashed::put_raw(
164
1
            CONFIGURATION_PENDING_CONFIGS_KEY,
165
1
            &vec![
166
1
                (
167
1
                    1234u32,
168
1
                    HostConfigurationV3 {
169
1
                        max_collators: 1,
170
1
                        min_orchestrator_collators: 4,
171
1
                        max_orchestrator_collators: 45,
172
1
                        collators_per_container: 5,
173
1
                        full_rotation_period: 1,
174
1
                        collators_per_parathread: 1,
175
1
                        parathreads_per_collator: 1,
176
1
                        target_container_chain_fullness: Perbill::from_percent(65),
177
1
                        max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
178
1
                    },
179
1
                ),
180
1
                (
181
1
                    5678u32,
182
1
                    HostConfigurationV3 {
183
1
                        max_collators: 1,
184
1
                        min_orchestrator_collators: 4,
185
1
                        max_orchestrator_collators: 45,
186
1
                        collators_per_container: 5,
187
1
                        full_rotation_period: 1,
188
1
                        collators_per_parathread: 1,
189
1
                        parathreads_per_collator: 1,
190
1
                        target_container_chain_fullness: Perbill::from_percent(65),
191
1
                        max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
192
1
                    },
193
1
                ),
194
1
            ]
195
1
            .encode(),
196
1
        );
197
1

            
198
1
        let migration = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
199
1
        migration.migrate(Default::default());
200
1

            
201
1
        let expected_active = pallet_configuration::HostConfiguration {
202
1
            max_collators: 5,
203
1
            min_orchestrator_collators: 2,
204
1
            max_orchestrator_collators: 1,
205
1
            collators_per_container: 3,
206
1
            full_rotation_period: 4,
207
1
            collators_per_parathread: 2,
208
1
            parathreads_per_collator: 1,
209
1
            target_container_chain_fullness: Perbill::from_percent(45),
210
1
            max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
211
1
            ..Default::default()
212
1
        };
213
1
        assert_eq!(CollatorConfiguration::config(), expected_active);
214

            
215
1
        let expected_pending = vec![
216
1
            (
217
1
                1234u32,
218
1
                pallet_configuration::HostConfiguration {
219
1
                    max_collators: 1,
220
1
                    min_orchestrator_collators: 4,
221
1
                    max_orchestrator_collators: 45,
222
1
                    collators_per_container: 5,
223
1
                    full_rotation_period: 1,
224
1
                    collators_per_parathread: 1,
225
1
                    parathreads_per_collator: 1,
226
1
                    target_container_chain_fullness: Perbill::from_percent(65),
227
1
                    max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
228
1
                    ..Default::default()
229
1
                },
230
1
            ),
231
1
            (
232
1
                5678u32,
233
1
                pallet_configuration::HostConfiguration {
234
1
                    max_collators: 1,
235
1
                    min_orchestrator_collators: 4,
236
1
                    max_orchestrator_collators: 45,
237
1
                    collators_per_container: 5,
238
1
                    full_rotation_period: 1,
239
1
                    collators_per_parathread: 1,
240
1
                    parathreads_per_collator: 1,
241
1
                    target_container_chain_fullness: Perbill::from_percent(65),
242
1
                    max_parachain_cores_percentage: Some(Perbill::from_percent(75)),
243
1
                    ..Default::default()
244
1
                },
245
1
            ),
246
1
        ];
247
1
        assert_eq!(CollatorConfiguration::pending_configs(), expected_pending);
248
1
    });
249
1
}
250

            
251
#[test]
252
1
fn test_add_timestamp_to_bonded_eras_migration() {
253
1
    ExtBuilder::default().build().execute_with(|| {
254
1
        let bonded_eras_key =
255
1
            pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key();
256
1

            
257
1
        let previous_value: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
258
1
            vec![(1, 1), (2, 2), (3, 3)];
259
1

            
260
1
        // Modify storage to pevious value
261
1
        frame_support::storage::unhashed::put_raw(&bonded_eras_key, &previous_value.encode());
262
1

            
263
1
        let migration = BondedErasTimestampMigration::<Runtime>(Default::default());
264
1
        migration.migrate(Default::default());
265
1

            
266
1
        let expected_bonded_eras_after: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex, u64)> =
267
1
            previous_value
268
1
                .iter()
269
3
                .map(|(era, session)| (*era, *session, 0u64))
270
1
                .collect();
271
1
        assert_eq!(
272
1
            pallet_external_validator_slashes::BondedEras::<Runtime>::get(),
273
1
            expected_bonded_eras_after
274
1
        );
275
1
    });
276
1
}
277

            
278
#[test]
279
1
fn test_genesis_hashes_migration() {
280
1
    ExtBuilder::default().build().execute_with(|| {
281
        // Raw values copied from moonlight runtime 1321
282
        const FOREIGN_TO_NATIVE_ID_KEY: &[u8] =
283
            &hex_literal::hex!("ccee781f0b9380204db9882d1b1c771d53e99bc228247291bd1d0d34fa7f53991550b71c8150857bbf873d7ce086b4d7bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e");
284
        const FOREIGN_TO_NATIVE_ID_VALUE: &[u8] =
285
            &hex_literal::hex!("010109006408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e");
286
        const NATIVE_TO_FOREIGN_ID_KEY: &[u8] =
287
            &hex_literal::hex!("ccee781f0b9380204db9882d1b1c771ddec2be471806c468b349224cf542e742be02dd7069c50095d8caa8a61b7c3af5010109006408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e");
288
        const NATIVE_TO_FOREIGN_ID_VALUE: &[u8] =
289
            &hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e");
290

            
291
        // Write foreign assets to pallet storage
292
1
        frame_support::storage::unhashed::put_raw(
293
1
            FOREIGN_TO_NATIVE_ID_KEY,
294
1
            FOREIGN_TO_NATIVE_ID_VALUE,
295
1
        );
296
1
        frame_support::storage::unhashed::put_raw(
297
1
            NATIVE_TO_FOREIGN_ID_KEY,
298
1
            NATIVE_TO_FOREIGN_ID_VALUE,
299
1
        );
300
1

            
301
1
        // Check storage before migration
302
1
        let f_n = snowbridge_pallet_system::ForeignToNativeId::<Runtime>::iter().collect::<Vec<_>>();
303
1
        let n_f = snowbridge_pallet_system::NativeToForeignId::<Runtime>::iter().collect::<Vec<_>>();
304
1

            
305
1
        assert_eq!(f_n, [(
306
1
            hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e").into(),
307
1
            Location {
308
1
                parents: 1,
309
1
                interior: X1([GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))].into()),
310
1
            },
311
1
        )]);
312
1
        assert_eq!(n_f, [(
313
1
            Location {
314
1
                parents: 1,
315
1
                interior: X1([GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))].into()),
316
1
            },
317
1
            hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e").into(),
318
1
        )]);
319

            
320
1
        let migration = MigrateEthSystemGenesisHashes::<Runtime, StarlightLocation>(Default::default());
321
1
        migration.migrate(Default::default());
322
1

            
323
1
        // Check storage after migration
324
1
        let f_n = snowbridge_pallet_system::ForeignToNativeId::<Runtime>::iter().collect::<Vec<_>>();
325
1
        let n_f = snowbridge_pallet_system::NativeToForeignId::<Runtime>::iter().collect::<Vec<_>>();
326
1

            
327
1
        assert_eq!(f_n, [(
328
1
            hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e").into(),
329
1
            StarlightLocation::get(),
330
1
        )]);
331
1
        assert_eq!(n_f, [(
332
1
            StarlightLocation::get(),
333
1
            hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e").into(),
334
1
        )]);
335
1
    });
336
1
}
337

            
338
#[test]
339
1
fn snowbridge_ethereum_system_token_id_does_not_change() {
340
1
    // If a new XCM version is released, we need to check that this location still encodes to the same
341
1
    // token id.
342
1
    // If this test fails, we need a migration in snowbridge_pallet_system to migrate the mappings
343
1
    // ForeignToNativeId and NativeToForeignId. Use migration SnowbridgeEthereumSystemXcmV5 as base.
344
1

            
345
1
    // Location of native starlight token.
346
1
    // When we support other token locations, maybe add them to this test as well.
347
1
    let location = Location {
348
1
        parents: 0,
349
1
        interior: Here,
350
1
    };
351
1

            
352
1
    let ethereum_location = EthereumLocation::get();
353
1
    // reanchor to Ethereum context
354
1
    // This means to add this junction: GlobalConsensus(NetworkId::ByGenesis(TANSSI_GENESIS_HASH))
355
1
    let location = location
356
1
        .clone()
357
1
        .reanchored(&ethereum_location, &UniversalLocation::get())
358
1
        .unwrap();
359
1

            
360
1
    let token_id = TokenIdOf::convert_location(&location).unwrap();
361
1

            
362
1
    // The token id from stagelight has been derived using xcm v4, but we are in xcm v5.
363
1
    // The derived token id from xcm v4 (the one you will find on chain) is:
364
1
    // 0x62e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6
365
1
    // So the exact token id from below is not important, as long as it does not change:
366
1
    assert_eq!(
367
1
        token_id,
368
1
        hex_literal::hex!("60dda4d65bd75bcebb4a0ea83becd6dd1139a296f439e2f5f65b37eb7b750fd8")
369
1
            .into()
370
1
    );
371
1
}