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
use anyhow::Context;
use async_trait::async_trait;
use std::sync::Arc;

use mithril_common::entities::{SignedEntityTypeDiscriminants, SingleSignatures};
use mithril_common::{StdError, StdResult};
use mithril_persistence::sqlite::{ConnectionExtensions, SqliteConnection};

use crate::database::query::{
    DeleteBufferedSingleSignatureQuery, GetBufferedSingleSignatureQuery,
    InsertOrReplaceBufferedSingleSignatureRecordQuery,
};
use crate::database::record::BufferedSingleSignatureRecord;
use crate::services::BufferedSingleSignatureStore;

/// An implementation of [BufferedSingleSignatureStore] that uses a SQLite database.
pub struct BufferedSingleSignatureRepository {
    connection: Arc<SqliteConnection>,
}

impl BufferedSingleSignatureRepository {
    /// Creates a new [BufferedSingleSignatureRepository] instance.
    pub fn new(connection_pool: Arc<SqliteConnection>) -> Self {
        Self {
            connection: connection_pool,
        }
    }

    #[cfg(test)]
    fn get_all(&self) -> StdResult<Vec<BufferedSingleSignatureRecord>> {
        self.connection
            .fetch_collect(GetBufferedSingleSignatureQuery::all())
    }

    fn get_by_discriminant<T>(
        &self,
        signed_entity_type_discriminant: SignedEntityTypeDiscriminants,
    ) -> StdResult<Vec<T>>
    where
        T: TryFrom<BufferedSingleSignatureRecord>,
        StdError: From<T::Error>,
    {
        let records: Vec<BufferedSingleSignatureRecord> =
            self.connection
                .fetch_collect(GetBufferedSingleSignatureQuery::by_discriminant(
                    signed_entity_type_discriminant,
                ))?;

        let mut entities: Vec<T> = Vec::with_capacity(records.len());
        for record in records {
            entities.push(record.try_into()?);
        }

        Ok(entities)
    }
}

#[async_trait]
impl BufferedSingleSignatureStore for BufferedSingleSignatureRepository {
    async fn buffer_signature(
        &self,
        signed_entity_type_discriminant: SignedEntityTypeDiscriminants,
        signature: &SingleSignatures,
    ) -> StdResult<()> {
        let record = BufferedSingleSignatureRecord::try_from_single_signatures(
            signature,
            signed_entity_type_discriminant,
        )
        .with_context(|| "Failed to convert SingleSignatures to BufferedSingleSignatureRecord")?;

        self.connection
            .fetch_first(InsertOrReplaceBufferedSingleSignatureRecordQuery::one(
                record,
            ))?;

        Ok(())
    }

    async fn get_buffered_signatures(
        &self,
        signed_entity_type_discriminant: SignedEntityTypeDiscriminants,
    ) -> StdResult<Vec<SingleSignatures>> {
        self.get_by_discriminant(signed_entity_type_discriminant)
    }

    async fn remove_buffered_signatures(
        &self,
        signed_entity_type_discriminant: SignedEntityTypeDiscriminants,
        single_signatures: Vec<SingleSignatures>,
    ) -> StdResult<()> {
        let signatures_party_ids = single_signatures.into_iter().map(|s| s.party_id).collect();
        self.connection.fetch_first(
            DeleteBufferedSingleSignatureQuery::by_discriminant_and_party_ids(
                signed_entity_type_discriminant,
                signatures_party_ids,
            ),
        )?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use mithril_common::entities::SignedEntityTypeDiscriminants::{
        CardanoTransactions, MithrilStakeDistribution,
    };
    use mithril_common::test_utils::fake_keys;

    use crate::database::record::{strip_buffered_sigs_date, BufferedSingleSignatureRecord};
    use crate::database::test_helper::{insert_buffered_single_signatures, main_db_connection};

    use super::*;

    #[test]
    fn retrieve_all() {
        let connection = main_db_connection().unwrap();
        insert_buffered_single_signatures(
            &connection,
            BufferedSingleSignatureRecord::fakes(&[
                ("party1", CardanoTransactions),
                ("party2", CardanoTransactions),
                ("party3", MithrilStakeDistribution),
            ]),
        )
        .unwrap();

        let store = BufferedSingleSignatureRepository::new(Arc::new(connection));

        let buffered_signatures_ctx = store.get_all().unwrap();
        assert_eq!(
            strip_buffered_sigs_date(&BufferedSingleSignatureRecord::fakes(&[
                ("party3", MithrilStakeDistribution),
                ("party2", CardanoTransactions),
                ("party1", CardanoTransactions),
            ])),
            strip_buffered_sigs_date(&buffered_signatures_ctx)
        );
    }

    #[tokio::test]
    async fn retrieve_signatures_by_discriminant() {
        let connection = main_db_connection().unwrap();
        insert_buffered_single_signatures(
            &connection,
            BufferedSingleSignatureRecord::fakes(&[
                ("party1", CardanoTransactions),
                ("party2", CardanoTransactions),
                ("party3", MithrilStakeDistribution),
            ]),
        )
        .unwrap();

        let store = BufferedSingleSignatureRepository::new(Arc::new(connection));

        let buffered_signatures_ctx = store
            .get_by_discriminant::<BufferedSingleSignatureRecord>(CardanoTransactions)
            .unwrap();
        assert_eq!(
            strip_buffered_sigs_date(&BufferedSingleSignatureRecord::fakes(&[
                ("party2", CardanoTransactions),
                ("party1", CardanoTransactions),
            ])),
            strip_buffered_sigs_date(&buffered_signatures_ctx)
        );

        let buffered_signatures_msd = store
            .get_by_discriminant::<BufferedSingleSignatureRecord>(MithrilStakeDistribution)
            .unwrap();
        assert_eq!(
            strip_buffered_sigs_date(&BufferedSingleSignatureRecord::fakes(&[(
                "party3",
                MithrilStakeDistribution
            ),])),
            strip_buffered_sigs_date(&buffered_signatures_msd)
        );
    }

    #[tokio::test]
    async fn store_signatures() {
        let connection = main_db_connection().unwrap();
        let store = BufferedSingleSignatureRepository::new(Arc::new(connection));

        // Multiple signatures of the same signed entity type
        {
            store
                .buffer_signature(
                    CardanoTransactions,
                    &SingleSignatures::new(
                        "party1",
                        fake_keys::single_signature()[0].try_into().unwrap(),
                        vec![1],
                    ),
                )
                .await
                .unwrap();
            store
                .buffer_signature(
                    CardanoTransactions,
                    &SingleSignatures::new(
                        "party2",
                        fake_keys::single_signature()[1].try_into().unwrap(),
                        vec![2],
                    ),
                )
                .await
                .unwrap();

            let buffered_signatures = store
                .get_buffered_signatures(CardanoTransactions)
                .await
                .unwrap();
            assert_eq!(
                vec![
                    SingleSignatures::new(
                        "party2",
                        fake_keys::single_signature()[1].try_into().unwrap(),
                        vec![2],
                    ),
                    SingleSignatures::new(
                        "party1",
                        fake_keys::single_signature()[0].try_into().unwrap(),
                        vec![1],
                    ),
                ],
                buffered_signatures
            );
        }
        // Another signed entity type to test that the store is able to differentiate between them
        {
            store
                .buffer_signature(
                    MithrilStakeDistribution,
                    &SingleSignatures::new(
                        "party3",
                        fake_keys::single_signature()[2].try_into().unwrap(),
                        vec![3],
                    ),
                )
                .await
                .unwrap();

            let buffered_signatures = store
                .get_buffered_signatures(MithrilStakeDistribution)
                .await
                .unwrap();
            assert_eq!(
                vec![SingleSignatures::new(
                    "party3",
                    fake_keys::single_signature()[2].try_into().unwrap(),
                    vec![3],
                )],
                buffered_signatures
            );
        }
    }

    #[tokio::test]
    async fn remove_buffered_signatures() {
        let connection = main_db_connection().unwrap();
        insert_buffered_single_signatures(
            &connection,
            BufferedSingleSignatureRecord::fakes(&[
                ("party1", MithrilStakeDistribution),
                ("party2", MithrilStakeDistribution),
                ("party3", MithrilStakeDistribution),
                ("party4", CardanoTransactions),
            ]),
        )
        .unwrap();

        let store = BufferedSingleSignatureRepository::new(Arc::new(connection));

        store
            .remove_buffered_signatures(
                MithrilStakeDistribution,
                vec![
                    BufferedSingleSignatureRecord::fake("party1", MithrilStakeDistribution)
                        .try_into()
                        .unwrap(),
                    BufferedSingleSignatureRecord::fake("party3", MithrilStakeDistribution)
                        .try_into()
                        .unwrap(),
                ],
            )
            .await
            .unwrap();

        let remaining_msd_sigs = store.get_all().unwrap();
        assert_eq!(
            strip_buffered_sigs_date(&BufferedSingleSignatureRecord::fakes(&[
                ("party4", CardanoTransactions),
                ("party2", MithrilStakeDistribution),
            ])),
            strip_buffered_sigs_date(&remaining_msd_sigs)
        );
    }
}