mithril_aggregator/database/repository/
signed_entity_store.rs1use std::sync::Arc;
2
3use anyhow::Context;
4use async_trait::async_trait;
5
6use mithril_common::StdResult;
7use mithril_common::entities::{Epoch, SignedEntityTypeDiscriminants};
8use mithril_persistence::sqlite::{ConnectionExtensions, SqliteConnection};
9
10use crate::database::query::{
11 GetSignedEntityRecordQuery, InsertSignedEntityRecordQuery, UpdateSignedEntityQuery,
12};
13use crate::database::record::SignedEntityRecord;
14
15#[cfg_attr(test, mockall::automock)]
17#[async_trait]
18pub trait SignedEntityStorer: Sync + Send {
19 async fn store_signed_entity(&self, signed_entity: &SignedEntityRecord) -> StdResult<()>;
21
22 async fn get_signed_entity(
24 &self,
25 signed_entity_id: &str,
26 ) -> StdResult<Option<SignedEntityRecord>>;
27
28 async fn get_signed_entity_by_certificate_id(
30 &self,
31 certificate_hash: &str,
32 ) -> StdResult<Option<SignedEntityRecord>>;
33
34 async fn get_signed_entities_by_certificates_ids<'a>(
36 &self,
37 certificates_ids: &[&'a str],
38 ) -> StdResult<Vec<SignedEntityRecord>>;
39
40 async fn get_last_signed_entities_by_type(
42 &self,
43 signed_entity_type_id: &SignedEntityTypeDiscriminants,
44 total: usize,
45 ) -> StdResult<Vec<SignedEntityRecord>>;
46
47 async fn get_cardano_stake_distribution_signed_entity_by_epoch(
49 &self,
50 epoch: Epoch,
51 ) -> StdResult<Option<SignedEntityRecord>>;
52
53 async fn update_signed_entities(
55 &self,
56 signed_entities: Vec<SignedEntityRecord>,
57 ) -> StdResult<Vec<SignedEntityRecord>>;
58}
59
60pub struct SignedEntityStore {
62 connection: Arc<SqliteConnection>,
63}
64
65impl SignedEntityStore {
66 pub fn new(connection: Arc<SqliteConnection>) -> Self {
68 Self { connection }
69 }
70}
71
72#[async_trait]
73impl SignedEntityStorer for SignedEntityStore {
74 async fn store_signed_entity(&self, signed_entity: &SignedEntityRecord) -> StdResult<()> {
75 let _ = self
76 .connection
77 .fetch_first(InsertSignedEntityRecordQuery::one(signed_entity.clone()));
78
79 Ok(())
80 }
81
82 async fn get_signed_entity(
83 &self,
84 signed_entity_id: &str,
85 ) -> StdResult<Option<SignedEntityRecord>> {
86 self.connection
87 .fetch_first(GetSignedEntityRecordQuery::by_signed_entity_id(
88 signed_entity_id,
89 ))
90 .with_context(|| format!("get signed entity by id failure, id: {signed_entity_id}"))
91 }
92
93 async fn get_signed_entity_by_certificate_id(
94 &self,
95 certificate_id: &str,
96 ) -> StdResult<Option<SignedEntityRecord>> {
97 self.connection
98 .fetch_first(GetSignedEntityRecordQuery::by_certificate_id(
99 certificate_id,
100 ))
101 .with_context(|| {
102 format!(
103 "get signed entity by certificate id failure, certificate_id: {certificate_id}"
104 )
105 })
106 }
107
108 async fn get_signed_entities_by_certificates_ids<'a>(
109 &self,
110 certificates_ids: &[&'a str],
111 ) -> StdResult<Vec<SignedEntityRecord>> {
112 self.connection
113 .fetch_collect(GetSignedEntityRecordQuery::by_certificates_ids(
114 certificates_ids,
115 ))
116 }
117
118 async fn get_last_signed_entities_by_type(
119 &self,
120 signed_entity_type_id: &SignedEntityTypeDiscriminants,
121 total: usize,
122 ) -> StdResult<Vec<SignedEntityRecord>> {
123 let cursor = self
124 .connection
125 .fetch(GetSignedEntityRecordQuery::by_signed_entity_type(
126 signed_entity_type_id,
127 )?)
128 .with_context(|| {
129 format!("get last signed entity by type failure, type: {signed_entity_type_id:?}")
130 })?;
131 let signed_entities: Vec<SignedEntityRecord> = cursor.take(total).collect();
132
133 Ok(signed_entities)
134 }
135
136 async fn get_cardano_stake_distribution_signed_entity_by_epoch(
137 &self,
138 epoch: Epoch,
139 ) -> StdResult<Option<SignedEntityRecord>> {
140 self.connection
141 .fetch_first(GetSignedEntityRecordQuery::cardano_stake_distribution_by_epoch(epoch))
142 }
143
144 async fn update_signed_entities(
145 &self,
146 signed_entities: Vec<SignedEntityRecord>,
147 ) -> StdResult<Vec<SignedEntityRecord>> {
148 let mut updated_records = vec![];
149
150 for record in signed_entities {
151 let id = record.signed_entity_id.clone();
152 let updated_record =
153 self.connection.fetch_first(UpdateSignedEntityQuery::one(record)?)?;
154
155 updated_records.push(updated_record.unwrap_or_else(|| {
156 panic!("Updating a signed_entity should not return nothing, id = {id:?}",)
157 }));
158 }
159
160 Ok(updated_records)
161 }
162}
163
164#[cfg(test)]
165mod tests {
166 use mithril_common::{
167 entities::{Epoch, MithrilStakeDistribution, Snapshot},
168 signable_builder::SignedEntity,
169 test::double::fake_data,
170 };
171
172 use crate::database::test_helper::{insert_signed_entities, main_db_connection};
173
174 use super::*;
175
176 fn insert_golden_signed_entities(connection: &SqliteConnection) {
177 connection
178 .execute(r#"
179 -- Cardano immutable file full
180 insert into signed_entity values(
181 'bfcd77e372a25e13353bb77697d0d08785ba98b703e22640a317c5054dc05fb1',
182 2,
183 '258edf0f1238c60985d0229869a6d4c4c635c118915b4d524d2686515be99946',
184 '{"epoch":142,"immutable_file_number":2847}',
185 '2023-05-09T13:11:15Z',
186 '{
187 "digest":"bfcd77e372a25e13353bb77697d0d08785ba98b703e22640a317c5054dc05fb1",
188 "network":"preview",
189 "beacon":{"epoch":142,"immutable_file_number":2847},
190 "size":1689696245,
191 "locations":["https://storage.googleapis.com/mithril-testing-preview-cs/preview-e142-i2847.bfcd77e372a25e13353bb77697d0d08785ba98b703e22640a317c5054dc05fb1.tar.gz"],
192 "compression_algorithm":"gzip",
193 "cardano_node_version": "0.0.1"
194 }'
195 );
196
197 -- Mithril stake distribution
198 insert into signed_entity
199 values(
200 '2da62e3ffee5e284ffd1e29ee52ee5547c5ff5ef34bee0a49dc54ea5e375f77e',
201 0,
202 'ad2d3705693dfaae8baac099b6976a5cc3e0f708245d0fa79d149a3fcbc79f00',
203 203,
204 '2023-05-16T02:17:16.203859116Z',
205 '{
206 "type":"MithrilStakeDistribution",
207 "epoch":203,
208 "signers_with_stake":[{
209 "party_id":"pool1r0tln8nct3mpyvehgy6uu3cdlmjnmtr2fxjcqnfl6v0qg0we42e",
210 "verification_key":"7b22766b223a5b3138352c3132342c3231382c31362c3133312c3137382c3136302c37312c35382c3235312c31382c36382c37372c3135342c35382c3131352c3133392c3139392c38392c3230382c3139312c3235332c3138362c3232302c3133372c3135382c34312c3230332c382c3136352c3232362c3139342c3133382c3135322c35382c3131352c35342c3136322c3230332c32322c32332c3232382c3139342c34382c3137322c3139342c3130352c36382c302c3138302c3131332c3230312c3130392c3234372c39362c39342c3232372c3135372c36322c3139352c3134382c33352c3230352c3133372c3132312c3135322c3130302c3138342c3136372c3230362c3133322c34352c3133382c3131312c38392c3138322c3230352c3138372c3135382c32322c32332c3231382c36342c3137332c35392c3134312c3133332c3138302c3131392c36302c3134392c3134382c38332c3234312c3230312c33375d2c22706f70223a5b3137352c3135382c3130322c34352c3133322c38352c33312c3130342c36352c3230342c38352c312c34332c3137382c3138372c3233382c3135372c32372c39312c3230332c35342c37332c36322c35352c3131322c3131352c302c32312c3130302c3230382c37392c3135382c3233332c3132372c38332c3234352c3134362c3231382c3131382c3139332c38322c3139352c3137302c32312c36382c3231342c3138352c38372c3136382c3135372c3230322c3136382c3132392c3233332c38372c3230332c37372c36332c3232312c31362c3130392c33302c3235312c35312c38342c36392c3233372c39382c3133372c36302c39312c37362c38302c3232322c302c3130342c3231332c3132352c31332c3135312c3133312c3130312c3230312c33322c3138392c3137362c3139392c3131342c3234302c31352c33312c3136302c31332c3136352c32372c3134335d7d",
211 "verification_key_signature":"7b227369676d61223a7b227369676d61223a7b227369676d61223a7b227369676d61223a7b227369676d61223a7b227369676d61223a5b36322c33302c32362c3131302c3134382c3137342c36302c32392c3139302c34362c37342c3135392c3137312c3134362c31342c3231362c37352c32302c38352c3134342c32332c3134352c3132352c39382c36362c3132342c3139332c32352c3233352c3234372c3130342c382c352c3133342c302c3134302c3131352c33362c31342c33382c31322c34392c39372c33392c3232312c3234352c39322c362c35302c3134362c3135372c3136362c32382c38352c33312c33352c3232392c3233312c34332c3230322c34372c3235352c3138322c375d2c226c68735f706b223a5b3234322c3132322c34322c39332c39352c31322c36352c3131332c31342c35322c3135352c3133372c3130312c3137382c3232362c3133332c31372c39302c3138332c3132312c3136362c35322c342c39312c3135332c3232332c32352c3133372c37332c3137332c3235332c3233315d2c227268735f706b223a5b322c3231312c3230372c3234392c3234322c362c3131322c362c3235322c31322c3135362c3139332c38362c3133362c3138352c36342c3132342c35302c3230392c38382c3138322c3133352c32392c3138372c3133302c3138392c34312c3134302c34322c33342c3135392c3234365d7d2c226c68735f706b223a5b37352c3232312c3235302c3235322c3135382c3134362c35362c34312c39382c3137362c3139382c3231392c33352c3130392c3136332c36312c3139362c3139342c3137382c3130392c3132382c3131352c3130302c3135322c33392c3231392c35382c34392c3235302c33312c3138342c395d2c227268735f706b223a5b3135372c3232312c38372c3139342c3235322c3234382c3132372c33312c3136362c3235322c3233342c3232362c33362c3139352c3230312c33312c34372c3232302c3233372c3137342c3130372c3134342c33382c3234372c3135352c3135382c34372c3139302c3235322c3134302c3235342c3131375d7d2c226c68735f706b223a5b34322c37372c37392c36302c3137312c3234372c31392c3230332c3232302c36332c3231352c3135372c3132392c3230382c3135382c35352c3131302c3232312c3139372c3233322c38372c33312c31312c3235342c3133352c32372c3234352c3137352c3135342c3231382c3232312c3138345d2c227268735f706b223a5b36382c3230332c38362c31352c37352c33352c3232332c342c3130392c3234392c3231372c3132352c34372c3231372c3130342c36352c3131332c3234312c3235332c3138332c3138362c36362c37352c3135302c3233342c3138362c3137332c3233302c3130332c3139342c3135322c3132375d7d2c226c68735f706b223a5b3133312c38372c3135382c3233352c34312c3233372c33332c34362c3235342c38302c3235322c3132392c37332c3234382c3135332c33382c3138332c33342c3231362c3135362c3131302c36392c37322c39302c32382c36382c3131342c33352c33352c3134332c3234312c3231305d2c227268735f706b223a5b3232382c3135352c3133332c34312c3137392c39342c3233362c3133392c3231362c3136302c3130382c3137362c3134362c3232352c3134302c3231352c35392c3130372c32302c3133372c3139372c33392c3135332c3132362c3233372c3135382c3132332c392c3133322c3139342c3132312c3232355d7d2c226c68735f706b223a5b3232322c39362c35332c34312c32342c38382c3136342c39382c3133312c33342c3132362c3133392c32382c37342c34362c3137332c35302c3133362c39372c3137312c3130312c3136322c33312c3137352c32332c3130352c3231352c36332c37362c3132342c31322c3131365d2c227268735f706b223a5b3133382c31382c31302c352c3231382c3134372c35332c35322c33362c3234342c33362c3131302c31302c33382c3134382c3132332c3235302c3131352c36342c36372c3137332c3130352c3137392c3235342c3130352c332c3132372c32302c31322c3230352c37372c3230365d7d2c226c68735f706b223a5b3132342c382c37312c3135302c34352c3130362c3232322c3234372c3130302c3137342c34352c3135322c3136312c3130382c3135382c32372c3234342c35362c3131352c3233322c3136332c3234342c38372c3138332c3232372c3235302c3232372c3234382c3137352c3136332c3230392c37345d2c227268735f706b223a5b3134302c33372c3131392c36332c39302c3132302c3131332c3135372c3130352c34362c31342c33332c3230372c3131322c3131332c3235342c38342c37332c3131302c33392c392c3230372c3133312c342c3232352c39302c3135312c32302c31352c36342c39372c39385d7d",
212 "operational_certificate":"5b5b5b3138332c33342c3231362c34362c3232372c3235312c37342c3130312c31352c3233332c3234392c34322c312c37372c37322c3234382c3137392c32312c3137332c3131332c3131382c3139382c36322c3133352c34352c38382c3138372c3233332c34302c37322c31362c36365d2c312c3132332c5b31362c3136392c3134312c3138332c32322c3137342c3131312c33322c36342c35322c3234392c36382c3230322c33352c3130362c332c38362c3230352c37382c3230302c3138362c39342c3139372c3232382c37392c3137352c32392c31342c3132382c36332c35392c3139382c36322c3233302c34362c34312c38342c39382c3131392c3134352c32392c3132312c33352c3139372c3132382c3137322c302c3135342c392c31332c32362c3138332c3138362c3138362c33312c3234392c3133322c3232392c3235332c3134332c3130322c3235342c3231322c315d5d2c5b3234312c32372c31332c34342c3131342c37382c3138392c3234392c3135302c3135302c35332c3134342c3233362c3135312c38382c3134302c3132382c3136322c36302c3232382c38382c3131312c392c3134342c3233322c38332c39342c3231302c3135362c3136382c33352c3234325d5d",
213 "kes_period":12,
214 "stake":9497629046
215 }],
216 "hash":"2da62e3ffee5e284ffd1e29ee52ee5547c5ff5ef34bee0a49dc54ea5e375f77e",
217 "protocol_parameters":{"k":2422,"m":20973,"phi_f":0.2}}'
218 );
219
220 "#,
221 )
222 .unwrap();
223 }
224
225 #[tokio::test]
226 async fn test_golden_master() {
227 let connection = main_db_connection().unwrap();
228 insert_golden_signed_entities(&connection);
229
230 let store = SignedEntityStore::new(Arc::new(connection));
231 let cardano_immutable_files_fulls: Vec<SignedEntity<Snapshot>> = store
232 .get_last_signed_entities_by_type(
233 &SignedEntityTypeDiscriminants::CardanoImmutableFilesFull,
234 usize::MAX,
235 )
236 .await
237 .expect("Getting Golden snapshot signed entities should not fail")
238 .into_iter()
239 .map(|r| r.try_into().unwrap())
240 .collect();
241 let mithril_stake_distributions: Vec<SignedEntity<MithrilStakeDistribution>> = store
242 .get_last_signed_entities_by_type(
243 &SignedEntityTypeDiscriminants::MithrilStakeDistribution,
244 usize::MAX,
245 )
246 .await
247 .expect("Getting Golden mithril stake distribution signed entities should not fail")
248 .into_iter()
249 .map(|r| r.try_into().unwrap())
250 .collect();
251
252 assert_eq!(cardano_immutable_files_fulls.len(), 1);
253 assert_eq!(mithril_stake_distributions.len(), 1);
254 }
255
256 #[tokio::test]
257 async fn test_get_signed_entity_record_by_certificate_id() {
258 let expected_record = SignedEntityRecord::fake_records(1).remove(0);
259 let connection = main_db_connection().unwrap();
260 insert_signed_entities(&connection, vec![expected_record.clone()]).unwrap();
261 let store = SignedEntityStore::new(Arc::new(connection));
262
263 let record = store
264 .get_signed_entity_by_certificate_id(&expected_record.certificate_id)
265 .await
266 .expect("querying signed entity record by certificate id should not fail");
267
268 assert_eq!(Some(expected_record), record);
269 }
270
271 #[tokio::test]
272 async fn test_get_signed_entity_record_by_certificates_ids() {
273 let expected_records = SignedEntityRecord::fake_records(3);
274 let connection = main_db_connection().unwrap();
275 insert_signed_entities(&connection, expected_records.clone()).unwrap();
276 let store = SignedEntityStore::new(Arc::new(connection));
277 let certificates_ids: Vec<&str> =
278 expected_records.iter().map(|r| r.certificate_id.as_str()).collect();
279
280 let queried_records = store
281 .get_signed_entities_by_certificates_ids(&certificates_ids)
282 .await
283 .expect("querying signed entity record by certificates ids should not fail");
284
285 assert_eq!(
286 expected_records.into_iter().rev().collect::<Vec<_>>(),
288 queried_records
289 );
290 }
291
292 #[tokio::test]
293 async fn update_only_given_entities() {
294 let mut signed_entity_records = SignedEntityRecord::fake_records(5);
295
296 let connection = main_db_connection().unwrap();
297 insert_signed_entities(&connection, signed_entity_records.clone()).unwrap();
298 let store = SignedEntityStore::new(Arc::new(connection));
299
300 let records_to_update: Vec<SignedEntityRecord> = signed_entity_records
301 .drain(2..)
302 .map(|mut r| {
303 r.certificate_id = format!("updated-{}", r.certificate_id);
304 r
305 })
306 .collect();
307 let expected_records: Vec<SignedEntityRecord> = signed_entity_records
308 .into_iter()
309 .chain(records_to_update.clone())
310 .rev() .collect();
312
313 let updated_records = store
314 .update_signed_entities(records_to_update.clone())
315 .await
316 .expect("updating signed entities should not fail");
317
318 let stored_records = store
319 .get_last_signed_entities_by_type(
320 &SignedEntityTypeDiscriminants::CardanoImmutableFilesFull,
321 usize::MAX,
322 )
323 .await
324 .expect("getting signed entities should not fail");
325
326 assert_eq!(records_to_update, updated_records);
327 assert_eq!(expected_records, stored_records);
328 }
329
330 #[tokio::test]
331 async fn get_cardano_stake_distribution_signed_entity_by_epoch_when_nothing_found() {
332 let epoch_to_retrieve = Epoch(4);
333 let connection = main_db_connection().unwrap();
334 let store = SignedEntityStore::new(Arc::new(connection));
335
336 let record = store
337 .get_cardano_stake_distribution_signed_entity_by_epoch(epoch_to_retrieve)
338 .await
339 .unwrap();
340
341 assert_eq!(None, record);
342 }
343
344 #[tokio::test]
345 async fn get_cardano_stake_distribution_signed_entity_by_epoch_when_signed_entity_found_for_epoch()
346 {
347 let cardano_stake_distribution = fake_data::cardano_stake_distribution(Epoch(4));
348
349 let expected_record: SignedEntityRecord = cardano_stake_distribution.into();
350
351 let connection = main_db_connection().unwrap();
352 insert_signed_entities(&connection, vec![expected_record.clone()]).unwrap();
353 let store = SignedEntityStore::new(Arc::new(connection));
354
355 let record = store
356 .get_cardano_stake_distribution_signed_entity_by_epoch(Epoch(4))
357 .await
358 .unwrap();
359
360 assert_eq!(Some(expected_record), record);
361 }
362}