-
Notifications
You must be signed in to change notification settings - Fork 39
/
builder.rs
1199 lines (1011 loc) · 46.1 KB
/
builder.rs
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
use std::sync::Arc;
use anyhow::Context;
use mithril_common::{
api_version::APIVersionProvider,
certificate_chain::{CertificateVerifier, MithrilCertificateVerifier},
chain_observer::{CardanoCliChainObserver, CardanoCliRunner, ChainObserver, FakeObserver},
crypto_helper::{
ProtocolGenesisSigner, ProtocolGenesisVerificationKey, ProtocolGenesisVerifier,
},
database::{ApplicationNodeType, DatabaseVersionChecker},
digesters::{
cache::{ImmutableFileDigestCacheProvider, JsonImmutableFileDigestCacheProviderBuilder},
CardanoImmutableDigester, DumbImmutableFileObserver, ImmutableDigester,
ImmutableFileObserver, ImmutableFileSystemObserver,
},
entities::{CertificatePending, CompressionAlgorithm, Epoch},
era::{
adapters::{EraReaderAdapterBuilder, EraReaderDummyAdapter},
EraChecker, EraMarker, EraReader, EraReaderAdapter, SupportedEra,
},
signable_builder::{
CardanoImmutableFilesFullSignableBuilder, MithrilStakeDistributionSignableBuilder,
},
signable_builder::{MithrilSignableBuilderService, SignableBuilderService},
store::adapter::{MemoryAdapter, SQLiteAdapter, StoreAdapter},
BeaconProvider, BeaconProviderImpl,
};
use semver::Version;
use slog::Logger;
use slog_scope::debug;
use sqlite::{Connection, ConnectionWithFullMutex};
use tokio::{
sync::{
mpsc::{UnboundedReceiver, UnboundedSender},
RwLock,
},
time::Duration,
};
use warp::Filter;
use crate::{
artifact_builder::{
CardanoImmutableFilesFullArtifactBuilder, MithrilStakeDistributionArtifactBuilder,
},
configuration::ExecutionEnvironment,
database::provider::{
CertificateRepository, EpochSettingStore, OpenMessageRepository, SignedEntityStoreAdapter,
SignedEntityStorer, SignerRegistrationStore, SignerStore, SingleSignatureRepository,
StakePoolStore,
},
event_store::{EventMessage, EventStore, TransmitterService},
http_server::routes::router,
services::{
CertifierService, MithrilCertifierService, MithrilEpochService, MithrilSignedEntityService,
MithrilStakeDistributionService, MithrilTickerService, SignedEntityService,
StakeDistributionService, TickerService,
},
tools::{CExplorerSignerRetriever, GcpFileUploader, GenesisToolsDependency, SignersImporter},
AggregatorConfig, AggregatorRunner, AggregatorRuntime, CertificatePendingStore,
CompressedArchiveSnapshotter, Configuration, DependencyContainer, DumbSnapshotUploader,
DumbSnapshotter, LocalSnapshotUploader, MithrilSignerRegisterer, MultiSigner, MultiSignerImpl,
ProtocolParametersStorer, RemoteSnapshotUploader, SnapshotUploader, SnapshotUploaderType,
Snapshotter, SnapshotterCompressionAlgorithm, VerificationKeyStorer,
};
use super::{DependenciesBuilderError, EpochServiceWrapper, Result};
const SQLITE_FILE: &str = "aggregator.sqlite3";
/// ## Dependencies container builder
///
/// This is meant to create SHARED DEPENDENCIES, ie: dependencies instances that
/// must be shared amongst several Tokio tasks. For example, database
/// repositories are NOT shared dependencies and therefor can be created ad hoc
/// whereas the database connection is a shared dependency.
///
/// Each shared dependency must implement a `build` and a `get` function. The
/// build function creates the dependency, the get function creates the
/// dependency at first call then return a clone of the Arc containing the
/// dependency for all further calls.
pub struct DependenciesBuilder {
/// Configuration parameters
pub configuration: Configuration,
/// SQLite database connection
pub sqlite_connection: Option<Arc<ConnectionWithFullMutex>>,
/// Stake Store used by the StakeDistributionService
/// It shall be a private dependency.
pub stake_store: Option<Arc<StakePoolStore>>,
/// Snapshot uploader service.
pub snapshot_uploader: Option<Arc<dyn SnapshotUploader>>,
/// Multisigner service.
pub multi_signer: Option<Arc<RwLock<dyn MultiSigner>>>,
/// Certificate pending store.
pub certificate_pending_store: Option<Arc<CertificatePendingStore>>,
/// Certificate repository.
pub certificate_repository: Option<Arc<CertificateRepository>>,
/// Verification key store.
pub verification_key_store: Option<Arc<dyn VerificationKeyStorer>>,
/// Protocol parameter store.
pub protocol_parameters_store: Option<Arc<dyn ProtocolParametersStorer>>,
/// Cardano CLI Runner for the [ChainObserver]
pub cardano_cli_runner: Option<Box<CardanoCliRunner>>,
/// Chain observer service.
pub chain_observer: Option<Arc<dyn ChainObserver>>,
/// Beacon provider service.
pub beacon_provider: Option<Arc<dyn BeaconProvider>>,
/// Immutable file digester service.
pub immutable_digester: Option<Arc<dyn ImmutableDigester>>,
/// Immutable file observer service.
pub immutable_file_observer: Option<Arc<dyn ImmutableFileObserver>>,
/// Immutable cache provider service.
pub immutable_cache_provider: Option<Arc<dyn ImmutableFileDigestCacheProvider>>,
/// Digester service.
pub digester: Option<Arc<dyn ImmutableDigester>>,
/// Snapshotter service.
pub snapshotter: Option<Arc<dyn Snapshotter>>,
/// Certificate verifier service.
pub certificate_verifier: Option<Arc<dyn CertificateVerifier>>,
/// Genesis signature verifier service.
pub genesis_verifier: Option<Arc<ProtocolGenesisVerifier>>,
/// Signer registerer service
pub mithril_registerer: Option<Arc<MithrilSignerRegisterer>>,
/// Era checker service
pub era_checker: Option<Arc<EraChecker>>,
/// Adapter for [EraReader]
pub era_reader_adapter: Option<Arc<dyn EraReaderAdapter>>,
/// Era reader service
pub era_reader: Option<Arc<EraReader>>,
/// Event Transmitter Service
pub event_transmitter: Option<Arc<TransmitterService<EventMessage>>>,
/// Event transmitter Channel Sender endpoint
pub event_transmitter_channel: (
Option<UnboundedReceiver<EventMessage>>,
Option<UnboundedSender<EventMessage>>,
),
/// API Version provider
pub api_version_provider: Option<Arc<APIVersionProvider>>,
/// Stake Distribution Service
pub stake_distribution_service: Option<Arc<dyn StakeDistributionService>>,
/// Ticker Service (TODO: remove BeaconProvider)
pub ticker_service: Option<Arc<dyn TickerService>>,
/// Signer Store
pub signer_store: Option<Arc<SignerStore>>,
/// Signable Builder Service
pub signable_builder_service: Option<Arc<dyn SignableBuilderService>>,
/// Signed Entity Service
pub signed_entity_service: Option<Arc<dyn SignedEntityService>>,
/// Certifier service
pub certifier_service: Option<Arc<dyn CertifierService>>,
/// Epoch service.
pub epoch_service: Option<EpochServiceWrapper>,
/// Signed Entity storer
pub signed_entity_storer: Option<Arc<dyn SignedEntityStorer>>,
}
impl DependenciesBuilder {
/// Create a new clean dependency builder
pub fn new(configuration: Configuration) -> Self {
Self {
configuration,
sqlite_connection: None,
stake_store: None,
snapshot_uploader: None,
multi_signer: None,
certificate_pending_store: None,
certificate_repository: None,
verification_key_store: None,
protocol_parameters_store: None,
cardano_cli_runner: None,
chain_observer: None,
beacon_provider: None,
immutable_digester: None,
immutable_file_observer: None,
immutable_cache_provider: None,
digester: None,
snapshotter: None,
certificate_verifier: None,
genesis_verifier: None,
mithril_registerer: None,
era_reader_adapter: None,
era_checker: None,
era_reader: None,
event_transmitter: None,
event_transmitter_channel: (None, None),
api_version_provider: None,
stake_distribution_service: None,
ticker_service: None,
signer_store: None,
signable_builder_service: None,
signed_entity_service: None,
certifier_service: None,
epoch_service: None,
signed_entity_storer: None,
}
}
async fn build_sqlite_connection(&self) -> Result<Arc<ConnectionWithFullMutex>> {
let path = match self.configuration.environment {
ExecutionEnvironment::Production => {
self.configuration.get_sqlite_dir().join(SQLITE_FILE)
}
_ => self.configuration.data_stores_directory.clone(),
};
let connection = Connection::open_with_full_mutex(&path)
.map(Arc::new)
.map_err(|e| DependenciesBuilderError::Initialization {
message: format!(
"SQLite initialization: could not open connection with string '{}'.",
path.display()
),
error: Some(e.into()),
})?;
// Check database migrations
let mut db_checker = DatabaseVersionChecker::new(
self.get_logger().await?,
ApplicationNodeType::Aggregator,
connection.clone(),
);
for migration in crate::database::migration::get_migrations() {
db_checker.add_migration(migration);
}
// configure session
connection
.execute("pragma foreign_keys=true")
.map_err(|e| DependenciesBuilderError::Initialization {
message: "SQLite initialization: could not enable FOREIGN KEY support.".to_string(),
error: Some(e.into()),
})?;
db_checker
.apply()
.await
.with_context(|| "Database migration error")?;
Ok(connection)
}
/// Get SQLite connection
pub async fn get_sqlite_connection(&mut self) -> Result<Arc<ConnectionWithFullMutex>> {
if self.sqlite_connection.is_none() {
self.sqlite_connection = Some(self.build_sqlite_connection().await?);
}
Ok(self.sqlite_connection.as_ref().cloned().unwrap())
}
async fn build_stake_store(&mut self) -> Result<Arc<StakePoolStore>> {
let stake_pool_store = Arc::new(StakePoolStore::new(
self.get_sqlite_connection().await?,
self.configuration.safe_epoch_retention_limit(),
));
Ok(stake_pool_store)
}
/// Return a [StakePoolStore]
pub async fn get_stake_store(&mut self) -> Result<Arc<StakePoolStore>> {
if self.stake_store.is_none() {
self.stake_store = Some(self.build_stake_store().await?);
}
Ok(self.stake_store.as_ref().cloned().unwrap())
}
async fn build_snapshot_uploader(&mut self) -> Result<Arc<dyn SnapshotUploader>> {
if self.configuration.environment == ExecutionEnvironment::Production {
match self.configuration.snapshot_uploader_type {
SnapshotUploaderType::Gcp => {
let bucket = self
.configuration
.snapshot_bucket_name
.to_owned()
.ok_or_else(|| {
DependenciesBuilderError::MissingConfiguration(
"snapshot_bucket_name".to_string(),
)
})?;
Ok(Arc::new(RemoteSnapshotUploader::new(
Box::new(GcpFileUploader::new(bucket.clone())),
bucket,
self.configuration.snapshot_use_cdn_domain,
)))
}
SnapshotUploaderType::Local => Ok(Arc::new(LocalSnapshotUploader::new(
self.configuration.get_server_url(),
&self.configuration.snapshot_directory,
))),
}
} else {
Ok(Arc::new(DumbSnapshotUploader::new()))
}
}
/// Get a [SnapshotUploader]
pub async fn get_snapshot_uploader(&mut self) -> Result<Arc<dyn SnapshotUploader>> {
if self.snapshot_uploader.is_none() {
self.snapshot_uploader = Some(self.build_snapshot_uploader().await?);
}
Ok(self.snapshot_uploader.as_ref().cloned().unwrap())
}
async fn build_multi_signer(&mut self) -> Result<Arc<RwLock<dyn MultiSigner>>> {
let multi_signer = MultiSignerImpl::new(self.get_epoch_service().await?);
Ok(Arc::new(RwLock::new(multi_signer)))
}
/// Get a configured multi signer
pub async fn get_multi_signer(&mut self) -> Result<Arc<RwLock<dyn MultiSigner>>> {
if self.multi_signer.is_none() {
self.multi_signer = Some(self.build_multi_signer().await?);
}
Ok(self.multi_signer.as_ref().cloned().unwrap())
}
async fn build_certificate_pending_store(&mut self) -> Result<Arc<CertificatePendingStore>> {
let adapter: Box<dyn StoreAdapter<Key = String, Record = CertificatePending>> = match self
.configuration
.environment
{
ExecutionEnvironment::Production => {
let adapter =
SQLiteAdapter::new("pending_certificate", self.get_sqlite_connection().await?)
.map_err(|e| DependenciesBuilderError::Initialization {
message: "Cannot create SQLite adapter for PendingCertificate Store."
.to_string(),
error: Some(e.into()),
})?;
Box::new(adapter)
}
_ => {
let adapter = MemoryAdapter::new(None).map_err(|e| {
DependenciesBuilderError::Initialization {
message: "Cannot create Memory adapter for PendingCertificate Store."
.to_string(),
error: Some(e.into()),
}
})?;
Box::new(adapter)
}
};
Ok(Arc::new(CertificatePendingStore::new(adapter)))
}
/// Get a configured [CertificatePendingStore].
pub async fn get_certificate_pending_store(&mut self) -> Result<Arc<CertificatePendingStore>> {
if self.certificate_pending_store.is_none() {
self.certificate_pending_store = Some(self.build_certificate_pending_store().await?);
}
Ok(self.certificate_pending_store.as_ref().cloned().unwrap())
}
async fn build_certificate_repository(&mut self) -> Result<Arc<CertificateRepository>> {
Ok(Arc::new(CertificateRepository::new(
self.get_sqlite_connection().await?,
)))
}
/// Get a configured [CertificateRepository].
pub async fn get_certificate_repository(&mut self) -> Result<Arc<CertificateRepository>> {
if self.certificate_repository.is_none() {
self.certificate_repository = Some(self.build_certificate_repository().await?);
}
Ok(self.certificate_repository.as_ref().cloned().unwrap())
}
async fn build_verification_key_store(&mut self) -> Result<Arc<dyn VerificationKeyStorer>> {
Ok(Arc::new(SignerRegistrationStore::new(
self.get_sqlite_connection().await?,
)))
}
/// Get a configured [VerificationKeyStorer].
pub async fn get_verification_key_store(&mut self) -> Result<Arc<dyn VerificationKeyStorer>> {
if self.verification_key_store.is_none() {
self.verification_key_store = Some(self.build_verification_key_store().await?);
}
Ok(self.verification_key_store.as_ref().cloned().unwrap())
}
async fn build_protocol_parameters_store(
&mut self,
) -> Result<Arc<dyn ProtocolParametersStorer>> {
Ok(Arc::new(EpochSettingStore::new(
self.get_sqlite_connection().await?,
self.configuration.safe_epoch_retention_limit(),
)))
}
/// Get a configured [ProtocolParametersStorer].
pub async fn get_protocol_parameters_store(
&mut self,
) -> Result<Arc<dyn ProtocolParametersStorer>> {
if self.protocol_parameters_store.is_none() {
self.protocol_parameters_store = Some(self.build_protocol_parameters_store().await?);
}
Ok(self.protocol_parameters_store.as_ref().cloned().unwrap())
}
async fn build_chain_observer(&mut self) -> Result<Arc<dyn ChainObserver>> {
let chain_observer: Arc<dyn ChainObserver> = match self.configuration.environment {
ExecutionEnvironment::Production => Arc::new(CardanoCliChainObserver::new(
self.get_cardano_cli_runner().await?,
)),
_ => Arc::new(FakeObserver::default()),
};
Ok(chain_observer)
}
/// Return a [ChainObserver]
pub async fn get_chain_observer(&mut self) -> Result<Arc<dyn ChainObserver>> {
if self.chain_observer.is_none() {
self.chain_observer = Some(self.build_chain_observer().await?);
}
Ok(self.chain_observer.as_ref().cloned().unwrap())
}
async fn build_cardano_cli_runner(&mut self) -> Result<Box<CardanoCliRunner>> {
let cli_runner = CardanoCliRunner::new(
self.configuration.cardano_cli_path.clone(),
self.configuration.cardano_node_socket_path.clone(),
self.configuration.get_network().with_context(|| {
"Dependencies Builder can not get Cardano network while building cardano cli runner"
})?,
);
Ok(Box::new(cli_runner))
}
/// Return a [CardanoCliRunner]
pub async fn get_cardano_cli_runner(&mut self) -> Result<Box<CardanoCliRunner>> {
if self.cardano_cli_runner.is_none() {
self.cardano_cli_runner = Some(self.build_cardano_cli_runner().await?);
}
Ok(self.cardano_cli_runner.as_ref().cloned().unwrap())
}
async fn build_beacon_provider(&mut self) -> Result<Arc<dyn BeaconProvider>> {
let beacon_provider = BeaconProviderImpl::new(
self.get_chain_observer().await?,
self.get_immutable_file_observer().await?,
self.configuration.get_network().with_context(|| {
"Dependencies Builder can not get Cardano network while building beacon provider"
})?,
);
Ok(Arc::new(beacon_provider))
}
/// Return a [BeaconProvider] instance.
pub async fn get_beacon_provider(&mut self) -> Result<Arc<dyn BeaconProvider>> {
if self.beacon_provider.is_none() {
self.beacon_provider = Some(self.build_beacon_provider().await?);
}
Ok(self.beacon_provider.as_ref().cloned().unwrap())
}
async fn build_immutable_file_observer(&mut self) -> Result<Arc<dyn ImmutableFileObserver>> {
let immutable_file_observer: Arc<dyn ImmutableFileObserver> =
match self.configuration.environment {
ExecutionEnvironment::Production => Arc::new(ImmutableFileSystemObserver::new(
&self.configuration.db_directory,
)),
_ => Arc::new(DumbImmutableFileObserver::default()),
};
Ok(immutable_file_observer)
}
/// Return a [ImmutableFileObserver] instance.
pub async fn get_immutable_file_observer(&mut self) -> Result<Arc<dyn ImmutableFileObserver>> {
if self.immutable_file_observer.is_none() {
self.immutable_file_observer = Some(self.build_immutable_file_observer().await?);
}
Ok(self.immutable_file_observer.as_ref().cloned().unwrap())
}
async fn build_immutable_cache_provider(
&mut self,
) -> Result<Arc<dyn ImmutableFileDigestCacheProvider>> {
let cache_provider = JsonImmutableFileDigestCacheProviderBuilder::new(
&self.configuration.data_stores_directory,
&format!("immutables_digests_{}.json", self.configuration.network),
)
.should_reset_digests_cache(self.configuration.reset_digests_cache)
.build()
.await?;
Ok(Arc::new(cache_provider))
}
/// Get an [ImmutableFileDigestCacheProvider]
pub async fn get_immutable_cache_provider(
&mut self,
) -> Result<Arc<dyn ImmutableFileDigestCacheProvider>> {
if self.immutable_cache_provider.is_none() {
self.immutable_cache_provider = Some(self.build_immutable_cache_provider().await?);
}
Ok(self.immutable_cache_provider.as_ref().cloned().unwrap())
}
async fn create_logger(&self) -> Result<Logger> {
Ok(slog_scope::logger())
}
/// This method does not cache the logger since it is managed internally by
/// its own crate.
pub async fn get_logger(&self) -> Result<Logger> {
self.create_logger().await
}
async fn build_immutable_digester(&mut self) -> Result<Arc<dyn ImmutableDigester>> {
let immutable_digester_cache = match self.configuration.environment {
ExecutionEnvironment::Production => Some(self.get_immutable_cache_provider().await?),
_ => None,
};
let digester =
CardanoImmutableDigester::new(immutable_digester_cache, self.get_logger().await?);
Ok(Arc::new(digester))
}
/// Immutable digester.
pub async fn get_immutable_digester(&mut self) -> Result<Arc<dyn ImmutableDigester>> {
if self.immutable_digester.is_none() {
self.immutable_digester = Some(self.build_immutable_digester().await?);
}
Ok(self.immutable_digester.as_ref().cloned().unwrap())
}
async fn build_snapshotter(&mut self) -> Result<Arc<dyn Snapshotter>> {
let snapshotter: Arc<dyn Snapshotter> = match self.configuration.environment {
ExecutionEnvironment::Production => {
let ongoing_snapshot_directory = self
.configuration
.snapshot_directory
.join("pending_snapshot");
let algorithm = match self.configuration.snapshot_compression_algorithm {
CompressionAlgorithm::Gzip => SnapshotterCompressionAlgorithm::Gzip,
CompressionAlgorithm::Zstandard => self
.configuration
.zstandard_parameters
.unwrap_or_default()
.into(),
};
Arc::new(CompressedArchiveSnapshotter::new(
self.configuration.db_directory.clone(),
ongoing_snapshot_directory,
algorithm,
)?)
}
_ => Arc::new(DumbSnapshotter::new()),
};
Ok(snapshotter)
}
/// [Snapshotter] service.
pub async fn get_snapshotter(&mut self) -> Result<Arc<dyn Snapshotter>> {
if self.snapshotter.is_none() {
self.snapshotter = Some(self.build_snapshotter().await?);
}
Ok(self.snapshotter.as_ref().cloned().unwrap())
}
async fn build_certificate_verifier(&mut self) -> Result<Arc<dyn CertificateVerifier>> {
let verifier = Arc::new(MithrilCertificateVerifier::new(
self.get_logger().await?,
self.get_certificate_repository().await?,
));
Ok(verifier)
}
/// [CertificateVerifier] service.
pub async fn get_certificate_verifier(&mut self) -> Result<Arc<dyn CertificateVerifier>> {
if self.certificate_verifier.is_none() {
self.certificate_verifier = Some(self.build_certificate_verifier().await?);
}
Ok(self.certificate_verifier.as_ref().cloned().unwrap())
}
async fn build_genesis_verifier(&mut self) -> Result<Arc<ProtocolGenesisVerifier>> {
let genesis_verifier: ProtocolGenesisVerifier = match self.configuration.environment {
ExecutionEnvironment::Production => ProtocolGenesisVerifier::from_verification_key(
ProtocolGenesisVerificationKey::from_json_hex(
&self.configuration.genesis_verification_key,
)
.map_err(|e| DependenciesBuilderError::Initialization {
message: format!(
"Could not decode hex key to build genesis verifier: '{}'",
self.configuration.genesis_verification_key
),
error: Some(e),
})?,
),
_ => ProtocolGenesisSigner::create_deterministic_genesis_signer()
.create_genesis_verifier(),
};
Ok(Arc::new(genesis_verifier))
}
/// Return a [ProtocolGenesisVerifier]
pub async fn get_genesis_verifier(&mut self) -> Result<Arc<ProtocolGenesisVerifier>> {
if self.genesis_verifier.is_none() {
self.genesis_verifier = Some(self.build_genesis_verifier().await?);
}
Ok(self.genesis_verifier.as_ref().cloned().unwrap())
}
async fn build_mithril_registerer(&mut self) -> Result<Arc<MithrilSignerRegisterer>> {
let registerer = MithrilSignerRegisterer::new(
self.get_chain_observer().await?,
self.get_verification_key_store().await?,
self.get_signer_store().await?,
self.configuration.safe_epoch_retention_limit(),
);
Ok(Arc::new(registerer))
}
/// [MithrilSignerRegisterer] service
pub async fn get_mithril_registerer(&mut self) -> Result<Arc<MithrilSignerRegisterer>> {
if self.mithril_registerer.is_none() {
self.mithril_registerer = Some(self.build_mithril_registerer().await?);
}
Ok(self.mithril_registerer.as_ref().cloned().unwrap())
}
async fn build_era_reader(&mut self) -> Result<Arc<EraReader>> {
let era_adapter: Arc<dyn EraReaderAdapter> = match self.configuration.environment {
ExecutionEnvironment::Production => EraReaderAdapterBuilder::new(
&self.configuration.era_reader_adapter_type,
&self.configuration.era_reader_adapter_params,
)
.build(self.get_chain_observer().await?)
.map_err(|e| DependenciesBuilderError::Initialization {
message: "Could not build EraReader as dependency.".to_string(),
error: Some(e.into()),
})?,
_ => Arc::new(EraReaderDummyAdapter::from_markers(vec![EraMarker::new(
&SupportedEra::dummy().to_string(),
Some(Epoch(0)),
)])),
};
Ok(Arc::new(EraReader::new(era_adapter)))
}
/// [EraReader] service
pub async fn get_era_reader(&mut self) -> Result<Arc<EraReader>> {
if self.era_reader.is_none() {
self.era_reader = Some(self.build_era_reader().await?);
}
Ok(self.era_reader.as_ref().cloned().unwrap())
}
async fn build_era_checker(&mut self) -> Result<Arc<EraChecker>> {
let current_epoch = self
.get_beacon_provider()
.await?
.get_current_beacon()
.await
.map_err(|e| DependenciesBuilderError::Initialization {
message: "Error while building EraChecker".to_string(),
error: Some(e),
})?
.epoch;
let era_epoch_token = self
.get_era_reader()
.await?
.read_era_epoch_token(current_epoch)
.await
.map_err(|e| DependenciesBuilderError::Initialization {
message: "Error while building EraChecker".to_string(),
error: Some(e.into()),
})?;
let era_checker = Arc::new(EraChecker::new(
era_epoch_token.get_current_supported_era().map_err(|e| {
DependenciesBuilderError::Initialization {
message: "Error while building EraChecker".to_string(),
error: Some(e),
}
})?,
era_epoch_token.get_current_epoch(),
));
Ok(era_checker)
}
/// [EraReader] service
pub async fn get_era_checker(&mut self) -> Result<Arc<EraChecker>> {
if self.era_checker.is_none() {
self.era_checker = Some(self.build_era_checker().await?);
}
Ok(self.era_checker.as_ref().cloned().unwrap())
}
async fn build_event_transmitter_channel(
&mut self,
) -> Result<(
UnboundedReceiver<EventMessage>,
UnboundedSender<EventMessage>,
)> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<EventMessage>();
Ok((rx, tx))
}
/// Return the EventMessage channel sender.
pub async fn get_event_transmitter_sender(&mut self) -> Result<UnboundedSender<EventMessage>> {
if let (_, None) = self.event_transmitter_channel {
let (rx, tx) = self.build_event_transmitter_channel().await?;
self.event_transmitter_channel = (Some(rx), Some(tx));
}
Ok(self
.event_transmitter_channel
.1
.as_ref()
.cloned()
.expect("Transmitter<EventMessage> should be set."))
}
/// Return the channel receiver setup for the [EventStore]. Since this
/// receiver is not clonable, it must be called only once.
pub async fn get_event_transmitter_receiver(
&mut self,
) -> Result<UnboundedReceiver<EventMessage>> {
if let (_, None) = self.event_transmitter_channel {
let (rx, tx) = self.build_event_transmitter_channel().await?;
self.event_transmitter_channel = (Some(rx), Some(tx));
}
let mut receiver: Option<UnboundedReceiver<EventMessage>> = None;
std::mem::swap(&mut self.event_transmitter_channel.0, &mut receiver);
receiver.ok_or_else(|| {
DependenciesBuilderError::InconsistentState(
"Receiver<EventMessage> has already been given and is not clonable.".to_string(),
)
})
}
async fn build_event_transmitter(&mut self) -> Result<Arc<TransmitterService<EventMessage>>> {
let sender = self.get_event_transmitter_sender().await?;
let event_transmitter = Arc::new(TransmitterService::new(sender));
Ok(event_transmitter)
}
/// [TransmitterService] service
pub async fn get_event_transmitter(&mut self) -> Result<Arc<TransmitterService<EventMessage>>> {
if self.event_transmitter.is_none() {
self.event_transmitter = Some(self.build_event_transmitter().await?);
}
Ok(self.event_transmitter.as_ref().cloned().unwrap())
}
async fn build_api_version_provider(&mut self) -> Result<Arc<APIVersionProvider>> {
let api_version_provider = Arc::new(APIVersionProvider::new(self.get_era_checker().await?));
Ok(api_version_provider)
}
/// [APIVersionProvider] service
pub async fn get_api_version_provider(&mut self) -> Result<Arc<APIVersionProvider>> {
if self.api_version_provider.is_none() {
self.api_version_provider = Some(self.build_api_version_provider().await?);
}
Ok(self.api_version_provider.as_ref().cloned().unwrap())
}
async fn build_stake_distribution_service(
&mut self,
) -> Result<Arc<dyn StakeDistributionService>> {
let stake_distribution_service = Arc::new(MithrilStakeDistributionService::new(
self.get_stake_store().await?,
self.get_chain_observer().await?,
));
Ok(stake_distribution_service)
}
/// [StakeDistributionService] service
pub async fn get_stake_distribution_service(
&mut self,
) -> Result<Arc<dyn StakeDistributionService>> {
if self.stake_distribution_service.is_none() {
self.stake_distribution_service = Some(self.build_stake_distribution_service().await?);
}
Ok(self.stake_distribution_service.as_ref().cloned().unwrap())
}
async fn build_signer_store(&mut self) -> Result<Arc<SignerStore>> {
let signer_store = Arc::new(SignerStore::new(self.get_sqlite_connection().await?));
Ok(signer_store)
}
/// [SignerStore] service
pub async fn get_signer_store(&mut self) -> Result<Arc<SignerStore>> {
match self.signer_store.as_ref().cloned() {
None => {
let store = self.build_signer_store().await?;
self.signer_store = Some(store.clone());
Ok(store)
}
Some(store) => Ok(store),
}
}
async fn build_signable_builder_service(&mut self) -> Result<Arc<dyn SignableBuilderService>> {
let mithril_stake_distribution_builder =
Arc::new(MithrilStakeDistributionSignableBuilder::default());
let immutable_signable_builder = Arc::new(CardanoImmutableFilesFullSignableBuilder::new(
self.get_immutable_digester().await?,
&self.configuration.db_directory,
self.get_logger().await?,
));
let signable_builder_service = Arc::new(MithrilSignableBuilderService::new(
mithril_stake_distribution_builder,
immutable_signable_builder,
));
Ok(signable_builder_service)
}
/// [SignableBuilderService] service
pub async fn get_signable_builder_service(
&mut self,
) -> Result<Arc<dyn SignableBuilderService>> {
if self.signable_builder_service.is_none() {
self.signable_builder_service = Some(self.build_signable_builder_service().await?);
}
Ok(self.signable_builder_service.as_ref().cloned().unwrap())
}
async fn build_signed_entity_service(&mut self) -> Result<Arc<dyn SignedEntityService>> {
let signed_entity_storer = self.build_signed_entity_storer().await?;
let epoch_service = self.get_epoch_service().await?;
let mithril_stake_distribution_artifact_builder =
Arc::new(MithrilStakeDistributionArtifactBuilder::new(epoch_service));
let snapshotter = self.build_snapshotter().await?;
let snapshot_uploader = self.build_snapshot_uploader().await?;
let cardano_node_version = Version::parse(&self.configuration.cardano_node_version)
.map_err(|e| DependenciesBuilderError::Initialization { message: format!("Could not parse configuration setting 'cardano_node_version' value '{}' as Semver.", self.configuration.cardano_node_version), error: Some(e.into()) })?;
let cardano_immutable_files_full_artifact_builder =
Arc::new(CardanoImmutableFilesFullArtifactBuilder::new(
&cardano_node_version,
snapshotter,
snapshot_uploader,
self.configuration.snapshot_compression_algorithm,
));
let signed_entity_service = Arc::new(MithrilSignedEntityService::new(
signed_entity_storer,
mithril_stake_distribution_artifact_builder,
cardano_immutable_files_full_artifact_builder,
));
Ok(signed_entity_service)
}
/// [SignedEntityService] service
pub async fn get_signed_entity_service(&mut self) -> Result<Arc<dyn SignedEntityService>> {
if self.signed_entity_service.is_none() {
self.signed_entity_service = Some(self.build_signed_entity_service().await?);
}
Ok(self.signed_entity_service.as_ref().cloned().unwrap())
}
async fn build_epoch_service(&mut self) -> Result<EpochServiceWrapper> {
let verification_key_store = self.get_verification_key_store().await?;
let protocol_parameters_store = self.get_protocol_parameters_store().await?;
let epoch_service = Arc::new(RwLock::new(MithrilEpochService::new(
self.configuration.protocol_parameters.clone(),
protocol_parameters_store,
verification_key_store,
)));
Ok(epoch_service)
}
/// [EpochService][crate::services::EpochService] service
pub async fn get_epoch_service(&mut self) -> Result<EpochServiceWrapper> {
if self.epoch_service.is_none() {
self.epoch_service = Some(self.build_epoch_service().await?);
}
Ok(self.epoch_service.as_ref().cloned().unwrap())
}
async fn build_signed_entity_storer(&mut self) -> Result<Arc<dyn SignedEntityStorer>> {
let signed_entity_storer = Arc::new(SignedEntityStoreAdapter::new(
self.get_sqlite_connection().await?,
));
Ok(signed_entity_storer)
}
/// [SignedEntityStorer] service
pub async fn get_signed_entity_storer(&mut self) -> Result<Arc<dyn SignedEntityStorer>> {
if self.signed_entity_storer.is_none() {
self.signed_entity_storer = Some(self.build_signed_entity_storer().await?);
}
Ok(self.signed_entity_storer.as_ref().cloned().unwrap())
}
/// Return an unconfigured [DependencyContainer]
pub async fn build_dependency_container(&mut self) -> Result<DependencyContainer> {
let dependency_manager = DependencyContainer {
config: self.configuration.clone(),
sqlite_connection: self.get_sqlite_connection().await?,
stake_store: self.get_stake_store().await?,
snapshot_uploader: self.get_snapshot_uploader().await?,
multi_signer: self.get_multi_signer().await?,
certificate_pending_store: self.get_certificate_pending_store().await?,
certificate_repository: self.get_certificate_repository().await?,
verification_key_store: self.get_verification_key_store().await?,
protocol_parameters_store: self.get_protocol_parameters_store().await?,
chain_observer: self.get_chain_observer().await?,
beacon_provider: self.get_beacon_provider().await?,
immutable_file_observer: self.get_immutable_file_observer().await?,
digester: self.get_immutable_digester().await?,
snapshotter: self.get_snapshotter().await?,
certificate_verifier: self.get_certificate_verifier().await?,
genesis_verifier: self.get_genesis_verifier().await?,
signer_registerer: self.get_mithril_registerer().await?,
signer_registration_round_opener: self.get_mithril_registerer().await?,
era_checker: self.get_era_checker().await?,
era_reader: self.get_era_reader().await?,