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
use crate::{
    entities::OpenMessage,
    runtime::{AggregatorRunnerTrait, RuntimeError},
    AggregatorConfig,
};

use anyhow::Context;
use mithril_common::entities::TimePoint;
use mithril_common::logging::LoggerExtensions;
use slog::{info, trace, Logger};
use std::fmt::Display;
use std::sync::Arc;
use tokio::time::sleep;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdleState {
    current_time_point: Option<TimePoint>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReadyState {
    current_time_point: TimePoint,
}

#[derive(Clone, Debug, PartialEq)]
pub struct SigningState {
    current_time_point: TimePoint,
    open_message: OpenMessage,
}

#[derive(Clone, Debug, PartialEq)]
pub enum AggregatorState {
    Idle(IdleState),
    Ready(ReadyState),
    Signing(SigningState),
}

impl Display for AggregatorState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AggregatorState::Idle(state) => write!(
                f,
                "Idle - {}",
                match &state.current_time_point {
                    None => "No TimePoint".to_string(),
                    Some(time_point) => time_point.to_string(),
                }
            ),
            AggregatorState::Ready(state) => write!(f, "Ready - {}", state.current_time_point),
            AggregatorState::Signing(state) => write!(f, "Signing - {}", state.current_time_point),
        }
    }
}

/// The AggregatorRuntime responsibility is to create a state machine to handle
/// all actions required by the process of getting multi-signatures.
/// See the
/// [documentation](https://mithril.network/doc/mithril/mithril-network/aggregator#under-the-hood)
/// for more explanations about the Aggregator state machine.
pub struct AggregatorRuntime {
    config: AggregatorConfig,
    state: AggregatorState,
    runner: Arc<dyn AggregatorRunnerTrait>,
    logger: Logger,
}

impl AggregatorRuntime {
    /// Create a new instance of the state machine.
    pub async fn new(
        aggregator_config: AggregatorConfig,
        init_state: Option<AggregatorState>,
        runner: Arc<dyn AggregatorRunnerTrait>,
        logger: Logger,
    ) -> Result<Self, RuntimeError> {
        let logger = logger.new_with_component_name::<Self>();
        info!(logger, "Initializing runtime");

        let state = if let Some(init_state) = init_state {
            trace!(logger, "Got initial state from caller");
            init_state
        } else {
            trace!(logger, "Idle state, no current time point");
            AggregatorState::Idle(IdleState {
                current_time_point: None,
            })
        };

        Ok(Self {
            config: aggregator_config,
            state,
            runner,
            logger,
        })
    }

    /// Return the actual state of the state machine.
    pub fn get_state(&self) -> String {
        match self.state {
            AggregatorState::Idle(_) => "idle".to_string(),
            AggregatorState::Ready(_) => "ready".to_string(),
            AggregatorState::Signing(_) => "signing".to_string(),
        }
    }

    /// Launches an infinite loop ticking the state machine.
    pub async fn run(&mut self) -> Result<(), RuntimeError> {
        info!(self.logger, "Launching State Machine");

        loop {
            if let Err(e) = self.cycle().await {
                e.write_to_log(&self.logger);
                if e.is_critical() {
                    return Err(e);
                }
            }

            info!(
                self.logger,
                "… Cycle finished, Sleeping for {} ms",
                self.config.interval.as_millis()
            );
            sleep(self.config.interval).await;
        }
    }

    /// Perform one tick of the state machine.
    pub async fn cycle(&mut self) -> Result<(), RuntimeError> {
        info!(
            self.logger,
            "================================================================================"
        );
        info!(self.logger, "new cycle: {}", self.state);

        self.runner
            .increment_runtime_cycle_total_since_startup_counter();

        match self.state.clone() {
            AggregatorState::Idle(state) => {
                let last_time_point = self.runner.get_time_point_from_chain().await.with_context(
                    || "AggregatorRuntime in the state IDLE can not get current time point from chain",
                )?;

                info!(self.logger, "→ Trying to transition to READY"; "last_time_point" => ?last_time_point);

                self.try_transition_from_idle_to_ready(
                    state.current_time_point,
                    last_time_point.clone(),
                )
                .await?;
                self.state = AggregatorState::Ready(ReadyState {
                    current_time_point: last_time_point,
                });
            }
            AggregatorState::Ready(state) => {
                let last_time_point: TimePoint = self
                    .runner
                    .get_time_point_from_chain()
                    .await
                    .with_context(|| {
                        "AggregatorRuntime in the state READY can not get current time point from chain"
                    })?;

                if state.current_time_point.epoch < last_time_point.epoch {
                    // transition READY > IDLE
                    info!(self.logger, "→ Epoch has changed, transitioning to IDLE"; "last_time_point" => ?last_time_point);
                    self.state = AggregatorState::Idle(IdleState {
                        current_time_point: Some(state.current_time_point),
                    });
                } else if let Some(open_message) = self
                    .runner
                    .get_current_non_certified_open_message(&last_time_point)
                    .await
                    .with_context(|| "AggregatorRuntime can not get the current open message")?
                {
                    // transition READY > SIGNING
                    info!(self.logger, "→ Transitioning to SIGNING");
                    let new_state = self
                        .transition_from_ready_to_signing(last_time_point.clone(), open_message.clone())
                        .await.with_context(|| format!("AggregatorRuntime can not perform a transition from READY state to SIGNING with entity_type: '{:?}'", open_message.signed_entity_type))?;
                    self.state = AggregatorState::Signing(new_state);
                } else {
                    // READY > READY
                    info!(
                        self.logger, " ⋅ No open message to certify, waiting…";
                        "time_point" => ?state.current_time_point
                    );
                    self.state = AggregatorState::Ready(ReadyState {
                        current_time_point: last_time_point,
                    });
                }
            }
            AggregatorState::Signing(state) => {
                let last_time_point: TimePoint =
                    self.runner.get_time_point_from_chain().await.with_context(|| {
                        "AggregatorRuntime in the state SIGNING can not get current time point from chain"
                    })?;

                let is_outdated = self
                    .runner
                    .is_open_message_outdated(
                        state.open_message.signed_entity_type.clone(),
                        &last_time_point,
                    )
                    .await?;

                if state.current_time_point.epoch < last_time_point.epoch {
                    // SIGNING > IDLE
                    info!(self.logger, "→ Epoch changed, transitioning to IDLE");
                    let new_state = self.transition_from_signing_to_idle(state).await?;
                    self.state = AggregatorState::Idle(new_state);
                } else if is_outdated {
                    // SIGNING > READY
                    info!(
                        self.logger,
                        "→ Open message changed, transitioning to READY"
                    );
                    let new_state = self
                        .transition_from_signing_to_ready_new_open_message(state)
                        .await?;
                    self.state = AggregatorState::Ready(new_state);
                } else {
                    // SIGNING > READY
                    let new_state = self
                        .transition_from_signing_to_ready_multisignature(state)
                        .await?;
                    info!(self.logger, "→ A multi-signature has been created, build an artifact & a certificate and transitioning back to READY");
                    self.state = AggregatorState::Ready(new_state);
                }
            }
        }

        self.runner
            .increment_runtime_cycle_success_since_startup_counter();

        Ok(())
    }

    /// Perform a transition from `IDLE` state to `READY` state when
    /// the certificate chain is valid.
    async fn try_transition_from_idle_to_ready(
        &mut self,
        maybe_current_time_point: Option<TimePoint>,
        new_time_point: TimePoint,
    ) -> Result<(), RuntimeError> {
        trace!(self.logger, "Trying transition from IDLE to READY state");

        if maybe_current_time_point.is_none()
            || maybe_current_time_point.as_ref().unwrap().epoch < new_time_point.epoch
        {
            self.runner.close_signer_registration_round().await?;
            self.runner
                .update_era_checker(new_time_point.epoch)
                .await
                .map_err(|e| RuntimeError::critical("transiting IDLE → READY", Some(e)))?;
            self.runner
                .update_stake_distribution(&new_time_point)
                .await?;
            self.runner.inform_new_epoch(new_time_point.epoch).await?;
            self.runner.upkeep(new_time_point.epoch).await?;
            self.runner
                .open_signer_registration_round(&new_time_point)
                .await?;
            self.runner.update_epoch_settings().await?;
            self.runner.precompute_epoch_data().await?;
        }

        self.runner
            .is_certificate_chain_valid(&new_time_point)
            .await
            .map_err(|e| RuntimeError::KeepState {
                message: "certificate chain is invalid".to_string(),
                nested_error: e.into(),
            })?;

        Ok(())
    }

    /// Perform a transition from `SIGNING` state to `READY` state when a new
    /// multi-signature is issued.
    async fn transition_from_signing_to_ready_multisignature(
        &self,
        state: SigningState,
    ) -> Result<ReadyState, RuntimeError> {
        trace!(
            self.logger,
            "Launching transition from SIGNING to READY state"
        );
        let certificate = self
            .runner
            .create_certificate(&state.open_message.signed_entity_type)
            .await?
            .ok_or_else(|| RuntimeError::KeepState {
                message: "not enough signature yet to create a certificate, waiting…".to_string(),
                nested_error: None,
            })?;
        self.runner
            .drop_pending_certificate()
            .await
            .map_err(|e| RuntimeError::ReInit {
                message: "transiting SIGNING → READY: failed to drop pending certificate"
                    .to_string(),
                nested_error: Some(e),
            })?;
        self.runner
            .create_artifact(&state.open_message.signed_entity_type, &certificate)
            .await
            .map_err(|e| RuntimeError::ReInit {
                message: "transiting SIGNING → READY: failed to create artifact. Retrying…"
                    .to_string(),
                nested_error: Some(e),
            })?;

        Ok(ReadyState {
            current_time_point: state.current_time_point,
        })
    }

    /// Perform a transition from `SIGNING` state to `IDLE` state when a new
    /// epoch is detected.
    async fn transition_from_signing_to_idle(
        &self,
        state: SigningState,
    ) -> Result<IdleState, RuntimeError> {
        trace!(
            self.logger,
            "Launching transition from SIGNING to IDLE state"
        );
        self.runner.drop_pending_certificate().await?;

        Ok(IdleState {
            current_time_point: Some(state.current_time_point),
        })
    }

    /// Perform a transition from `SIGNING` state to `READY` state when a new
    /// open message is detected.
    async fn transition_from_signing_to_ready_new_open_message(
        &self,
        state: SigningState,
    ) -> Result<ReadyState, RuntimeError> {
        trace!(
            self.logger,
            "Launching transition from SIGNING to READY state"
        );
        self.runner.drop_pending_certificate().await?;

        Ok(ReadyState {
            current_time_point: state.current_time_point,
        })
    }

    /// Perform a transition from `READY` state to `SIGNING` state when a new
    /// open message is opened.
    async fn transition_from_ready_to_signing(
        &mut self,
        new_time_point: TimePoint,
        open_message: OpenMessage,
    ) -> Result<SigningState, RuntimeError> {
        trace!(
            self.logger,
            "Launching transition from READY to SIGNING state"
        );

        let certificate_pending = self
            .runner
            .create_new_pending_certificate(
                new_time_point.clone(),
                &open_message.signed_entity_type,
            )
            .await?;
        self.runner
            .save_pending_certificate(certificate_pending.clone())
            .await?;
        let state = SigningState {
            current_time_point: new_time_point,
            open_message,
        };

        Ok(state)
    }
}

#[cfg(test)]
mod tests {
    use crate::entities::OpenMessage;
    use anyhow::anyhow;
    use mockall::predicate;
    use std::time::Duration;

    use mithril_common::test_utils::fake_data;

    use crate::test_tools::TestLogger;

    use super::super::runner::MockAggregatorRunner;
    use super::*;

    async fn init_runtime(
        init_state: Option<AggregatorState>,
        runner: MockAggregatorRunner,
    ) -> AggregatorRuntime {
        AggregatorRuntime::new(
            AggregatorConfig::new(Duration::from_millis(20)),
            init_state,
            Arc::new(runner),
            TestLogger::stdout(),
        )
        .await
        .unwrap()
    }

    #[tokio::test]
    pub async fn idle_check_certificate_chain_is_not_valid() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_update_stake_distribution()
            .with(predicate::eq(TimePoint::dummy()))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_close_signer_registration_round()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_open_signer_registration_round()
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_is_certificate_chain_valid()
            .once()
            .returning(|_| Err(anyhow!("error")));
        runner
            .expect_update_era_checker()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_inform_new_epoch()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_update_epoch_settings()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_precompute_epoch_data()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_upkeep()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .never();

        let mut runtime = init_runtime(
            Some(AggregatorState::Idle(IdleState {
                current_time_point: None,
            })),
            runner,
        )
        .await;
        let err = runtime.cycle().await.unwrap_err();
        assert!(matches!(err, RuntimeError::KeepState { .. }));

        assert_eq!("idle".to_string(), runtime.get_state());
    }

    #[tokio::test]
    pub async fn idle_check_certificate_chain_is_valid() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_update_stake_distribution()
            .with(predicate::eq(TimePoint::dummy()))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_close_signer_registration_round()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_open_signer_registration_round()
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_is_certificate_chain_valid()
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_update_era_checker()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_inform_new_epoch()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_update_epoch_settings()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_precompute_epoch_data()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_upkeep()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());

        let mut runtime = init_runtime(
            Some(AggregatorState::Idle(IdleState {
                current_time_point: None,
            })),
            runner,
        )
        .await;
        runtime.cycle().await.unwrap();

        assert_eq!("ready".to_string(), runtime.get_state());
    }

    #[tokio::test]
    pub async fn ready_new_epoch_detected() {
        let mut runner = MockAggregatorRunner::new();
        let time_point = TimePoint::dummy();
        let new_time_point = TimePoint {
            epoch: time_point.epoch + 1,
            ..time_point.clone()
        };
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(move || Ok(new_time_point.clone()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());
        let mut runtime = init_runtime(
            Some(AggregatorState::Ready(ReadyState {
                current_time_point: time_point,
            })),
            runner,
        )
        .await;
        runtime.cycle().await.unwrap();

        assert_eq!("idle".to_string(), runtime.get_state());
    }

    #[tokio::test]
    pub async fn ready_open_message_not_exist() {
        let mut runner = MockAggregatorRunner::new();
        let time_point = TimePoint::dummy();
        let next_time_point = TimePoint {
            immutable_file_number: time_point.immutable_file_number + 1,
            ..time_point.clone()
        };
        let expected_time_point = next_time_point.clone();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(move || Ok(next_time_point.clone()));
        runner
            .expect_get_current_non_certified_open_message()
            .once()
            .returning(|_| Ok(None));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());
        let mut runtime = init_runtime(
            Some(AggregatorState::Ready(ReadyState {
                current_time_point: time_point.clone(),
            })),
            runner,
        )
        .await;
        runtime.cycle().await.unwrap();

        assert_eq!("ready".to_string(), runtime.get_state());
        assert_eq!(
            AggregatorState::Ready(ReadyState {
                current_time_point: expected_time_point,
            }),
            runtime.state
        );
    }

    #[tokio::test]
    pub async fn ready_certificate_does_not_exist_for_time_point() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_get_current_non_certified_open_message()
            .once()
            .returning(|_| {
                let open_message = OpenMessage {
                    is_certified: false,
                    ..OpenMessage::dummy()
                };
                Ok(Some(open_message))
            });
        runner
            .expect_create_new_pending_certificate()
            .once()
            .returning(|_, _| Ok(fake_data::certificate_pending()));
        runner
            .expect_save_pending_certificate()
            .once()
            .returning(|_| Ok(()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());

        let mut runtime = init_runtime(
            Some(AggregatorState::Ready(ReadyState {
                current_time_point: TimePoint::dummy(),
            })),
            runner,
        )
        .await;
        runtime.cycle().await.unwrap();

        assert_eq!("signing".to_string(), runtime.get_state());
    }

    #[tokio::test]
    async fn signing_changing_open_message_to_ready() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_is_open_message_outdated()
            .once()
            .returning(|_, _| Ok(true));
        runner
            .expect_drop_pending_certificate()
            .once()
            .returning(|| Ok(Some(fake_data::certificate_pending())));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());

        let initial_state = AggregatorState::Signing(SigningState {
            current_time_point: TimePoint::dummy(),
            open_message: OpenMessage::dummy(),
        });

        let mut runtime = init_runtime(Some(initial_state), runner).await;
        runtime.cycle().await.unwrap();

        assert_eq!("ready".to_string(), runtime.get_state());
    }

    #[tokio::test]
    async fn signing_certificate_is_not_created() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_is_open_message_outdated()
            .once()
            .returning(|_, _| Ok(false));
        runner
            .expect_create_certificate()
            .once()
            .returning(|_| Ok(None));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .never();
        let state = SigningState {
            current_time_point: TimePoint::dummy(),
            open_message: OpenMessage::dummy(),
        };
        let mut runtime = init_runtime(Some(AggregatorState::Signing(state)), runner).await;
        let err = runtime
            .cycle()
            .await
            .expect_err("cycle should have returned an error");

        match err {
            RuntimeError::KeepState { .. } => (),
            _ => panic!("KeepState error expected, got {err:?}."),
        };

        assert_eq!("signing".to_string(), runtime.get_state());
    }

    #[tokio::test]
    async fn signing_artifact_not_created() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_is_open_message_outdated()
            .once()
            .returning(|_, _| Ok(false));
        runner
            .expect_create_certificate()
            .return_once(move |_| Ok(Some(fake_data::certificate("whatever".to_string()))));
        runner
            .expect_drop_pending_certificate()
            .once()
            .returning(|| Ok(Some(fake_data::certificate_pending())));
        runner
            .expect_create_artifact()
            .once()
            .returning(|_, _| Err(anyhow!("whatever")));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .never();
        let state = SigningState {
            current_time_point: TimePoint::dummy(),
            open_message: OpenMessage::dummy(),
        };
        let mut runtime = init_runtime(Some(AggregatorState::Signing(state)), runner).await;
        let err = runtime
            .cycle()
            .await
            .expect_err("cycle should have returned an error");

        match err {
            RuntimeError::ReInit { .. } => (),
            _ => panic!("ReInit error expected, got {err:?}."),
        };

        assert_eq!("signing".to_string(), runtime.get_state());
    }

    #[tokio::test]
    async fn signing_certificate_is_created() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_is_open_message_outdated()
            .once()
            .returning(|_, _| Ok(false));
        runner
            .expect_create_certificate()
            .return_once(move |_| Ok(Some(fake_data::certificate("whatever".to_string()))));
        runner
            .expect_drop_pending_certificate()
            .once()
            .returning(|| Ok(Some(fake_data::certificate_pending())));
        runner
            .expect_create_artifact()
            .once()
            .returning(|_, _| Ok(()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .once()
            .returning(|| ());

        let state = SigningState {
            current_time_point: TimePoint::dummy(),
            open_message: OpenMessage::dummy(),
        };
        let mut runtime = init_runtime(Some(AggregatorState::Signing(state)), runner).await;
        runtime.cycle().await.unwrap();

        assert_eq!("ready".to_string(), runtime.get_state());
    }

    #[tokio::test]
    pub async fn critical_error() {
        let mut runner = MockAggregatorRunner::new();
        runner
            .expect_get_time_point_from_chain()
            .once()
            .returning(|| Ok(TimePoint::dummy()));
        runner
            .expect_update_era_checker()
            .with(predicate::eq(TimePoint::dummy().epoch))
            .once()
            .returning(|_| Err(anyhow!("ERROR")));
        runner
            .expect_close_signer_registration_round()
            .once()
            .returning(|| Ok(()));
        runner
            .expect_increment_runtime_cycle_total_since_startup_counter()
            .once()
            .returning(|| ());
        runner
            .expect_increment_runtime_cycle_success_since_startup_counter()
            .never();

        let mut runtime = init_runtime(
            Some(AggregatorState::Idle(IdleState {
                current_time_point: None,
            })),
            runner,
        )
        .await;
        runtime.cycle().await.unwrap_err();

        assert_eq!("idle".to_string(), runtime.get_state());
    }
}