exonum 1.0.0

An extensible framework for blockchain software projects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
// Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use assert_matches::assert_matches;
use exonum_crypto::KeyPair;
use exonum_merkledb::{
    access::{AccessExt, CopyAccessExt},
    migration::Migration,
    HashTag, ObjectHash, SystemSchema, TemporaryDB,
};

use std::time::Duration;

use super::*;
use crate::{
    blockchain::{ApiSender, Block, BlockParams, BlockchainMut},
    helpers::{Height, ValidatorId},
    runtime::{
        migrations::{InitMigrationError, MigrationError},
        oneshot::Receiver,
        BlockchainData, CoreError, DispatcherSchema, ErrorMatch, MethodId, RuntimeIdentifier,
        SnapshotExt, WellKnownRuntime,
    },
};

const DELAY: Duration = Duration::from_millis(40);

#[derive(Default, Debug, Clone)]
struct MigrationRuntime {
    /// Flag to run good or erroneous migration script for `good-or-not-good` artifact.
    run_good_script: bool,
}

impl MigrationRuntime {
    fn with_script_flag(flag: bool) -> Self {
        Self {
            run_good_script: flag,
        }
    }
}

impl WellKnownRuntime for MigrationRuntime {
    const ID: u32 = 2;
}

impl Runtime for MigrationRuntime {
    fn deploy_artifact(&mut self, _artifact: ArtifactId, _deploy_spec: Vec<u8>) -> Receiver {
        Receiver::with_result(Ok(()))
    }

    // We use service freezing in some tests.
    fn is_supported(&self, feature: &RuntimeFeature) -> bool {
        match feature {
            RuntimeFeature::FreezingServices => true,
        }
    }

    fn is_artifact_deployed(&self, _id: &ArtifactId) -> bool {
        true
    }

    fn initiate_adding_service(
        &self,
        _context: ExecutionContext<'_>,
        _artifact: &ArtifactId,
        _parameters: Vec<u8>,
    ) -> Result<(), ExecutionError> {
        Ok(())
    }

    fn initiate_resuming_service(
        &self,
        _context: ExecutionContext<'_>,
        _artifact: &ArtifactId,
        _parameters: Vec<u8>,
    ) -> Result<(), ExecutionError> {
        Ok(())
    }

    fn update_service_status(&mut self, _snapshot: &dyn Snapshot, _state: &InstanceState) {}

    fn migrate(
        &self,
        new_artifact: &ArtifactId,
        data_version: &Version,
    ) -> Result<Option<MigrationScript>, InitMigrationError> {
        let mut end_version = new_artifact.version.clone();
        end_version.patch = 0;

        let script = match new_artifact.name.as_str() {
            "good" => simple_delayed_migration,
            "complex" => {
                let version1 = Version::new(0, 2, 0);
                let version2 = Version::new(0, 3, 0);

                if *data_version < version1 {
                    end_version = version1;
                    complex_migration_part1
                } else if *data_version < version2 && new_artifact.version >= version2 {
                    end_version = version2;
                    complex_migration_part2
                } else {
                    return Ok(None);
                }
            }
            "not-good" => erroneous_migration,
            "bad" => panicking_migration,
            "with-state" => migration_modifying_state_hash,
            "none" => return Ok(None),
            "good-or-not-good" => {
                if self.run_good_script {
                    simple_delayed_migration
                } else {
                    erroneous_migration
                }
            }
            _ => return Err(InitMigrationError::NotSupported),
        };
        let script = MigrationScript::new(script, end_version);
        Ok(Some(script))
    }

    fn execute(
        &self,
        _context: ExecutionContext<'_>,
        _method_id: MethodId,
        _arguments: &[u8],
    ) -> Result<(), ExecutionError> {
        Ok(())
    }

    fn before_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
        Ok(())
    }

    fn after_transactions(&self, _context: ExecutionContext<'_>) -> Result<(), ExecutionError> {
        Ok(())
    }

    fn after_commit(&mut self, _snapshot: &dyn Snapshot, _mailbox: &mut Mailbox) {}
}

fn simple_delayed_migration(_ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    thread::sleep(DELAY);
    Ok(())
}

fn erroneous_migration(_ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    thread::sleep(DELAY);
    Err(MigrationError::new("This migration is unsuccessful!"))
}

fn panicking_migration(_ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    thread::sleep(DELAY);
    panic!("This migration is unsuccessful!");
}

fn migration_modifying_state_hash(ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    for i in 1_u32..=2 {
        ctx.helper.new_data().get_proof_entry("entry").set(i);
        thread::sleep(DELAY / 2);
        ctx.helper.merge()?;
    }
    Ok(())
}

fn complex_migration_part1(ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    assert!(ctx.data_version < Version::new(0, 2, 0));
    ctx.helper.new_data().get_proof_entry("entry").set(1_u32);
    Ok(())
}

fn complex_migration_part2(ctx: &mut MigrationContext) -> Result<(), MigrationError> {
    assert!(ctx.data_version >= Version::new(0, 2, 0));
    assert!(ctx.data_version < Version::new(0, 3, 0));
    ctx.helper.new_data().get_proof_entry("entry").set(2_u32);
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum LocalResult {
    None,
    InMemory,
    Saved,
    SavedWithNodeRestart,
}

/// Test rig encapsulating typical tasks for migration tests, such as artifact deployment
/// and service instantiation.
#[derive(Debug)]
struct Rig {
    blockchain: BlockchainMut,
    next_service_id: InstanceId,
}

impl Rig {
    fn new() -> Self {
        Self::with_db_and_flag(Arc::new(TemporaryDB::new()), false)
    }

    fn with_db_and_flag(db: Arc<TemporaryDB>, flag: bool) -> Self {
        let blockchain = Blockchain::new(
            db as Arc<dyn Database>,
            KeyPair::random(),
            ApiSender::closed(),
        );
        let blockchain = blockchain
            .into_mut_with_dummy_config()
            .with_runtime(MigrationRuntime::with_script_flag(flag))
            .build();

        Self {
            blockchain,
            next_service_id: 100,
        }
    }

    /// Computes expected state hash of a migration.
    fn migration_hash(&self, indexes: &[(&str, Hash)]) -> Hash {
        let fork = self.blockchain.fork();
        let mut aggregator = fork.get_proof_map::<_, str, Hash>("_aggregator");
        for &(index_name, hash) in indexes {
            aggregator.put(index_name, hash);
        }
        aggregator.object_hash()
    }

    /// Emulates node stopping.
    fn stop(self) -> Blockchain {
        self.blockchain.immutable_view()
    }

    /// Emulates node restart by recreating the dispatcher.
    fn restart(&mut self) {
        let blockchain = self.blockchain.as_ref().to_owned();
        let blockchain = blockchain
            .into_mut_with_dummy_config()
            .with_runtime(MigrationRuntime::default())
            .build();
        self.blockchain = blockchain;
    }

    fn dispatcher(&mut self) -> &mut Dispatcher {
        self.blockchain.dispatcher()
    }

    fn migration_threads(&mut self) -> &HashMap<String, MigrationThread> {
        &self.dispatcher().migrations.threads
    }

    /// Asserts that no migration scripts are currently being executed.
    fn assert_no_migration_threads(&mut self) {
        assert!(self.migration_threads().is_empty());
    }

    /// Waits for migration scripts to finish according to the specified policy.
    fn wait_migration_threads(&mut self, local_result: LocalResult) {
        if local_result == LocalResult::None {
            // Don't wait at all.
        } else {
            // Wait for the script to finish.
            thread::sleep(DELAY * 3);
            if local_result == LocalResult::InMemory {
                // Keep the local result in memory.
            } else {
                self.create_block(self.blockchain.fork());
                assert!(self.dispatcher().migrations.threads.is_empty());

                if local_result == LocalResult::SavedWithNodeRestart {
                    self.restart();
                }
            }
        }
    }

    fn create_block(&mut self, fork: Fork) -> Block {
        let block_params = BlockParams::new(ValidatorId(0), Height(100), &[]);
        let patch = self
            .blockchain
            .create_patch_inner(fork, &block_params, &[], &());
        self.blockchain.commit(patch, vec![]).unwrap();
        self.blockchain.as_ref().last_block()
    }

    fn deploy_artifact(&mut self, name: &str, version: Version) -> ArtifactId {
        let artifact = ArtifactId::from_raw_parts(MigrationRuntime::ID, name.into(), version);

        let fork = self.blockchain.fork();
        Dispatcher::commit_artifact(&fork, &artifact, vec![]);
        self.create_block(fork);
        artifact
    }

    fn initialize_service(&mut self, artifact: ArtifactId, name: &str) -> InstanceSpec {
        let service = InstanceSpec::from_raw_parts(self.next_service_id, name.to_owned(), artifact);
        self.next_service_id += 1;

        let mut fork = self.blockchain.fork();
        let mut should_rollback = false;
        let mut context = ExecutionContext::for_block_call(
            self.dispatcher(),
            &mut fork,
            &mut should_rollback,
            service.as_descriptor(),
        );
        context
            .initiate_adding_service(service.clone(), vec![])
            .expect("`initiate_adding_service` failed");
        assert!(!should_rollback);
        self.create_block(fork);
        service
    }

    fn stop_service(&mut self, spec: &InstanceSpec) {
        let fork = self.blockchain.fork();
        Dispatcher::initiate_stopping_service(&fork, spec.id).unwrap();
        self.create_block(fork);
    }

    fn freeze_service(&mut self, spec: &InstanceSpec) {
        let fork = self.blockchain.fork();
        self.dispatcher()
            .initiate_freezing_service(&fork, spec.id)
            .unwrap();
        self.create_block(fork);
    }
}

fn test_migration_workflow(freeze_service: bool) {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact.clone(), "good");

    // Since service is not stopped, the migration should fail.
    let fork = rig.blockchain.fork();
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::InvalidServiceTransition)
            .with_description_containing("Data migration cannot be initiated")
    );

    // Stop or freeze the service.
    if freeze_service {
        rig.freeze_service(&service);
    } else {
        rig.stop_service(&service);
    }

    // Now, the migration start should succeed.
    let fork = rig.blockchain.fork();
    let ty = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    assert_matches!(ty, MigrationType::Async);
    // Migration scripts should not start executing immediately, but only on block commit.
    assert!(!rig.migration_threads().contains_key(&service.name));
    // Check that the migration target cannot be unloaded.
    let err = Dispatcher::unload_artifact(&fork, &new_artifact).unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUnloadArtifact)
            .with_description_containing("`100:good` references it as the data migration target")
    );
    rig.create_block(fork);

    // Check that the migration was initiated.
    assert!(rig.migration_threads().contains_key(&service.name));
    // Check that the old service data can be accessed.
    let snapshot = rig.blockchain.snapshot();
    assert!(snapshot.for_service(service.id).is_some());

    // Check that it is now impossible to unload either the old or the new artifact.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::unload_artifact(&fork, &old_artifact).unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUnloadArtifact)
            .with_description_containing("`100:good` references it as the current artifact")
    );
    let err = Dispatcher::unload_artifact(&fork, &new_artifact).unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUnloadArtifact)
            .with_description_containing("`100:good` references it as the data migration target")
    );

    // Create several more blocks before the migration is complete and check that
    // we don't spawn multiple migration scripts at once (this check is performed in `Migrations`).
    for _ in 0..3 {
        rig.create_block(rig.blockchain.fork());
    }

    // Wait until the migration script is completed and check that its result is recorded.
    thread::sleep(DELAY * 3);

    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let state = schema.get_instance(service.id).unwrap();
    let end_version = match state.status.unwrap() {
        InstanceStatus::Migrating(migration) => migration.end_version,
        status => panic!("Unexpected service status: {:?}", status),
    };
    assert_eq!(end_version, Version::new(0, 5, 0));
    let res = schema.local_migration_result(&service.name).unwrap();
    assert_eq!(res.0, Ok(HashTag::empty_map_hash()));
    assert!(!rig.migration_threads().contains_key(&service.name));

    // Create couple more blocks to check that the migration script is not launched again,
    // and the migration result is not overridden (these checks are `debug_assert`s
    // in the `Dispatcher` code).
    for _ in 0..3 {
        rig.create_block(rig.blockchain.fork());
    }
    assert!(!rig.migration_threads().contains_key(&service.name));
}

/// Tests basic workflow of migration initiation.
#[test]
fn migration_workflow() {
    test_migration_workflow(false);
}

#[test]
fn migration_workflow_with_frozen_service() {
    test_migration_workflow(true);
}

#[test]
fn migration_after_artifact_unloading() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");

    // Stop the service.
    rig.stop_service(&service);

    // Mark the new artifact for unload. This is valid because so far, no services are
    // associated with it.
    let fork = rig.blockchain.fork();
    Dispatcher::unload_artifact(&fork, &new_artifact).unwrap();
    // However, unloading means that we cannot initiate migration to the artifact.
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap_err();
    let expected_msg =
        "artifact `2:good:0.5.2` for data migration of service `100:good` is not active";
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::ArtifactNotDeployed)
            .with_description_containing(expected_msg)
    );
}

fn test_fast_forward_migration(freeze_service: bool) {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("none", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("none", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact.clone(), "service");
    if freeze_service {
        rig.freeze_service(&service);
    } else {
        rig.stop_service(&service);
    }

    let fork = rig.blockchain.fork();
    let ty = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    assert_matches!(ty, MigrationType::FastForward);
    rig.create_block(fork);

    // Service version should be updated when the block is merged.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let state = schema.get_instance(service.id).unwrap();
    assert_eq!(state.status, Some(InstanceStatus::Stopped));
    assert_eq!(state.pending_status, None);
    assert_eq!(state.spec.artifact, new_artifact);
    assert_eq!(state.data_version, None);

    // Check that the old artifact can now be unloaded.
    let fork = rig.blockchain.fork();
    Dispatcher::unload_artifact(&fork, &old_artifact).unwrap();
    rig.create_block(fork);
    let snapshot = rig.blockchain.snapshot();
    assert!(DispatcherSchema::new(&snapshot)
        .get_artifact(&old_artifact)
        .is_none());
}

/// Tests fast-forwarding a migration.
#[test]
fn fast_forward_migration() {
    test_fast_forward_migration(false);
}

#[test]
fn fast_forward_migration_with_service_freezing() {
    test_fast_forward_migration(true);
}

/// Tests checks performed by the dispatcher during migration initiation.
#[test]
fn migration_immediate_errors() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let unrelated_artifact = rig.deploy_artifact("unrelated", "1.0.1".parse().unwrap());
    let old_service = rig.initialize_service(old_artifact.clone(), "old");
    rig.stop_service(&old_service);
    let new_service = rig.initialize_service(new_artifact.clone(), "new");
    rig.stop_service(&new_service);

    let fork = rig.blockchain.fork();

    // Attempt to upgrade service to an unrelated artifact.
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, unrelated_artifact, &old_service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUpgradeService).with_any_description()
    );

    // Attempt to downgrade service.
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, old_artifact, &new_service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUpgradeService).with_any_description()
    );

    // Attempt to migrate to the same version.
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &new_service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::CannotUpgradeService).with_any_description()
    );

    // Attempt to migrate unknown service.
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, new_artifact, "bogus-service")
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::IncorrectInstanceId)
            .with_description_containing("for non-existing service `bogus-service`")
    );

    // Attempt to migrate to unknown artifact.
    let unknown_artifact = ArtifactId::from_raw_parts(
        RuntimeIdentifier::Rust as _,
        "good".into(),
        Version::new(0, 6, 0),
    );
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, unknown_artifact.clone(), &old_service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::UnknownArtifactId).with_any_description()
    );

    // Mark the artifact as pending.
    Dispatcher::commit_artifact(&fork, &unknown_artifact, vec![]);
    let err = rig
        .dispatcher()
        .initiate_migration(&fork, unknown_artifact, &old_service.name)
        .unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::ArtifactNotDeployed).with_any_description()
    );
}

/// Tests that an unfinished migration script is restarted on node restart.
#[test]
fn migration_is_resumed_after_node_restart() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    // Start migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    // Emulate node restart. Note that the old migration thread will continue running
    // as a detached thread, but since `Dispatcher.migrations` is dropped, the migration
    // will be aborted.
    rig.restart();
    assert!(rig.migration_threads().contains_key(&service.name));

    thread::sleep(DELAY * 3);
    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema.local_migration_result(&service.name).unwrap();
    assert_eq!(res.0, Ok(HashTag::empty_map_hash()));
}

/// Tests that migration scripts are timely aborted on node stop.
#[test]
fn migration_threads_are_timely_aborted() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("with-state", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("with-state", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    thread::sleep(DELAY * 2 / 3);
    let blockchain = rig.stop();
    thread::sleep(DELAY * 10);
    let snapshot = blockchain.snapshot();
    let migration = Migration::new(&service.name, &snapshot);
    // The `migration_modifying_state_hash` script should complete the 0 or 1 merge, but not
    // 2 merges.
    let val = migration
        .get_proof_entry::<_, u32>("entry")
        .get()
        .unwrap_or(0);
    assert!(val < 2);

    // New merges should not be added with time.
    thread::sleep(DELAY * 2);
    let snapshot = blockchain.snapshot();
    let migration = Migration::new(&service.name, &snapshot);
    let new_val = migration
        .get_proof_entry::<_, u32>("entry")
        .get()
        .unwrap_or(0);
    assert_eq!(val, new_val);
}

/// Tests that a completed migration script is not launched again.
#[test]
fn completed_migration_is_not_resumed_after_node_restart() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    // Start migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    thread::sleep(DELAY * 3);
    rig.create_block(rig.blockchain.fork());
    // Migration should be completed.
    rig.assert_no_migration_threads();
    // Check that the local migration result is persisted.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    assert!(schema.local_migration_result(&service.name).is_some());

    // Therefore, the script should not resume after blockchain restart.
    rig.restart();
    rig.assert_no_migration_threads();
}

/// Tests that an error in a migration script is reflected in the local migration result.
fn test_erroneous_migration(artifact_name: &str) {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact(artifact_name, "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact(artifact_name, "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "service");
    rig.stop_service(&service);

    // Start migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    // Wait for the migration script to complete.
    let res = loop {
        thread::sleep(DELAY * 3);

        rig.create_block(rig.blockchain.fork());
        let snapshot = rig.blockchain.snapshot();
        let schema = DispatcherSchema::new(&snapshot);
        if let Some(res) = schema.local_migration_result(&service.name) {
            break res;
        }
    };
    assert!(res
        .0
        .unwrap_err()
        .contains("This migration is unsuccessful!"));
}

#[test]
fn migration_with_error() {
    test_erroneous_migration("not-good");
}

#[test]
fn migration_with_panic() {
    test_erroneous_migration("bad");
}

/// Tests that concurrent migrations with the same artifact are independent.
#[test]
fn concurrent_migrations_to_same_artifact() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact.clone(), "service");
    rig.stop_service(&service);
    let other_service = rig.initialize_service(old_artifact.clone(), "other-service");
    rig.stop_service(&other_service);
    let another_service = rig.initialize_service(old_artifact, "another-service");
    rig.stop_service(&another_service);

    // Place two migration starts in the same block.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &other_service.name)
        .unwrap();
    rig.create_block(fork);

    let threads = rig.migration_threads();
    assert!(threads.contains_key(&service.name));
    assert!(threads.contains_key(&other_service.name));
    assert!(!threads.contains_key(&another_service.name));

    // ...and one more in the following block.
    thread::sleep(DELAY * 2 / 3);
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &another_service.name)
        .unwrap();
    rig.create_block(fork);

    assert!(rig.migration_threads().contains_key(&another_service.name));

    // Wait for first two migrations to finish.
    thread::sleep(DELAY / 2);
    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema.local_migration_result(&service.name).unwrap();
    assert_eq!(res.0, Ok(HashTag::empty_map_hash()));
    let res = schema.local_migration_result(&other_service.name).unwrap();
    assert_eq!(res.0, Ok(HashTag::empty_map_hash()));

    // Wait for the third migration to finish.
    thread::sleep(DELAY);
    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema
        .local_migration_result(&another_service.name)
        .unwrap();
    assert_eq!(res.0, Ok(HashTag::empty_map_hash()));

    rig.assert_no_migration_threads();
}

/// Tests that migration workflow changes state hash as expected.
#[test]
fn migration_influencing_state_hash() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("with-state", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("with-state", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "service");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    let state_hash = rig.create_block(fork).state_hash;

    for _ in 0..2 {
        // The sleeping interval is chosen to be larger than the interval of DB merges
        // in the migration script.
        thread::sleep(DELAY * 2 / 3);

        let fork = rig.blockchain.fork();
        // Check that we can access the old service data from outside.
        let blockchain_data = BlockchainData::new(&fork, "test");
        assert!(!blockchain_data
            .for_service(service.id)
            .unwrap()
            .get_proof_entry::<_, u32>("entry")
            .exists());
        // Check that the state during migration does not influence the default `state_hash`.
        let new_state_hash = rig.create_block(fork).state_hash;
        assert_eq!(state_hash, new_state_hash);
    }

    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema.local_migration_result(&service.name).unwrap();
    let migration_hash = res.0.unwrap();

    let migration = Migration::new(&service.name, &snapshot);
    assert_eq!(migration_hash, migration.state_hash());
    let aggregator = migration.state_aggregator();
    assert_eq!(
        aggregator.keys().collect::<Vec<_>>(),
        vec!["service.entry".to_owned()]
    );
    assert_eq!(aggregator.get("service.entry"), Some(2_u32.object_hash()));
}

/// Tests the basic workflow of migration rollback.
#[test]
fn migration_rollback_workflow() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    // Wait until the migration is finished locally.
    thread::sleep(DELAY * 3);
    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    schema.local_migration_result(&service.name).unwrap();
    rig.assert_no_migration_threads();

    // Signal the rollback.
    let fork = rig.blockchain.fork();
    Dispatcher::rollback_migration(&fork, &service.name).unwrap();
    rig.create_block(fork);

    // Check that local migration result is erased.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    assert!(schema.local_migration_result(&service.name).is_none());
    let state = schema.get_instance(service.id).unwrap();
    assert_eq!(state.status, Some(InstanceStatus::Stopped));
    // The artifact version hasn't changed.
    assert_eq!(state.data_version, None);
}

/// Tests the checks performed by the dispatcher during migration rollback.
#[test]
fn migration_rollback_invariants() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");

    // Non-existing service.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::rollback_migration(&fork, "bogus").unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::IncorrectInstanceId)
            .with_description_containing("Cannot rollback migration for unknown service `bogus`")
    );

    // Service is not stopped.
    let err = Dispatcher::rollback_migration(&fork, &service.name).unwrap_err();
    let no_migration_match = ErrorMatch::from_fail(&CoreError::NoMigration)
        .with_description_containing("it has no ongoing migration");
    assert_eq!(err, no_migration_match);

    rig.stop_service(&service);

    // Service is stopped, but there is no migration happening.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::rollback_migration(&fork, &service.name).unwrap_err();
    assert_eq!(err, no_migration_match);

    // Start migration and commit its result, thus making the rollback impossible.
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);
    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, HashTag::empty_map_hash()).unwrap();

    // In the same block, we'll get an error because the service already has
    // a pending status update.
    let err = Dispatcher::rollback_migration(&fork, &service.name).unwrap_err();
    assert_eq!(err, ErrorMatch::from_fail(&CoreError::ServicePending));
    rig.create_block(fork);
    // ...In the next block, we'll get another error.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::rollback_migration(&fork, &service.name).unwrap_err();
    assert_eq!(err, no_migration_match);
}

/// Tests that migration rollback aborts locally executed migration script.
#[test]
fn migration_rollback_aborts_migration_script() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("with-state", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("with-state", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    // Rollback the migration without waiting for the migration script to succeed locally.
    let fork = rig.blockchain.fork();
    Dispatcher::rollback_migration(&fork, &service.name).unwrap();
    rig.create_block(fork);

    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    assert!(schema.local_migration_result(&service.name).is_none());
    rig.assert_no_migration_threads();
    let migration = Migration::new(&service.name, &snapshot);
    assert!(!migration.get_proof_entry::<_, u32>("entry").exists());

    // Wait some time to ensure that script doesn't merge changes to the DB.
    thread::sleep(DELAY);
    let snapshot = rig.blockchain.snapshot();
    let migration = Migration::new(&service.name, &snapshot);
    assert!(!migration.get_proof_entry::<_, u32>("entry").exists());
}

/// Tests that migration rollback erases data created by the migration script.
#[test]
fn migration_rollback_erases_migration_data() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("with-state", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("with-state", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    // Wait until the migration is finished locally.
    thread::sleep(DELAY * 10);
    rig.create_block(rig.blockchain.fork());
    let snapshot = rig.blockchain.snapshot();
    let migration = Migration::new(&service.name, &snapshot);
    assert_eq!(migration.get_proof_entry::<_, u32>("entry").get(), Some(2));

    let fork = rig.blockchain.fork();
    Dispatcher::rollback_migration(&fork, &service.name).unwrap();
    rig.create_block(fork);

    // Migration data should be dropped now.
    let snapshot = rig.blockchain.snapshot();
    let migration = Migration::new(&service.name, &snapshot);
    assert!(!migration.get_proof_entry::<_, u32>("entry").exists());
}

/// Tests basic migration commit workflow.
#[test]
fn migration_commit_workflow() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    // Wait until the migration is finished locally.
    thread::sleep(DELAY * 3);
    rig.create_block(rig.blockchain.fork());

    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, HashTag::empty_map_hash()).unwrap();
    rig.create_block(fork);

    // Check that local migration result is erased.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema.local_migration_result(&service.name).unwrap();
    assert_eq!(res.0.unwrap(), HashTag::empty_map_hash());
    let state = schema.get_instance(service.id).unwrap();
    let expected_status = InstanceStatus::migrating(InstanceMigration::from_raw_parts(
        new_artifact,
        Version::new(0, 5, 0),
        Some(HashTag::empty_map_hash()),
    ));
    assert_eq!(state.status, Some(expected_status));
}

/// Tests checks performed by the dispatcher during migration commit.
#[test]
fn migration_commit_invariants() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "good");

    // Non-existing service.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::commit_migration(&fork, "bogus", Hash::zero()).unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::IncorrectInstanceId)
            .with_description_containing("Cannot commit migration for unknown service `bogus`")
    );

    // Service is not stopped.
    let err = Dispatcher::commit_migration(&fork, &service.name, Hash::zero()).unwrap_err();
    let no_migration_match = ErrorMatch::from_fail(&CoreError::NoMigration)
        .with_description_containing("Cannot commit migration for service `100:good`");
    assert_eq!(err, no_migration_match);

    rig.stop_service(&service);

    // Service is stopped, but there is no migration happening.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::commit_migration(&fork, &service.name, Hash::zero()).unwrap_err();
    assert_eq!(err, no_migration_match);

    // Start migration and commit its result, making the second commit impossible.
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);
    let fork = rig.blockchain.fork();
    let migration_hash = HashTag::empty_map_hash();
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();

    // In the same block, we'll get an error because the service already has
    // a pending status update.
    let err = Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap_err();
    assert_eq!(err, ErrorMatch::from_fail(&CoreError::ServicePending));
    rig.create_block(fork);

    // ...In the next block, we'll get another error.
    let fork = rig.blockchain.fork();
    let err = Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap_err();
    assert_eq!(err, no_migration_match);
}

/// Tests that a migration commit after the migration script finished locally with an error
/// leads to node stopping.
fn test_migration_commit_with_local_error(
    rig: &mut Rig,
    local_result: LocalResult,
    artifact_name: &str,
) {
    let old_artifact = rig.deploy_artifact(artifact_name, "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact(artifact_name, "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "service");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    rig.wait_migration_threads(local_result);

    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, Hash::zero()).unwrap();
    rig.create_block(fork); // << should panic
}

#[test]
#[should_panic(expected = "locally it has finished with an error: This migration is unsuccessful")]
fn migration_commit_with_local_error_blocking() {
    test_migration_commit_with_local_error(&mut Rig::new(), LocalResult::None, "not-good");
}

#[test]
#[should_panic(expected = "locally it has finished with an error: This migration is unsuccessful")]
fn migration_commit_with_local_error_in_memory() {
    test_migration_commit_with_local_error(&mut Rig::new(), LocalResult::InMemory, "not-good");
}

#[test]
#[should_panic(expected = "locally it has finished with an error: This migration is unsuccessful")]
fn migration_commit_with_local_error_saved() {
    test_migration_commit_with_local_error(&mut Rig::new(), LocalResult::Saved, "not-good");
}

#[test]
#[should_panic(expected = "locally it has finished with an error: This migration is unsuccessful")]
fn migration_commit_with_local_error_saved_and_node_restart() {
    test_migration_commit_with_local_error(
        &mut Rig::new(),
        LocalResult::SavedWithNodeRestart,
        "not-good",
    );
}

#[test]
fn test_migration_restart() {
    let artifact_name = "good-or-not-good";
    let service_name = "service";
    let db = Arc::new(TemporaryDB::new());

    // Running migration that should fail.
    std::panic::catch_unwind(|| {
        // Set script flag to fail migration.
        let mut rig = Rig::with_db_and_flag(Arc::clone(&db), false);
        test_migration_commit_with_local_error(&mut rig, LocalResult::Saved, artifact_name)
    })
    .expect_err("Node should panic on unsuccessful migration commit");

    // Check that we have failed result locally.
    let snapshot = db.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema
        .local_migration_result(service_name)
        .expect("Schema does not have local result");
    assert_eq!(res.0.unwrap_err(), "This migration is unsuccessful!");

    // Remove local migration result.
    let mut fork = db.fork();
    rollback_migration(&mut fork, service_name);
    remove_local_migration_result(&fork, service_name);
    db.merge_sync(fork.into_patch())
        .expect("Failed to merge patch after local migration result remove");

    // Check that local result is removed.
    let snapshot = db.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    assert!(schema.local_migration_result(service_name).is_none());

    // Set script flag to migrate successfully.
    let mut rig = Rig::with_db_and_flag(Arc::clone(&db), true);

    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, service_name, HashTag::empty_map_hash())
        .expect("Failed to commit migration");
    rig.create_block(fork);

    // Check that the migration script has finished.
    rig.assert_no_migration_threads();

    // Check that local migration result is erased.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let res = schema.local_migration_result(service_name).unwrap();
    assert_eq!(res.0.unwrap(), HashTag::empty_map_hash());

    // Check current instance migration status.
    let state = schema.get_instance(100).unwrap();
    let artifact = ArtifactId::from_raw_parts(
        MigrationRuntime::ID,
        artifact_name.to_string(),
        "0.5.2".parse().unwrap(),
    );
    let expected_status = InstanceStatus::migrating(InstanceMigration::from_raw_parts(
        artifact,
        Version::new(0, 5, 0),
        Some(HashTag::empty_map_hash()),
    ));
    assert_eq!(state.status, Some(expected_status));
}

/// Tests that a migration commit after the migration script finished locally with another hash
/// leads to node stopping.
fn test_migration_commit_with_differing_hash(local_result: LocalResult) {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("good", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("good", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "service");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    rig.wait_migration_threads(local_result);

    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, Hash::zero()).unwrap();
    rig.create_block(fork); // << should panic
}

#[test]
#[should_panic(expected = "locally it has finished with another hash")]
fn migration_commit_with_differing_hash_blocking() {
    test_migration_commit_with_differing_hash(LocalResult::None);
}

#[test]
#[should_panic(expected = "locally it has finished with another hash")]
fn migration_commit_with_differing_hash_in_memory() {
    test_migration_commit_with_differing_hash(LocalResult::InMemory);
}

#[test]
#[should_panic(expected = "locally it has finished with another hash")]
fn migration_commit_with_differing_hash_saved() {
    test_migration_commit_with_differing_hash(LocalResult::Saved);
}

#[test]
#[should_panic(expected = "locally it has finished with another hash")]
fn migration_commit_with_differing_hash_saved_and_node_restarted() {
    test_migration_commit_with_differing_hash(LocalResult::SavedWithNodeRestart);
}

/// Tests that committing a migration with a locally running migration script leads to the node
/// waiting until the script is completed.
#[test]
fn migration_commit_without_completing_script_locally() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("with-state", "0.3.0".parse().unwrap());
    let new_artifact = rig.deploy_artifact("with-state", "0.5.2".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "test");
    rig.stop_service(&service);

    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    // Compute migration hash using the knowledge about the end state of migrated data.
    let migration_hash = rig.migration_hash(&[("test.entry", 2_u32.object_hash())]);

    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();
    rig.create_block(fork);
    // Check that the migration script has finished.
    rig.assert_no_migration_threads();

    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let state = schema.get_instance(service.id).unwrap();
    let expected_status = InstanceStatus::migrating(InstanceMigration::from_raw_parts(
        new_artifact,
        Version::new(0, 5, 0),
        Some(migration_hash),
    ));
    assert_eq!(state.status, Some(expected_status));

    // Flush the migration.
    let mut fork = rig.blockchain.fork();
    Dispatcher::flush_migration(&mut fork, &service.name).unwrap();
    let state_hash = rig.create_block(fork).state_hash;

    // The artifact version should be updated.
    let snapshot = rig.blockchain.snapshot();
    let schema = DispatcherSchema::new(&snapshot);
    let state = schema.get_instance(service.id).unwrap();
    assert_eq!(state.data_version, Some(Version::new(0, 5, 0)));
    assert_eq!(state.status, Some(InstanceStatus::Stopped));
    assert!(schema.local_migration_result(&service.name).is_none());

    // Check that service data has been updated.
    let entry = snapshot.get_proof_entry::<_, u32>("test.entry");
    assert_eq!(entry.get(), Some(2));
    // Check state aggregation.
    let aggregator = SystemSchema::new(&snapshot).state_aggregator();
    assert_eq!(aggregator.get("test.entry"), Some(2_u32.object_hash()));
    assert_eq!(aggregator.object_hash(), state_hash);
}

/// Tests that the migration workflow is applicable to a migration spanning multiple scripts.
#[test]
fn two_part_migration() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("complex", "0.1.1".parse().unwrap());
    let new_artifact = rig.deploy_artifact("complex", "0.3.7".parse().unwrap());
    let service = rig.initialize_service(old_artifact.clone(), "test");
    rig.stop_service(&service);

    // First part of migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    let migration_hash = rig.migration_hash(&[("test.entry", 1_u32.object_hash())]);
    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();
    rig.create_block(fork);

    let mut fork = rig.blockchain.fork();
    Dispatcher::flush_migration(&mut fork, &service.name).unwrap();
    rig.create_block(fork);

    // Check service data and metadata.
    let snapshot = rig.blockchain.snapshot();
    assert_eq!(
        snapshot.get_proof_entry::<_, u32>("test.entry").get(),
        Some(1)
    );
    let schema = DispatcherSchema::new(&snapshot);
    let instance_state = schema.get_instance(service.id).unwrap();
    assert_eq!(instance_state.data_version, Some(Version::new(0, 2, 0)));

    // The old artifact can now be unloaded, since it's no longer associated with the service.
    // In other words, the service cannot be started with the old artifact due to a different
    // data layout, so it can be removed from the blockchain.
    let fork = rig.blockchain.fork();
    Dispatcher::unload_artifact(&fork, &old_artifact).unwrap();

    // Second part of migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    let migration_hash = rig.migration_hash(&[("test.entry", 2_u32.object_hash())]);
    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();
    rig.create_block(fork);

    let mut fork = rig.blockchain.fork();
    Dispatcher::flush_migration(&mut fork, &service.name).unwrap();
    rig.create_block(fork);

    // Check service data and metadata.
    let snapshot = rig.blockchain.snapshot();
    assert_eq!(
        snapshot.get_proof_entry::<_, u32>("test.entry").get(),
        Some(2)
    );
    let schema = DispatcherSchema::new(&snapshot);
    let instance_state = schema.get_instance(service.id).unwrap();
    assert_eq!(instance_state.data_version, Some(Version::new(0, 3, 0)));

    // Check that the new artifact can be unloaded.
    let fork = rig.blockchain.fork();
    Dispatcher::unload_artifact(&fork, &new_artifact).unwrap();
    rig.create_block(fork);
}

#[test]
fn two_part_migration_with_intermediate_artifact() {
    let mut rig = Rig::new();
    let old_artifact = rig.deploy_artifact("complex", "0.1.1".parse().unwrap());
    let intermediate_artifact = rig.deploy_artifact("complex", "0.2.2".parse().unwrap());
    let new_artifact = rig.deploy_artifact("complex", "0.3.7".parse().unwrap());
    let service = rig.initialize_service(old_artifact, "test");
    rig.stop_service(&service);

    // First part of migration.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    let migration_hash = rig.migration_hash(&[("test.entry", 1_u32.object_hash())]);
    let fork = rig.blockchain.fork();
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();
    rig.create_block(fork);
    let mut fork = rig.blockchain.fork();
    Dispatcher::flush_migration(&mut fork, &service.name).unwrap();
    rig.create_block(fork);

    // Use a fast-forward migration to associate the service with an intermediate artifact.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, intermediate_artifact.clone(), &service.name)
        .unwrap();
    rig.create_block(fork);

    // Check service data and metadata.
    let snapshot = rig.blockchain.snapshot();
    assert_eq!(
        snapshot.get_proof_entry::<_, u32>("test.entry").get(),
        Some(1)
    );
    let schema = DispatcherSchema::new(&snapshot);
    let instance_state = schema.get_instance(service.id).unwrap();
    assert_eq!(instance_state.status, Some(InstanceStatus::Stopped));
    assert_eq!(instance_state.spec.artifact, intermediate_artifact);
    assert_eq!(instance_state.data_version, None);

    // Second part of migration. Since we've associated the service with a newer artifact,
    // the state will indicate that read endpoints may be retained for the service.
    let fork = rig.blockchain.fork();
    rig.dispatcher()
        .initiate_migration(&fork, new_artifact, &service.name)
        .unwrap();
    rig.create_block(fork);

    thread::sleep(DELAY * 5);
    let migration_hash = rig.migration_hash(&[("test.entry", 2_u32.object_hash())]);
    let fork = rig.blockchain.fork();
    // Check that intermediate blockchain data can be accessed.
    let blockchain_data = BlockchainData::new(&fork, "other");
    let entry_value = blockchain_data
        .for_service(service.id)
        .unwrap()
        .get_proof_entry::<_, u32>("entry")
        .get();
    assert_eq!(entry_value, Some(1));
    Dispatcher::commit_migration(&fork, &service.name, migration_hash).unwrap();
    rig.create_block(fork);

    let mut fork = rig.blockchain.fork();
    Dispatcher::flush_migration(&mut fork, &service.name).unwrap();
    rig.create_block(fork);

    // Check service data and metadata.
    let snapshot = rig.blockchain.snapshot();
    assert_eq!(
        snapshot.get_proof_entry::<_, u32>("test.entry").get(),
        Some(2)
    );
    let schema = DispatcherSchema::new(&snapshot);
    let instance_state = schema.get_instance(service.id).unwrap();
    assert_eq!(instance_state.data_version, Some(Version::new(0, 3, 0)));
}