exonum-rust-runtime 1.0.0

The runtime is for running Exonum services written in Rust.
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
// 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::{
    blockchain::{ApiSender, Blockchain, BlockchainBuilder, BlockchainMut},
    crypto::KeyPair,
    helpers::Height,
    merkledb::{
        access::{Access, CopyAccessExt, FromAccess},
        Database, ObjectHash, ProofEntry, TemporaryDB,
    },
    runtime::{
        migrations::{
            InitMigrationError, MigrateData, MigrationContext, MigrationError, MigrationScript,
        },
        versioning::{ArtifactReqError, Version},
        ArtifactId, CoreError, ErrorMatch, ExecutionContext, ExecutionError, InstanceId,
        InstanceStatus, RuntimeIdentifier, SnapshotExt,
    },
};
use exonum_api::UpdateEndpoints;
use exonum_derive::*;
use futures::channel::mpsc;
use pretty_assertions::assert_eq;

use std::{cmp, sync::Arc};

use self::inspected::{
    assert_no_endpoint_update, create_genesis_config_builder, execute_transaction,
    get_endpoint_paths, CommitMigration, EventsHandle, Inspected, MigrateService, ResumeService,
    RuntimeEvent, ToySupervisor, ToySupervisorService,
};
use exonum_rust_runtime::{
    spec::{Deploy, Spec},
    ArtifactProtobufSpec, DefaultInstance, RustRuntimeBuilder, Service, ServiceFactory,
};

mod inspected;

/// Artifact versions initially deployed on the blockchain.
const VERSIONS: &[&str] = &["0.1.0", "0.1.1", "0.1.5", "0.2.0"];

impl CommitMigration {
    fn for_counter(blockchain: &BlockchainMut, new_counter_value: u64) -> Self {
        let migration_hash = {
            let fork = blockchain.fork();
            let mut aggregator = fork.get_proof_map("_temp");
            aggregator.put("counter.counter", new_counter_value.object_hash());
            aggregator.object_hash()
        };
        Self {
            instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
            migration_hash,
        }
    }
}

#[derive(Debug, FromAccess, RequireArtifact)]
#[require_artifact(name = "counter", version = "^0.1")]
struct Schema<T: Access> {
    counter: ProofEntry<T::Base, u64>,
}

impl<T: Access> Schema<T> {
    pub fn new(access: T) -> Self {
        Self::from_root(access).unwrap()
    }
}

#[exonum_interface(auto_ids)]
trait CountInterface<Ctx> {
    type Output;

    fn increment(&self, context: Ctx, value: u64) -> Self::Output;
}

#[derive(Debug, ServiceDispatcher)]
#[service_dispatcher(implements("CountInterface"))]
struct Counter;

impl Service for Counter {}

impl CountInterface<ExecutionContext<'_>> for Counter {
    type Output = Result<(), ExecutionError>;

    fn increment(&self, context: ExecutionContext<'_>, value: u64) -> Self::Output {
        let mut schema = Schema::new(context.service_data());
        let count = schema.counter.get().unwrap_or(0);
        schema.counter.set(count + value);
        Ok(())
    }
}

#[derive(Debug)]
struct CounterFactory {
    version: Version,
}

impl CounterFactory {
    fn new(version: Version) -> Self {
        Self { version }
    }
}

impl ServiceFactory for CounterFactory {
    fn artifact_id(&self) -> ArtifactId {
        ArtifactId::from_raw_parts(
            RuntimeIdentifier::Rust as _,
            "counter".to_owned(),
            self.version.clone(),
        )
    }

    fn artifact_protobuf_spec(&self) -> ArtifactProtobufSpec {
        ArtifactProtobufSpec::default()
    }

    fn create_instance(&self) -> Box<dyn Service> {
        Box::new(Counter)
    }
}

impl DefaultInstance for CounterFactory {
    const INSTANCE_ID: InstanceId = 100;
    const INSTANCE_NAME: &'static str = "counter";
}

fn migration_script(context: &mut MigrationContext) -> Result<(), MigrationError> {
    let old_schema = Schema::new(context.helper.old_data());
    let mut new_schema = Schema::new(context.helper.new_data());
    new_schema
        .counter
        .set(old_schema.counter.get().unwrap_or(0) + 1);
    Ok(())
}

impl MigrateData for CounterFactory {
    fn migration_scripts(
        &self,
        start_version: &Version,
    ) -> Result<Vec<MigrationScript>, InitMigrationError> {
        // We use custom implementation here to generate an infinite amount of scripts.
        let min_version = Version::new(0, 1, 0);
        let max_version = cmp::min(Version::new(0, 2, 0), self.version.clone());
        if *start_version < min_version {
            Err(InitMigrationError::OldStartVersion {
                min_supported_version: min_version,
            })
        } else if *start_version > max_version {
            Err(InitMigrationError::FutureStartVersion {
                max_supported_version: max_version,
            })
        } else if *start_version == max_version {
            Ok(vec![])
        } else {
            let mut end_version = start_version.to_owned();
            end_version.increment_patch();
            let script = MigrationScript::new(migration_script, end_version);
            Ok(vec![script])
        }
    }
}

fn create_runtime(
    db: impl Into<Arc<dyn Database>>,
) -> (BlockchainMut, EventsHandle, mpsc::Receiver<UpdateEndpoints>) {
    let mut counter_services = VERSIONS.iter().map(|&version| {
        let factory = CounterFactory::new(version.parse().unwrap());
        Spec::migrating(factory)
    });

    let mut genesis = create_genesis_config_builder();
    let mut rust_runtime = RustRuntimeBuilder::new();
    Spec::new(ToySupervisorService)
        .with_default_instance()
        .deploy(&mut genesis, &mut rust_runtime);

    // Deploy the instance of the earliest counter service and artifacts for other versions.
    let service = counter_services.next().unwrap();
    service
        .with_default_instance()
        .deploy(&mut genesis, &mut rust_runtime);
    for service in counter_services {
        service.deploy(&mut genesis, &mut rust_runtime);
    }

    let (endpoints_tx, endpoints_rx) = mpsc::channel(16);
    let inspected = Inspected::new(rust_runtime.build(endpoints_tx));
    let events_handle = inspected.events.clone();

    let blockchain = Blockchain::new(db, KeyPair::random(), ApiSender::closed());
    let blockchain = BlockchainBuilder::new(blockchain)
        .with_genesis_config(genesis.build())
        .with_runtime(inspected)
        .build();
    (blockchain, events_handle, endpoints_rx)
}

fn test_basic_migration(freeze_service: bool) {
    let (mut blockchain, events, mut endpoints_rx) = create_runtime(TemporaryDB::new());
    let old_spec = CounterFactory::new(VERSIONS[0].parse().unwrap())
        .default_instance()
        .instance_spec;
    let new_artifact = CounterFactory::new(VERSIONS[2].parse().unwrap()).artifact_id();
    get_endpoint_paths(&mut endpoints_rx);

    let keypair = KeyPair::random();
    let tx = keypair.increment(CounterFactory::INSTANCE_ID, 1);
    execute_transaction(&mut blockchain, tx).unwrap();
    assert_no_endpoint_update(&mut endpoints_rx);

    // Stop or freeze the service.
    let tx = if freeze_service {
        keypair.freeze_service(
            ToySupervisorService::INSTANCE_ID,
            CounterFactory::INSTANCE_ID,
        )
    } else {
        keypair.stop_service(
            ToySupervisorService::INSTANCE_ID,
            CounterFactory::INSTANCE_ID,
        )
    };
    execute_transaction(&mut blockchain, tx).unwrap();

    if freeze_service {
        assert_no_endpoint_update(&mut endpoints_rx);
    } else {
        let paths = get_endpoint_paths(&mut endpoints_rx);
        assert!(paths.contains("services/supervisor"));
        assert!(!paths.contains("services/counter"));
    }

    // Start async migration.
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: new_artifact,
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    execute_transaction(&mut blockchain, tx).unwrap();

    if freeze_service {
        assert_no_endpoint_update(&mut endpoints_rx);
    } else {
        let paths = get_endpoint_paths(&mut endpoints_rx);
        assert!(paths.contains("services/supervisor"));
        assert!(paths.contains("services/counter"));
    }

    // Commit migration.
    let commit = CommitMigration::for_counter(&blockchain, 2);
    let tx = keypair.commit_migration(ToySupervisorService::INSTANCE_ID, commit);
    execute_transaction(&mut blockchain, tx).unwrap();
    assert_no_endpoint_update(&mut endpoints_rx);

    // Check that we're still accessing old service data.
    let snapshot = blockchain.snapshot();
    let schema: Schema<_> = snapshot
        .service_schema(CounterFactory::INSTANCE_ID)
        .unwrap();
    assert_eq!(schema.counter.get(), Some(1));
    // Check that transactions to the service are not dispatched.
    let tx = keypair.increment(CounterFactory::INSTANCE_ID, 5);
    drop(events.take());

    let err = execute_transaction(&mut blockchain, tx).unwrap_err();
    assert_eq!(
        err,
        ErrorMatch::from_fail(&CoreError::IncorrectInstanceId)
            .with_description_containing("unknown service with ID 100")
    );
    assert_no_endpoint_update(&mut endpoints_rx);

    // Check that the migrating service does not receive hooks.
    assert_eq!(
        events.take(),
        vec![
            RuntimeEvent::BeforeTransactions(Height(5), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::AfterTransactions(Height(5), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::AfterCommit(Height(6)),
        ]
    );

    // Flush migration. The service will transition to `Stopped` status.
    let tx = keypair.flush_migration(
        ToySupervisorService::INSTANCE_ID,
        CounterFactory::INSTANCE_NAME.to_owned(),
    );
    execute_transaction(&mut blockchain, tx).unwrap();
    let snapshot = blockchain.snapshot();
    let err = snapshot
        .service_schema::<Schema<_>, _>(CounterFactory::INSTANCE_ID)
        .unwrap_err();
    assert_matches!(err, ArtifactReqError::NoService);

    assert_eq!(
        events.take(),
        vec![
            RuntimeEvent::BeforeTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::AfterTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::CommitService(Height(7), old_spec, InstanceStatus::Stopped),
            RuntimeEvent::AfterCommit(Height(7)),
        ]
    );

    // Since service has transitioned from `Migrating` to `Stopped`, its endpoints should
    // be removed.
    let paths = get_endpoint_paths(&mut endpoints_rx);
    assert!(paths.contains("services/supervisor"));
    assert!(!paths.contains("services/counter"));
}

#[test]
fn basic_migration() {
    test_basic_migration(false);
}

#[test]
fn basic_migration_with_service_freeze() {
    test_basic_migration(true);
}

#[derive(Debug, Clone, Copy)]
struct RestartScenario {
    after_initiation: bool,
    after_commitment: bool,
    after_flush: bool,
}

fn check_state_after_restart(
    events: &EventsHandle,
    endpoints_rx: &mut mpsc::Receiver<UpdateEndpoints>,
) {
    let initial_events = events.take();
    assert_eq!(initial_events[0], RuntimeEvent::InitializeRuntime);
    assert_eq!(*initial_events.last().unwrap(), RuntimeEvent::ResumeRuntime);
    let supervisor = ToySupervisorService.default_instance().instance_spec;
    assert!(initial_events.iter().any(|event| match event {
        RuntimeEvent::CommitService(_, spec, InstanceStatus::Active) if *spec == supervisor => true,
        _ => false,
    }));

    let old_spec = CounterFactory::new(VERSIONS[0].parse().unwrap())
        .default_instance()
        .instance_spec;
    let counter_status = initial_events
        .iter()
        .filter_map(|event| match event {
            RuntimeEvent::CommitService(_, spec, status) if *spec == old_spec => Some(status),
            _ => None,
        })
        .next();
    let counter_status = counter_status.expect("No event regarding counter service");
    let is_migrating = match counter_status {
        InstanceStatus::Migrating(_) => true,
        InstanceStatus::Stopped => false,
        other => panic!("Unexpected counter status: {:?}", other),
    };

    // Check that endpoints of the migrating service are on.
    let paths = get_endpoint_paths(endpoints_rx);
    assert!(paths.contains("services/supervisor"));
    assert_eq!(paths.contains("services/counter"), is_migrating);
}

fn test_node_restart_during_migration(scenario: RestartScenario) {
    let db = Arc::new(TemporaryDB::new()) as Arc<dyn Database>;
    let (mut blockchain, ..) = create_runtime(Arc::clone(&db));
    let new_artifact = CounterFactory::new(VERSIONS[2].parse().unwrap()).artifact_id();
    let keypair = KeyPair::random();

    let tx = keypair.increment(CounterFactory::INSTANCE_ID, 1);
    execute_transaction(&mut blockchain, tx).unwrap();

    // Stop the service.
    let tx = keypair.stop_service(
        ToySupervisorService::INSTANCE_ID,
        CounterFactory::INSTANCE_ID,
    );
    execute_transaction(&mut blockchain, tx).unwrap();

    // Start async migration.
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: new_artifact,
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    execute_transaction(&mut blockchain, tx).unwrap();

    if scenario.after_initiation {
        let (new_blockchain, events, mut endpoints_rx) = create_runtime(Arc::clone(&db));
        blockchain = new_blockchain;
        check_state_after_restart(&events, &mut endpoints_rx);
    }

    // Commit migration.
    let commit = CommitMigration::for_counter(&blockchain, 2);
    let tx = keypair.commit_migration(ToySupervisorService::INSTANCE_ID, commit);
    execute_transaction(&mut blockchain, tx).unwrap();

    if scenario.after_commitment {
        let (new_blockchain, events, mut endpoints_rx) = create_runtime(Arc::clone(&db));
        blockchain = new_blockchain;
        check_state_after_restart(&events, &mut endpoints_rx);
    }

    let tx = keypair.flush_migration(
        ToySupervisorService::INSTANCE_ID,
        CounterFactory::INSTANCE_NAME.to_owned(),
    );
    execute_transaction(&mut blockchain, tx).unwrap();

    if scenario.after_flush {
        let (new_blockchain, events, mut endpoints_rx) = create_runtime(Arc::clone(&db));
        blockchain = new_blockchain;
        check_state_after_restart(&events, &mut endpoints_rx);
    }

    // Check that the service data has been updated.
    let snapshot = blockchain.snapshot();
    assert_eq!(
        snapshot.get_proof_entry::<_, u64>("counter.counter").get(),
        Some(2)
    );
}

#[test]
fn node_restart_after_migration_initiation() {
    test_node_restart_during_migration(RestartScenario {
        after_initiation: true,
        after_commitment: false,
        after_flush: false,
    });
}

#[test]
fn node_restart_after_migration_commitment() {
    test_node_restart_during_migration(RestartScenario {
        after_initiation: false,
        after_commitment: true,
        after_flush: false,
    });
}

#[test]
fn node_restart_after_migration_flush() {
    test_node_restart_during_migration(RestartScenario {
        after_initiation: false,
        after_commitment: false,
        after_flush: true,
    });
}

#[test]
fn node_restarts_after_each_migration_step() {
    test_node_restart_during_migration(RestartScenario {
        after_initiation: true,
        after_commitment: true,
        after_flush: true,
    });
}

fn perform_first_migration(blockchain: &mut BlockchainMut, new_artifact: ArtifactId) {
    let keypair = KeyPair::random();
    let tx = keypair.increment(CounterFactory::INSTANCE_ID, 1);
    execute_transaction(blockchain, tx).unwrap();

    // Freeze the service.
    let tx = keypair.freeze_service(
        ToySupervisorService::INSTANCE_ID,
        CounterFactory::INSTANCE_ID,
    );
    execute_transaction(blockchain, tx).unwrap();

    // Start async migration.
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: new_artifact,
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    execute_transaction(blockchain, tx).unwrap();

    // Commit migration.
    let commit = CommitMigration::for_counter(&blockchain, 2);
    let tx = keypair.commit_migration(ToySupervisorService::INSTANCE_ID, commit);
    execute_transaction(blockchain, tx).unwrap();

    // Flush migration.
    let tx = keypair.flush_migration(
        ToySupervisorService::INSTANCE_ID,
        CounterFactory::INSTANCE_NAME.to_owned(),
    );
    execute_transaction(blockchain, tx).unwrap();
}

#[test]
fn two_step_migration_without_intermediate_update() {
    let (mut blockchain, events, mut endpoints_rx) = create_runtime(TemporaryDB::new());
    let keypair = KeyPair::random();
    let new_artifact = CounterFactory::new(VERSIONS[2].parse().unwrap()).artifact_id();
    get_endpoint_paths(&mut endpoints_rx);

    perform_first_migration(&mut blockchain, new_artifact.clone());
    // Since service has transitioned from `Migrating` to `Stopped`, its endpoints should
    // be removed.
    let paths = get_endpoint_paths(&mut endpoints_rx);
    assert!(paths.contains("services/supervisor"));
    assert!(!paths.contains("services/counter"));

    // Start another async migration.
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: new_artifact.clone(),
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    drop(events.take());
    execute_transaction(&mut blockchain, tx).unwrap();
    let mut events_vec = events.take();
    let commit_service_event = events_vec.remove(3);

    assert_eq!(
        events_vec,
        vec![
            RuntimeEvent::BeforeTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::MigrateService(new_artifact.clone(), Version::new(0, 1, 1)),
            RuntimeEvent::AfterTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            // The removed event would be here...
            RuntimeEvent::MigrateService(new_artifact, Version::new(0, 1, 1)),
            RuntimeEvent::AfterCommit(Height(7)),
        ]
    );
    let old_spec = CounterFactory::new(VERSIONS[0].parse().unwrap())
        .default_instance()
        .instance_spec;
    let migration = match commit_service_event {
        RuntimeEvent::CommitService(height, spec, InstanceStatus::Migrating(migration)) => {
            assert_eq!(height, Height(7));
            assert_eq!(spec, old_spec);
            migration
        }
        other => panic!("Unexpected event: {:?}", other),
    };
    assert_eq!(migration.end_version, Version::new(0, 1, 2));
    assert_eq!(migration.completed_hash, None);

    // Since the service is not associated with a deployed artifact, service endpoints
    // should remain switched off.
    assert_no_endpoint_update(&mut endpoints_rx);
}

#[test]
fn two_step_migration_with_intermediate_update() {
    let (mut blockchain, events, mut endpoints_rx) = create_runtime(TemporaryDB::new());
    let keypair = KeyPair::random();
    let new_artifact = CounterFactory::new(VERSIONS[2].parse().unwrap()).artifact_id();
    get_endpoint_paths(&mut endpoints_rx);

    perform_first_migration(&mut blockchain, new_artifact.clone());
    get_endpoint_paths(&mut endpoints_rx); // endpoint removal, as in the previous example.

    // Fast-forward the service to the intermediate artifact.
    let intermediate_factory = CounterFactory::new(Version::new(0, 1, 1));
    let intermediate_artifact = intermediate_factory.artifact_id();
    let intermediate_spec = intermediate_factory.default_instance().instance_spec;
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: intermediate_artifact.clone(),
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);

    drop(events.take());
    execute_transaction(&mut blockchain, tx).unwrap();
    assert_eq!(
        events.take(),
        vec![
            RuntimeEvent::BeforeTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::MigrateService(intermediate_artifact, Version::new(0, 1, 1)),
            RuntimeEvent::AfterTransactions(Height(6), ToySupervisorService::INSTANCE_ID),
            RuntimeEvent::CommitService(Height(7), intermediate_spec, InstanceStatus::Stopped),
            RuntimeEvent::AfterCommit(Height(7)),
        ]
    );

    // Start another async migration.
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: new_artifact,
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    execute_transaction(&mut blockchain, tx).unwrap();

    // Since the service has been associated with a deployed artifact, service endpoints
    // should remain switched on.
    let paths = get_endpoint_paths(&mut endpoints_rx);
    assert!(paths.contains("services/supervisor"));
    assert!(paths.contains("services/counter"));
}

#[test]
fn resume_with_incorrect_artifact_version() {
    let (mut blockchain, ..) = create_runtime(TemporaryDB::new());
    let keypair = KeyPair::random();
    let new_artifact = CounterFactory::new(VERSIONS[2].parse().unwrap()).artifact_id();

    perform_first_migration(&mut blockchain, new_artifact);

    let resume = ResumeService {
        instance_id: CounterFactory::INSTANCE_ID,
        params: vec![],
    };
    let tx = keypair.resume_service(ToySupervisorService::INSTANCE_ID, resume);
    let actual_err = execute_transaction(&mut blockchain, tx).unwrap_err();
    let expected_msg = "Cannot resume service `100:counter` because its data version (0.1.1) \
                        does not match the associated artifact `0:counter:0.1.0`";
    assert_eq!(
        actual_err,
        ErrorMatch::from_fail(&CoreError::CannotResumeService)
            .with_description_containing(expected_msg)
    );

    // Check that the problem is solved by fast-forward migration as the error description suggests.
    let intermediate_factory = CounterFactory::new(Version::new(0, 1, 1));
    let intermediate_artifact = intermediate_factory.artifact_id();
    let migration = MigrateService {
        instance_name: CounterFactory::INSTANCE_NAME.to_owned(),
        artifact: intermediate_artifact,
    };
    let tx = keypair.migrate_service(ToySupervisorService::INSTANCE_ID, migration);
    execute_transaction(&mut blockchain, tx).unwrap();

    let resume = ResumeService {
        instance_id: CounterFactory::INSTANCE_ID,
        params: vec![0], // get different transaction hash
    };
    let tx = keypair.resume_service(ToySupervisorService::INSTANCE_ID, resume);
    execute_transaction(&mut blockchain, tx).unwrap();

    // Check that the service processes transactions.
    let tx = keypair.increment(CounterFactory::INSTANCE_ID, 5);
    execute_transaction(&mut blockchain, tx).unwrap();
}