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
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use slog::{debug, warn, Logger};
use std::sync::Arc;
use std::time::Duration;

use mithril_common::entities::{
    Certificate, CertificatePending, Epoch, ProtocolMessage, SignedEntityType, Signer, TimePoint,
};
use mithril_common::logging::LoggerExtensions;
use mithril_common::StdResult;
use mithril_persistence::store::StakeStorer;

use crate::entities::OpenMessage;
use crate::DependencyContainer;

/// Configuration structure dedicated to the AggregatorRuntime.
#[derive(Debug, Clone)]
pub struct AggregatorConfig {
    /// Interval between each snapshot, in ms
    pub interval: Duration,
}

impl AggregatorConfig {
    /// Create a new instance of AggregatorConfig.
    pub fn new(interval: Duration) -> Self {
        Self { interval }
    }
}

/// This trait is intended to allow mocking the AggregatorRunner in tests.
/// It exposes all the methods needed by the state machine.
#[async_trait]
pub trait AggregatorRunnerTrait: Sync + Send {
    /// Return the current [TimePoint] from the chain
    async fn get_time_point_from_chain(&self) -> StdResult<TimePoint>;

    /// Retrieves the current open message for a given signed entity type.
    async fn get_current_open_message_for_signed_entity_type(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<OpenMessage>>;

    /// Retrieves the current non-certified open message.
    async fn get_current_non_certified_open_message(
        &self,
        current_time_point: &TimePoint,
    ) -> StdResult<Option<OpenMessage>>;

    /// Check if a certificate chain is valid.
    async fn is_certificate_chain_valid(&self, time_point: &TimePoint) -> StdResult<()>;

    /// Read the stake distribution from the blockchain and store it.
    async fn update_stake_distribution(&self, new_time_point: &TimePoint) -> StdResult<()>;

    /// Open the signer registration round of an epoch.
    async fn open_signer_registration_round(&self, new_time_point: &TimePoint) -> StdResult<()>;

    /// Close the signer registration round of an epoch.
    async fn close_signer_registration_round(&self) -> StdResult<()>;

    /// Ask the EpochService to update the epoch settings.
    async fn update_epoch_settings(&self) -> StdResult<()>;

    /// Compute the protocol message
    async fn compute_protocol_message(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<ProtocolMessage>;

    /// Mark expired open message.
    async fn mark_open_message_if_expired(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<OpenMessage>>;

    /// Create a new pending certificate.
    async fn create_new_pending_certificate(
        &self,
        time_point: TimePoint,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<CertificatePending>;

    /// Store the given pending certificate.
    async fn save_pending_certificate(
        &self,
        pending_certificate: CertificatePending,
    ) -> StdResult<()>;

    /// Drop the actual pending certificate in the store.
    async fn drop_pending_certificate(&self) -> StdResult<Option<CertificatePending>>;

    /// Tell the certifier to try to create a new certificate.
    async fn create_certificate(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<Certificate>>;

    /// Create an artifact and persist it.
    async fn create_artifact(
        &self,
        signed_entity_type: &SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<()>;

    /// Update the EraChecker with EraReader information.
    async fn update_era_checker(&self, epoch: Epoch) -> StdResult<()>;

    /// Ask services to update themselves for the new epoch
    async fn inform_new_epoch(&self, epoch: Epoch) -> StdResult<()>;

    /// Perform the upkeep tasks.
    async fn upkeep(&self, epoch: Epoch) -> StdResult<()>;

    /// Precompute what doesn't change for the actual epoch
    async fn precompute_epoch_data(&self) -> StdResult<()>;

    /// Create new open message
    async fn create_open_message(
        &self,
        signed_entity_type: &SignedEntityType,
        protocol_message: &ProtocolMessage,
    ) -> StdResult<OpenMessage>;

    /// Checks if the open message is considered outdated.
    async fn is_open_message_outdated(
        &self,
        open_message_signed_entity_type: SignedEntityType,
        last_time_point: &TimePoint,
    ) -> StdResult<bool>;

    /// Increment the runtime cycle success metric.
    fn increment_runtime_cycle_success_since_startup_counter(&self);

    /// Increment the runtime cycle total metric.
    fn increment_runtime_cycle_total_since_startup_counter(&self);
}

/// The runner responsibility is to expose a code API for the state machine. It
/// holds services and configuration.
pub struct AggregatorRunner {
    dependencies: Arc<DependencyContainer>,
    logger: Logger,
}

impl AggregatorRunner {
    /// Create a new instance of the Aggregator Runner.
    pub fn new(dependencies: Arc<DependencyContainer>) -> Self {
        let logger = dependencies.root_logger.new_with_component_name::<Self>();
        Self {
            dependencies,
            logger,
        }
    }

    async fn list_available_signed_entity_types(
        &self,
        time_point: &TimePoint,
    ) -> StdResult<Vec<SignedEntityType>> {
        let signed_entity_types = self
            .dependencies
            .epoch_service
            .read()
            .await
            .signed_entity_config()?
            .list_allowed_signed_entity_types(time_point)?;
        let unlocked_signed_entities = self
            .dependencies
            .signed_entity_type_lock
            .filter_unlocked_entries(signed_entity_types)
            .await;

        Ok(unlocked_signed_entities)
    }

    fn increment_artifact_total_produced_metric_since_startup(
        &self,
        signed_entity_type: &SignedEntityType,
    ) {
        let metrics = self.dependencies.metrics_service.clone();
        let metric_counter = match signed_entity_type {
            SignedEntityType::MithrilStakeDistribution(_) => {
                metrics.get_artifact_mithril_stake_distribution_total_produced_since_startup()
            }
            SignedEntityType::CardanoImmutableFilesFull(_) => {
                metrics.get_artifact_cardano_db_total_produced_since_startup()
            }
            SignedEntityType::CardanoStakeDistribution(_) => {
                metrics.get_artifact_cardano_stake_distribution_total_produced_since_startup()
            }
            SignedEntityType::CardanoTransactions(_, _) => {
                metrics.get_artifact_cardano_transaction_total_produced_since_startup()
            }
        };

        metric_counter.increment();
    }
}

#[cfg_attr(test, mockall::automock)]
#[async_trait]
impl AggregatorRunnerTrait for AggregatorRunner {
    /// Return the current time point from the chain
    async fn get_time_point_from_chain(&self) -> StdResult<TimePoint> {
        debug!(self.logger, ">> get_time_point_from_chain");
        let time_point = self
            .dependencies
            .ticker_service
            .get_current_time_point()
            .await?;

        Ok(time_point)
    }

    async fn get_current_open_message_for_signed_entity_type(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<OpenMessage>> {
        debug!(self.logger,">> get_current_open_message_for_signed_entity_type"; "signed_entity_type" => ?signed_entity_type);
        self.mark_open_message_if_expired(signed_entity_type)
            .await?;

        Ok(self
            .dependencies
            .certifier_service
            .get_open_message(signed_entity_type)
            .await
            .with_context(|| format!("CertifierService can not get open message for signed_entity_type: '{signed_entity_type}'"))?)
    }

    async fn get_current_non_certified_open_message(
        &self,
        current_time_point: &TimePoint,
    ) -> StdResult<Option<OpenMessage>> {
        debug!(self.logger,">> get_current_non_certified_open_message"; "time_point" => #?current_time_point);
        let signed_entity_types = self
            .list_available_signed_entity_types(current_time_point)
            .await?;

        for signed_entity_type in signed_entity_types {
            let current_open_message = self.get_current_open_message_for_signed_entity_type(&signed_entity_type)
                .await
                .with_context(|| format!("AggregatorRunner can not get current open message for signed entity type: '{}'", &signed_entity_type))?;
            match current_open_message {
                None => {
                    let protocol_message = self.compute_protocol_message(&signed_entity_type).await.with_context(|| format!("AggregatorRunner can not compute protocol message for signed_entity_type: '{signed_entity_type}'"))?;
                    let open_message_new = self.create_open_message(&signed_entity_type, &protocol_message)
                        .await
                        .with_context(|| format!("AggregatorRunner can not create open message for signed_entity_type: '{signed_entity_type}'"))?;

                    return Ok(Some(open_message_new));
                }
                Some(open_message) => {
                    if !open_message.is_certified && !open_message.is_expired {
                        return Ok(Some(open_message));
                    }
                }
            }
        }

        Ok(None)
    }

    async fn is_certificate_chain_valid(&self, time_point: &TimePoint) -> StdResult<()> {
        debug!(self.logger, ">> is_certificate_chain_valid");
        self.dependencies
            .certifier_service
            .verify_certificate_chain(time_point.epoch)
            .await?;

        Ok(())
    }

    async fn update_stake_distribution(&self, new_time_point: &TimePoint) -> StdResult<()> {
        debug!(self.logger,">> update_stake_distribution"; "time_point" => #?new_time_point);
        self.dependencies
            .stake_distribution_service
            .update_stake_distribution()
            .await
            .with_context(|| format!("AggregatorRunner could not update stake distribution for time_point: '{new_time_point}'"))
    }

    async fn open_signer_registration_round(&self, new_time_point: &TimePoint) -> StdResult<()> {
        debug!(self.logger,">> open_signer_registration_round"; "time_point" => #?new_time_point);
        let registration_epoch = new_time_point.epoch.offset_to_recording_epoch();

        let stakes = self
            .dependencies
            .stake_store
            .get_stakes(registration_epoch)
            .await?
            .unwrap_or_default();

        self.dependencies
            .signer_registration_round_opener
            .open_registration_round(registration_epoch, stakes)
            .await
    }

    async fn close_signer_registration_round(&self) -> StdResult<()> {
        debug!(self.logger, ">> close_signer_registration_round");
        self.dependencies
            .signer_registration_round_opener
            .close_registration_round()
            .await
    }

    async fn update_epoch_settings(&self) -> StdResult<()> {
        debug!(self.logger, ">> update_epoch_settings");
        self.dependencies
            .epoch_service
            .write()
            .await
            .update_epoch_settings()
            .await
    }

    async fn compute_protocol_message(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<ProtocolMessage> {
        debug!(self.logger, ">> compute_protocol_message");
        let protocol_message = self
            .dependencies
            .signable_builder_service
            .compute_protocol_message(signed_entity_type.to_owned())
            .await
            .with_context(|| format!("Runner can not compute protocol message for signed entity type: '{signed_entity_type}'"))?;

        Ok(protocol_message)
    }

    async fn mark_open_message_if_expired(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<OpenMessage>> {
        debug!(self.logger, ">> mark_open_message_if_expired");
        let expired_open_message = self
            .dependencies
            .certifier_service
            .mark_open_message_if_expired(signed_entity_type)
            .await
            .with_context(|| "CertifierService can not mark expired open message")?;

        debug!(
            self.logger, "Marked expired open messages";
            "expired_open_message" => ?expired_open_message
        );

        Ok(expired_open_message)
    }

    async fn create_new_pending_certificate(
        &self,
        time_point: TimePoint,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<CertificatePending> {
        debug!(self.logger, ">> create_new_pending_certificate"; "signed_entity_type" => ?signed_entity_type);
        let epoch_service = self.dependencies.epoch_service.read().await;

        let signers = epoch_service.current_signers_with_stake()?;
        let next_signers = epoch_service.next_signers_with_stake()?;

        let protocol_parameters = epoch_service.next_protocol_parameters().with_context(|| {
            format!("no current protocol parameters found for time point {time_point:?}")
        })?;
        let signer_registration_protocol_parameters = epoch_service
            .signer_registration_protocol_parameters()
            .with_context(|| {
                format!("no signer registration protocol parameters found for time point {time_point:?}")
            })?;

        let pending_certificate = CertificatePending::new(
            time_point.epoch,
            signed_entity_type.to_owned(),
            protocol_parameters.clone(),
            signer_registration_protocol_parameters.clone(),
            Signer::vec_from(signers.clone()),
            Signer::vec_from(next_signers.clone()),
        );

        Ok(pending_certificate)
    }

    async fn save_pending_certificate(
        &self,
        pending_certificate: CertificatePending,
    ) -> StdResult<()> {
        debug!(self.logger, ">> save_pending_certificate");
        let signed_entity_type = pending_certificate.signed_entity_type.clone();
        self.dependencies
            .certificate_pending_store
            .save(pending_certificate)
            .await
            .map_err(|e| anyhow!(e))
            .with_context(|| format!("CertificatePendingStore can not save pending certificate with signed_entity_type: '{signed_entity_type}'"))
    }

    async fn drop_pending_certificate(&self) -> StdResult<Option<CertificatePending>> {
        debug!(self.logger, ">> drop_pending_certificate");
        let certificate_pending = self.dependencies.certificate_pending_store.remove().await?;
        if certificate_pending.is_none() {
            warn!(self.logger," > drop_pending_certificate::no certificate pending in store, did the previous loop crashed ?");
        }

        Ok(certificate_pending)
    }

    async fn create_certificate(
        &self,
        signed_entity_type: &SignedEntityType,
    ) -> StdResult<Option<Certificate>> {
        debug!(self.logger, ">> create_certificate"; "signed_entity_type" => ?signed_entity_type);

        let certificate = self.dependencies
            .certifier_service
            .create_certificate(signed_entity_type)
            .await
            .with_context(|| {
                format!(
                    "CertifierService can not create certificate for signed_entity_type: '{signed_entity_type}'"
                )
            })?;

        if certificate.is_some() {
            self.dependencies
                .metrics_service
                .get_certificate_total_produced_since_startup()
                .increment();
        }

        Ok(certificate)
    }

    async fn create_artifact(
        &self,
        signed_entity_type: &SignedEntityType,
        certificate: &Certificate,
    ) -> StdResult<()> {
        debug!(
            self.logger, ">> create_artifact";
            "signed_entity_type" => ?signed_entity_type,
            "certificate_hash" => &certificate.hash
        );

        self.dependencies
            .signed_entity_service
            .create_artifact(signed_entity_type.to_owned(), certificate)
            .await
            .with_context(|| {
                format!(
                    "SignedEntityService can not create artifact for signed_entity_type: '{signed_entity_type}' with certificate hash: '{}'",
                    certificate.hash
                )
            })?;

        self.increment_artifact_total_produced_metric_since_startup(signed_entity_type);

        Ok(())
    }

    async fn update_era_checker(&self, epoch: Epoch) -> StdResult<()> {
        debug!(self.logger, ">> update_era_checker({epoch:?})");
        let token = self
            .dependencies
            .era_reader
            .read_era_epoch_token(epoch)
            .await
            .with_context(|| {
                format!(
                    "EraReader can not get era epoch token for current epoch: '{}'",
                    epoch
                )
            })?;

        let current_era = token
            .get_current_supported_era()
            .with_context(|| "EraEpochToken can not get current supported era")?;
        self.dependencies
            .era_checker
            .change_era(current_era, token.get_current_epoch());
        debug!(
            self.logger,
            "Current Era is {current_era} (Epoch {}).",
            token.get_current_epoch()
        );

        if token.get_next_supported_era().is_err() {
            let era_name = &token.get_next_era_marker().unwrap().name;
            warn!(self.logger,"Upcoming Era '{era_name}' is not supported by this version of the software. Please update!");
        }

        Ok(())
    }

    async fn precompute_epoch_data(&self) -> StdResult<()> {
        debug!(self.logger, ">> precompute_epoch_data");
        self.dependencies
            .epoch_service
            .write()
            .await
            .precompute_epoch_data()
            .await?;

        Ok(())
    }

    async fn inform_new_epoch(&self, epoch: Epoch) -> StdResult<()> {
        debug!(self.logger, ">> inform_new_epoch({epoch:?})");
        self.dependencies
            .certifier_service
            .inform_epoch(epoch)
            .await?;

        self.dependencies
            .epoch_service
            .write()
            .await
            .inform_epoch(epoch)
            .await?;

        Ok(())
    }

    async fn upkeep(&self, epoch: Epoch) -> StdResult<()> {
        debug!(self.logger, ">> upkeep");
        self.dependencies.upkeep_service.run(epoch).await
    }

    async fn create_open_message(
        &self,
        signed_entity_type: &SignedEntityType,
        protocol_message: &ProtocolMessage,
    ) -> StdResult<OpenMessage> {
        debug!(self.logger, ">> create_open_message");
        self.dependencies
            .certifier_service
            .create_open_message(signed_entity_type, protocol_message)
            .await
    }

    async fn is_open_message_outdated(
        &self,
        open_message_signed_entity_type: SignedEntityType,
        last_time_point: &TimePoint,
    ) -> StdResult<bool> {
        let current_open_message = self
            .get_current_open_message_for_signed_entity_type(
                &open_message_signed_entity_type,
            )
            .await
            .with_context(|| format!("AggregatorRuntime can not get the current open message for signed entity type: '{}'", &open_message_signed_entity_type))?;
        let is_expired_open_message = current_open_message
            .as_ref()
            .map(|om| om.is_expired)
            .unwrap_or(false);

        let exists_newer_open_message = {
            let new_signed_entity_type = self
                .dependencies
                .epoch_service
                .read()
                .await
                .signed_entity_config()?
                .time_point_to_signed_entity(&open_message_signed_entity_type, last_time_point)?;
            new_signed_entity_type != open_message_signed_entity_type
        };

        Ok(exists_newer_open_message || is_expired_open_message)
    }

    fn increment_runtime_cycle_success_since_startup_counter(&self) {
        self.dependencies
            .metrics_service
            .get_runtime_cycle_success_since_startup()
            .increment();
    }

    fn increment_runtime_cycle_total_since_startup_counter(&self) {
        self.dependencies
            .metrics_service
            .get_runtime_cycle_total_since_startup()
            .increment();
    }
}

#[cfg(test)]
pub mod tests {
    use crate::dependency_injection::DependenciesBuilder;
    use crate::entities::AggregatorEpochSettings;
    use crate::services::{FakeEpochService, FakeEpochServiceBuilder, MockUpkeepService};
    use crate::{
        entities::OpenMessage,
        initialize_dependencies,
        runtime::{AggregatorRunner, AggregatorRunnerTrait},
        services::{MithrilStakeDistributionService, MockCertifierService},
        Configuration, DependencyContainer, MithrilSignerRegisterer, SignerRegistrationRound,
    };
    use async_trait::async_trait;
    use chrono::{DateTime, Utc};
    use mithril_common::entities::{
        CardanoTransactionsSigningConfig, ChainPoint, Epoch, SignedEntityConfig,
        SignedEntityTypeDiscriminants,
    };
    use mithril_common::signed_entity_type_lock::SignedEntityTypeLock;
    use mithril_common::{
        chain_observer::FakeObserver,
        digesters::DumbImmutableFileObserver,
        entities::{
            CertificatePending, ProtocolMessage, SignedEntityType, Signer, StakeDistribution,
            TimePoint,
        },
        signable_builder::SignableBuilderService,
        test_utils::{fake_data, MithrilFixtureBuilder},
        MithrilTickerService, StdResult,
    };
    use mithril_persistence::store::StakeStorer;
    use mockall::predicate::eq;
    use mockall::{mock, Sequence};
    use std::sync::Arc;
    use tokio::sync::RwLock;

    mock! {
        SignableBuilderServiceImpl { }

        #[async_trait]
        impl SignableBuilderService for SignableBuilderServiceImpl
        {

            async fn compute_protocol_message(
                &self,
                signed_entity_type: SignedEntityType,
            ) -> StdResult<ProtocolMessage>;
        }
    }

    async fn build_runner_with_fixture_data(deps: DependencyContainer) -> AggregatorRunner {
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let current_epoch = deps
            .chain_observer
            .get_current_epoch()
            .await
            .unwrap()
            .unwrap();
        deps.init_state_from_fixture(
            &fixture,
            &[
                current_epoch.offset_to_signer_retrieval_epoch().unwrap(),
                current_epoch,
                current_epoch.next(),
            ],
        )
        .await;

        AggregatorRunner::new(Arc::new(deps))
    }

    async fn build_runner(mock_certifier_service: MockCertifierService) -> AggregatorRunner {
        let mut deps = initialize_dependencies().await;
        deps.certifier_service = Arc::new(mock_certifier_service);

        let mut mock_signable_builder_service = MockSignableBuilderServiceImpl::new();
        mock_signable_builder_service
            .expect_compute_protocol_message()
            .return_once(|_| Ok(ProtocolMessage::default()));
        deps.signable_builder_service = Arc::new(mock_signable_builder_service);

        let runner = build_runner_with_fixture_data(deps).await;

        let current_epoch = runner
            .dependencies
            .ticker_service
            .get_current_epoch()
            .await
            .unwrap();
        runner.inform_new_epoch(current_epoch).await.unwrap();
        runner.precompute_epoch_data().await.unwrap();
        runner
    }

    fn init_certifier_service_mock(
        mock_certifier_service: &mut MockCertifierService,
        messages: Vec<OpenMessage>,
    ) {
        for message in messages {
            mock_certifier_service
                .expect_get_open_message()
                .return_once(|_| Ok(Some(message)))
                .times(1);
        }
        // When all messages are retrieved, the function return None
        mock_certifier_service
            .expect_get_open_message()
            .returning(|_| Ok(None));

        mock_certifier_service
            .expect_inform_epoch()
            .return_once(|_| Ok(()));
        mock_certifier_service
            .expect_mark_open_message_if_expired()
            .returning(|_| Ok(None));
    }

    fn create_open_message(is_certified: IsCertified, is_expired: IsExpired) -> OpenMessage {
        OpenMessage {
            signed_entity_type: SignedEntityType::CardanoImmutableFilesFull(fake_data::beacon()),
            is_certified: is_certified == IsCertified::Yes,
            is_expired: is_expired == IsExpired::Yes,
            ..OpenMessage::dummy()
        }
    }

    #[derive(Eq, PartialEq)]
    enum IsCertified {
        Yes,
        No,
    }

    #[derive(Eq, PartialEq)]
    enum IsExpired {
        Yes,
        No,
    }

    #[tokio::test]
    async fn test_get_time_point_from_chain() {
        let expected = TimePoint::new(2, 17, ChainPoint::dummy());
        let mut dependencies = initialize_dependencies().await;
        let immutable_file_observer = Arc::new(DumbImmutableFileObserver::default());
        immutable_file_observer
            .shall_return(Some(expected.immutable_file_number))
            .await;
        let ticker_service = Arc::new(MithrilTickerService::new(
            Arc::new(FakeObserver::new(Some(expected.clone()))),
            immutable_file_observer,
        ));
        dependencies.ticker_service = ticker_service;
        let runner = AggregatorRunner::new(Arc::new(dependencies));

        // Retrieves the expected time point
        let res = runner.get_time_point_from_chain().await;
        assert_eq!(expected, res.unwrap());
    }

    #[tokio::test]
    async fn test_update_stake_distribution() {
        let mut deps = initialize_dependencies().await;
        let chain_observer = Arc::new(FakeObserver::default());
        deps.chain_observer = chain_observer.clone();
        deps.stake_distribution_service = Arc::new(MithrilStakeDistributionService::new(
            deps.stake_store.clone(),
            chain_observer.clone(),
        ));
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());
        let time_point = runner.get_time_point_from_chain().await.unwrap();
        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let expected = fixture.stake_distribution();

        chain_observer
            .set_signers(fixture.signers_with_stake())
            .await;
        runner
            .update_stake_distribution(&time_point)
            .await
            .expect("updating stake distribution should not return an error");

        let saved_stake_distribution = deps
            .stake_store
            .get_stakes(time_point.epoch.offset_to_recording_epoch())
            .await
            .unwrap()
            .unwrap_or_else(|| {
                panic!(
                    "I should have a stake distribution for the epoch {:?}",
                    time_point.epoch
                )
            });

        assert_eq!(expected, saved_stake_distribution);
    }

    #[tokio::test]
    async fn test_open_signer_registration_round() {
        let mut deps = initialize_dependencies().await;
        let signer_registration_round_opener = Arc::new(MithrilSignerRegisterer::new(
            deps.chain_observer.clone(),
            deps.verification_key_store.clone(),
            deps.signer_recorder.clone(),
            None,
        ));
        deps.signer_registration_round_opener = signer_registration_round_opener.clone();
        let stake_store = deps.stake_store.clone();
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());

        let time_point = TimePoint::dummy();
        let recording_epoch = time_point.epoch.offset_to_recording_epoch();
        let stake_distribution: StakeDistribution =
            StakeDistribution::from([("a".to_string(), 5), ("b".to_string(), 10)]);

        stake_store
            .save_stakes(recording_epoch, stake_distribution.clone())
            .await
            .expect("Save Stake distribution should not fail");

        runner
            .open_signer_registration_round(&time_point)
            .await
            .expect("opening signer registration should not return an error");

        let saved_current_round = signer_registration_round_opener.get_current_round().await;

        let expected_signer_registration_round =
            SignerRegistrationRound::dummy(recording_epoch, stake_distribution);

        assert_eq!(
            Some(expected_signer_registration_round),
            saved_current_round,
        );
    }

    #[tokio::test]
    async fn test_close_signer_registration_round() {
        let mut deps = initialize_dependencies().await;
        let signer_registration_round_opener = Arc::new(MithrilSignerRegisterer::new(
            deps.chain_observer.clone(),
            deps.verification_key_store.clone(),
            deps.signer_recorder.clone(),
            None,
        ));
        deps.signer_registration_round_opener = signer_registration_round_opener.clone();
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());

        let time_point = TimePoint::dummy();
        runner
            .open_signer_registration_round(&time_point)
            .await
            .expect("opening signer registration should not return an error");

        runner
            .close_signer_registration_round()
            .await
            .expect("closing signer registration should not return an error");

        let saved_current_round = signer_registration_round_opener.get_current_round().await;
        assert!(saved_current_round.is_none());
    }

    #[tokio::test]
    async fn test_expire_open_message() {
        let pending_certificate = fake_data::certificate_pending();

        let open_message_expected = OpenMessage {
            signed_entity_type: pending_certificate.signed_entity_type.clone(),
            is_certified: false,
            is_expired: false,
            expires_at: Some(
                DateTime::parse_from_rfc3339("2000-01-19T13:43:05.618857482Z")
                    .unwrap()
                    .with_timezone(&Utc),
            ),
            ..OpenMessage::dummy()
        };
        let open_message_clone = open_message_expected.clone();

        let mut mock_certifier_service = MockCertifierService::new();
        mock_certifier_service
            .expect_mark_open_message_if_expired()
            .return_once(|_| Ok(Some(open_message_clone)));

        let mut deps = initialize_dependencies().await;
        deps.certifier_service = Arc::new(mock_certifier_service);

        let runner = build_runner_with_fixture_data(deps).await;
        let open_message_expired = runner
            .mark_open_message_if_expired(&open_message_expected.signed_entity_type)
            .await
            .expect("mark_open_message_if_expired should not fail");

        assert_eq!(Some(open_message_expected), open_message_expired);
    }

    #[tokio::test]
    async fn test_create_new_pending_certificate() {
        let deps = initialize_dependencies().await;
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());
        let time_point = runner.get_time_point_from_chain().await.unwrap();
        let signed_entity_type = SignedEntityType::dummy();

        let fixture = MithrilFixtureBuilder::default().with_signers(5).build();
        let current_signers = fixture.signers_with_stake()[1..3].to_vec();
        let next_signers = fixture.signers_with_stake()[2..5].to_vec();
        let protocol_parameters = fake_data::protocol_parameters();
        deps.prepare_for_genesis(
            current_signers.clone(),
            next_signers.clone(),
            &protocol_parameters.clone(),
            &CardanoTransactionsSigningConfig::dummy(),
        )
        .await;
        runner.inform_new_epoch(time_point.epoch).await.unwrap();

        let mut certificate = runner
            .create_new_pending_certificate(time_point.clone(), &signed_entity_type)
            .await
            .unwrap();
        certificate.signers.sort_by_key(|s| s.party_id.clone());
        certificate.next_signers.sort_by_key(|s| s.party_id.clone());
        let mut expected = CertificatePending::new(
            time_point.epoch,
            signed_entity_type,
            protocol_parameters.clone(),
            protocol_parameters,
            Signer::vec_from(current_signers),
            Signer::vec_from(next_signers),
        );
        expected.signers.sort_by_key(|s| s.party_id.clone());
        expected.next_signers.sort_by_key(|s| s.party_id.clone());

        assert_eq!(expected, certificate);
    }

    #[tokio::test]
    async fn test_save_pending_certificate() {
        let deps = initialize_dependencies().await;
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());
        let pending_certificate = fake_data::certificate_pending();

        runner
            .save_pending_certificate(pending_certificate.clone())
            .await
            .expect("save_pending_certificate should not fail");

        let saved_cert = deps.certificate_pending_store.get().await.unwrap().unwrap();
        assert_eq!(pending_certificate, saved_cert);
    }

    #[tokio::test]
    async fn test_drop_pending_certificate() {
        let deps = initialize_dependencies().await;
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());
        let pending_certificate = fake_data::certificate_pending();
        deps.certificate_pending_store
            .save(pending_certificate.clone())
            .await
            .unwrap();

        let cert = runner.drop_pending_certificate().await.unwrap();
        assert_eq!(Some(pending_certificate), cert);
        let maybe_saved_cert = deps.certificate_pending_store.get().await.unwrap();
        assert_eq!(None, maybe_saved_cert);
    }

    #[tokio::test]
    async fn test_drop_pending_no_certificate() {
        let deps = initialize_dependencies().await;
        let deps = Arc::new(deps);
        let runner = AggregatorRunner::new(deps.clone());

        let cert = runner.drop_pending_certificate().await.unwrap();
        assert_eq!(None, cert);
        let maybe_saved_cert = deps.certificate_pending_store.get().await.unwrap();
        assert_eq!(None, maybe_saved_cert);
    }

    #[tokio::test]
    async fn test_update_era_checker() {
        let deps = initialize_dependencies().await;
        let ticker_service = deps.ticker_service.clone();
        let era_checker = deps.era_checker.clone();
        let mut time_point = ticker_service.get_current_time_point().await.unwrap();

        assert_eq!(time_point.epoch, era_checker.current_epoch());
        let runner = AggregatorRunner::new(Arc::new(deps));
        time_point.epoch += 1;

        runner.update_era_checker(time_point.epoch).await.unwrap();
        assert_eq!(time_point.epoch, era_checker.current_epoch());
    }

    #[tokio::test]
    async fn test_inform_new_epoch() {
        let mut mock_certifier_service = MockCertifierService::new();
        mock_certifier_service
            .expect_inform_epoch()
            .returning(|_| Ok(()))
            .times(1);
        let mut deps = initialize_dependencies().await;
        let current_epoch = deps
            .chain_observer
            .get_current_epoch()
            .await
            .unwrap()
            .unwrap();

        deps.certifier_service = Arc::new(mock_certifier_service);
        deps.epoch_service = Arc::new(RwLock::new(FakeEpochService::from_fixture(
            current_epoch,
            &MithrilFixtureBuilder::default().build(),
        )));

        let runner = AggregatorRunner::new(Arc::new(deps));

        runner.inform_new_epoch(current_epoch).await.unwrap();
    }

    #[tokio::test]
    async fn test_upkeep_calls_run_on_upkeep_service() {
        let mut upkeep_service = MockUpkeepService::new();
        upkeep_service
            .expect_run()
            .with(eq(Epoch(5)))
            .returning(|_| Ok(()))
            .times(1);

        let mut deps = initialize_dependencies().await;
        deps.upkeep_service = Arc::new(upkeep_service);

        let runner = AggregatorRunner::new(Arc::new(deps));

        runner.upkeep(Epoch(5)).await.unwrap();
    }

    #[tokio::test]
    async fn test_update_epoch_settings() {
        let mut mock_certifier_service = MockCertifierService::new();
        mock_certifier_service
            .expect_inform_epoch()
            .returning(|_| Ok(()))
            .times(1);

        let config = Configuration::new_sample();
        let mut deps = DependenciesBuilder::new_with_stdout_logger(config.clone())
            .build_dependency_container()
            .await
            .unwrap();
        deps.certifier_service = Arc::new(mock_certifier_service);
        let epoch_settings_storer = deps.epoch_settings_storer.clone();
        let current_epoch = deps.ticker_service.get_current_epoch().await.unwrap();
        let insert_epoch = current_epoch.offset_to_epoch_settings_recording_epoch();

        let runner = build_runner_with_fixture_data(deps).await;
        runner.inform_new_epoch(current_epoch).await.unwrap();
        runner
            .update_epoch_settings()
            .await
            .expect("update_epoch_settings should not fail");

        let saved_epoch_settings = epoch_settings_storer
            .get_epoch_settings(insert_epoch)
            .await
            .unwrap()
            .unwrap_or_else(|| panic!("should have epoch settings for epoch {insert_epoch}",));

        assert_eq!(
            AggregatorEpochSettings {
                protocol_parameters: config.protocol_parameters.clone(),
                cardano_transactions_signing_config: config
                    .cardano_transactions_signing_config
                    .clone(),
            },
            saved_epoch_settings
        );
    }

    #[tokio::test]
    async fn test_precompute_epoch_data() {
        let mut deps = initialize_dependencies().await;
        let current_epoch = deps
            .chain_observer
            .get_current_epoch()
            .await
            .unwrap()
            .unwrap();

        deps.epoch_service = Arc::new(RwLock::new(FakeEpochService::from_fixture(
            current_epoch,
            &MithrilFixtureBuilder::default().build(),
        )));

        let runner = AggregatorRunner::new(Arc::new(deps));

        runner.precompute_epoch_data().await.unwrap();
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_create_new_open_message_if_none_exists(
    ) {
        let open_message_created = create_open_message(IsCertified::No, IsExpired::No);
        let open_message_expected = open_message_created.clone();

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(&mut mock_certifier_service, vec![]);

            mock_certifier_service
                .expect_create_open_message()
                .return_once(|_, _| Ok(open_message_created))
                .times(1);
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();
        assert_eq!(Some(open_message_expected), open_message_returned);
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_return_existing_open_message_if_already_exists_and_not_expired(
    ) {
        let not_certified_and_not_expired = create_open_message(IsCertified::No, IsExpired::No);

        let open_message_expected = not_certified_and_not_expired.clone();

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(
                &mut mock_certifier_service,
                vec![not_certified_and_not_expired],
            );

            mock_certifier_service.expect_create_open_message().never();
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();

        assert_eq!(Some(open_message_expected), open_message_returned);
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_return_existing_open_message_if_already_exists_and_open_message_already_certified(
    ) {
        let certified_and_not_expired = create_open_message(IsCertified::Yes, IsExpired::No);
        let not_certified_and_not_expired = create_open_message(IsCertified::No, IsExpired::No);

        let open_message_expected = not_certified_and_not_expired.clone();

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(
                &mut mock_certifier_service,
                vec![certified_and_not_expired, not_certified_and_not_expired],
            );

            mock_certifier_service.expect_create_open_message().never();
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();

        assert_eq!(Some(open_message_expected), open_message_returned);
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_create_open_message_if_none_exists_and_open_message_already_certified(
    ) {
        let certified_and_not_expired = create_open_message(IsCertified::Yes, IsExpired::No);

        let open_message_created = create_open_message(IsCertified::No, IsExpired::No);
        let open_message_expected = open_message_created.clone();

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(
                &mut mock_certifier_service,
                vec![certified_and_not_expired],
            );

            mock_certifier_service
                .expect_create_open_message()
                .return_once(|_, _| Ok(open_message_created))
                .times(1);
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();

        assert_eq!(Some(open_message_expected), open_message_returned);
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_return_none_if_all_open_message_already_certified(
    ) {
        let certified_and_not_expired_1 = create_open_message(IsCertified::Yes, IsExpired::No);
        let certified_and_not_expired_2 = create_open_message(IsCertified::Yes, IsExpired::No);

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(
                &mut mock_certifier_service,
                vec![certified_and_not_expired_1, certified_and_not_expired_2],
            );

            mock_certifier_service.expect_create_open_message().never();
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();

        assert!(open_message_returned.is_none());
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_should_return_first_not_certified_and_not_expired_open_message(
    ) {
        let not_certified_and_expired = create_open_message(IsCertified::No, IsExpired::Yes);
        let not_certified_and_not_expired = create_open_message(IsCertified::No, IsExpired::No);

        let open_message_expected = not_certified_and_not_expired.clone();

        let runner = {
            let mut mock_certifier_service = MockCertifierService::new();
            init_certifier_service_mock(
                &mut mock_certifier_service,
                vec![not_certified_and_expired, not_certified_and_not_expired],
            );

            mock_certifier_service.expect_create_open_message().never();
            build_runner(mock_certifier_service).await
        };

        let open_message_returned = runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();

        assert_eq!(Some(open_message_expected), open_message_returned);
    }

    #[tokio::test]
    async fn test_get_current_non_certified_open_message_called_for_mithril_stake_distribution_and_then_for_immutable_file(
    ) {
        let mut mock_certifier_service = MockCertifierService::new();

        let mut seq = Sequence::new();
        mock_certifier_service
            .expect_get_open_message()
            .with(eq(SignedEntityType::MithrilStakeDistribution(
                TimePoint::dummy().epoch,
            )))
            .times(1)
            .in_sequence(&mut seq)
            .return_once(|_| Ok(Some(create_open_message(IsCertified::Yes, IsExpired::No))));

        mock_certifier_service
            .expect_get_open_message()
            .with(eq(SignedEntityType::CardanoImmutableFilesFull(
                fake_data::beacon(),
            )))
            .times(1)
            .in_sequence(&mut seq)
            .return_once(|_| Ok(Some(create_open_message(IsCertified::Yes, IsExpired::No))));

        mock_certifier_service.expect_create_open_message().never();

        mock_certifier_service
            .expect_inform_epoch()
            .return_once(|_| Ok(()));
        mock_certifier_service
            .expect_mark_open_message_if_expired()
            .returning(|_| Ok(None));

        let runner = build_runner(mock_certifier_service).await;

        runner
            .get_current_non_certified_open_message(&TimePoint::dummy())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn list_available_signed_entity_types_list_all_configured_entities_if_none_are_locked() {
        let runner = {
            let mut dependencies = initialize_dependencies().await;
            let epoch_service = FakeEpochServiceBuilder {
                signed_entity_config: SignedEntityConfig {
                    allowed_discriminants: SignedEntityTypeDiscriminants::all(),
                    ..SignedEntityConfig::dummy()
                },
                ..FakeEpochServiceBuilder::dummy(Epoch(32))
            }
            .build();
            dependencies.epoch_service = Arc::new(RwLock::new(epoch_service));
            dependencies.signed_entity_type_lock = Arc::new(SignedEntityTypeLock::default());
            AggregatorRunner::new(Arc::new(dependencies))
        };

        let time_point = TimePoint::dummy();
        let signed_entities: Vec<SignedEntityTypeDiscriminants> = runner
            .list_available_signed_entity_types(&time_point)
            .await
            .unwrap()
            .into_iter()
            .map(Into::into)
            .collect();

        assert_eq!(
            signed_entities,
            SignedEntityTypeDiscriminants::all()
                .into_iter()
                .collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn list_available_signed_entity_types_exclude_locked_entities() {
        let signed_entity_type_lock = Arc::new(SignedEntityTypeLock::default());
        let runner = {
            let mut dependencies = initialize_dependencies().await;
            dependencies.signed_entity_type_lock = signed_entity_type_lock.clone();
            let epoch_service = FakeEpochServiceBuilder {
                signed_entity_config: SignedEntityConfig {
                    allowed_discriminants: SignedEntityTypeDiscriminants::all(),
                    ..SignedEntityConfig::dummy()
                },
                ..FakeEpochServiceBuilder::dummy(Epoch(32))
            }
            .build();
            dependencies.epoch_service = Arc::new(RwLock::new(epoch_service));

            AggregatorRunner::new(Arc::new(dependencies))
        };

        signed_entity_type_lock
            .lock(SignedEntityTypeDiscriminants::CardanoTransactions)
            .await;

        let time_point = TimePoint::dummy();
        let signed_entities: Vec<SignedEntityTypeDiscriminants> = runner
            .list_available_signed_entity_types(&time_point)
            .await
            .unwrap()
            .into_iter()
            .map(Into::into)
            .collect();

        assert!(!signed_entities.is_empty());
        assert!(!signed_entities.contains(&SignedEntityTypeDiscriminants::CardanoTransactions));
    }

    #[tokio::test]
    async fn is_open_message_outdated_return_false_when_message_is_not_expired_and_no_newer_open_message(
    ) {
        assert!(!is_outdated_returned_when(IsExpired::No, false).await);
    }

    #[tokio::test]
    async fn is_open_message_outdated_return_true_when_message_is_expired_and_no_newer_open_message(
    ) {
        assert!(is_outdated_returned_when(IsExpired::Yes, false).await);
    }

    #[tokio::test]
    async fn is_open_message_outdated_return_true_when_message_is_not_expired_and_exists_newer_open_message(
    ) {
        assert!(is_outdated_returned_when(IsExpired::No, true).await);
    }

    #[tokio::test]
    async fn is_open_message_outdated_return_true_when_message_is_expired_and_exists_newer_open_message(
    ) {
        assert!(is_outdated_returned_when(IsExpired::Yes, true).await);
    }

    async fn is_outdated_returned_when(is_expired: IsExpired, newer_open_message: bool) -> bool {
        let current_time_point = TimePoint {
            epoch: Epoch(2),
            ..TimePoint::dummy()
        };

        let message_epoch = if newer_open_message {
            current_time_point.epoch + 54
        } else {
            current_time_point.epoch
        };
        let open_message_to_verify = OpenMessage {
            signed_entity_type: SignedEntityType::MithrilStakeDistribution(message_epoch),
            is_expired: is_expired == IsExpired::Yes,
            ..OpenMessage::dummy()
        };

        let runner = {
            let mut deps = initialize_dependencies().await;
            let mut mock_certifier_service = MockCertifierService::new();

            let open_message_current = open_message_to_verify.clone();
            mock_certifier_service
                .expect_get_open_message()
                .times(1)
                .return_once(|_| Ok(Some(open_message_current)));
            mock_certifier_service
                .expect_mark_open_message_if_expired()
                .returning(|_| Ok(None));

            deps.certifier_service = Arc::new(mock_certifier_service);

            let epoch_service = FakeEpochServiceBuilder::dummy(current_time_point.epoch).build();
            deps.epoch_service = Arc::new(RwLock::new(epoch_service));

            build_runner_with_fixture_data(deps).await
        };

        runner
            .is_open_message_outdated(
                open_message_to_verify.signed_entity_type,
                &current_time_point,
            )
            .await
            .unwrap()
    }
}