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, ROCOCO_GENESIS_HASH};
25
use xcm_executor::traits::ConvertLocation;
26
use {
27
    crate::{
28
        tests::common::ExtBuilder, BeefyMmrLeaf, CollatorConfiguration, ExternalValidators,
29
        PalletInfo, Runtime, Session,
30
    },
31
    beefy_primitives::mmr::BeefyAuthoritySet,
32
    frame_support::{migration::clear_storage_prefix, storage::unhashed, traits::PalletInfo as _},
33
    pallet_migrations::Migration,
34
    parity_scale_codec::Encode,
35
    sp_arithmetic::Perbill,
36
    tanssi_runtime_common::migrations::{
37
        BondedErasTimestampMigration, ExternalValidatorsInitialMigration, HostConfigurationV3,
38
        MigrateConfigurationAddFullRotationMode, MigrateMMRLeafPallet,
39
        SnowbridgeEthereumSystemXcmV5,
40
    },
41
    xcm::v3::Weight,
42
};
43

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
276
#[test]
277
1
fn test_snowbridge_ethereum_system_xcm_v5_migration() {
278
1
    ExtBuilder::default().build().execute_with(|| {
279
        // Raw values copied from stagelight runtime 1100
280
        const FOREIGN_TO_NATIVE_ID_KEY: &[u8] =
281
            &hex_literal::hex!("ccee781f0b9380204db9882d1b1c771d53e99bc228247291bd1d0d34fa7f53993faff06e7c800c84bd5d1f5ea566d14962e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6");
282
        const FOREIGN_TO_NATIVE_ID_VALUE: &[u8] =
283
            &hex_literal::hex!("01010905");
284
        const NATIVE_TO_FOREIGN_ID_KEY: &[u8] =
285
            &hex_literal::hex!("ccee781f0b9380204db9882d1b1c771ddec2be471806c468b349224cf542e742627f68650cbf12ff5b6ab3d5751bc1ea01010905");
286
        const NATIVE_TO_FOREIGN_ID_VALUE: &[u8] =
287
            &hex_literal::hex!("62e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6");
288

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

            
299
1
        let migration = SnowbridgeEthereumSystemXcmV5::<Runtime>(Default::default());
300
1
        migration.migrate(Default::default());
301
1

            
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!("62e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6").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!("62e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6").into(),
318
1
        )]);
319
1
    });
320
1
}
321

            
322
#[test]
323
1
fn snowbridge_ethereum_system_token_id_does_not_change() {
324
1
    // If a new XCM version is released, we need to check that this location still encodes to the same
325
1
    // token id.
326
1
    // If this test fails, we need a migration in snowbridge_pallet_system to migrate the mappings
327
1
    // ForeignToNativeId and NativeToForeignId. Use migration SnowbridgeEthereumSystemXcmV5 as base.
328
1

            
329
1
    // Location of native starlight token.
330
1
    // When we support other token locations, maybe add them to this test as well.
331
1
    let location = Location {
332
1
        parents: 0,
333
1
        interior: Here,
334
1
    };
335
1

            
336
1
    let ethereum_location = EthereumLocation::get();
337
1
    // reanchor to Ethereum context
338
1
    // This means to add this junction: GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))
339
1
    let location = location
340
1
        .clone()
341
1
        .reanchored(&ethereum_location, &UniversalLocation::get())
342
1
        .unwrap();
343
1

            
344
1
    let token_id = TokenIdOf::convert_location(&location).unwrap();
345
1

            
346
1
    // The token id from stagelight has been derived using xcm v4, but we are in xcm v5.
347
1
    // The derived token id from xcm v4 (the one you will find on chain) is:
348
1
    // 0x62e8f33b7fb0e7e2d2276564061a2f3c7bcb612e733b8bf5733ea16cee0ecba6
349
1
    // So the exact token id from below is not important, as long as it does not change:
350
1
    assert_eq!(
351
1
        token_id,
352
1
        hex_literal::hex!("bcd4282ca0c30cbd9c578b5c790e88c803d80cd9cc91f28686f24ac25a61e06e")
353
1
            .into()
354
1
    );
355
1
}