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
use std::collections::HashMap;

use async_trait::async_trait;
use mithril_common::StdResult;
use slog_scope::debug;
use tokio::sync::RwLock;

use mithril_common::entities::{Epoch, ProtocolParameters};

/// Store and get [protocol parameters][ProtocolParameters] for given epoch.
#[async_trait]
pub trait ProtocolParametersStorer: Sync + Send {
    /// Save the given `ProtocolParameter` for the given [Epoch].
    async fn save_protocol_parameters(
        &self,
        epoch: Epoch,
        protocol_parameters: ProtocolParameters,
    ) -> StdResult<Option<ProtocolParameters>>;

    /// Get the saved `ProtocolParameter` for the given [Epoch] if any.
    async fn get_protocol_parameters(&self, epoch: Epoch) -> StdResult<Option<ProtocolParameters>>;

    /// Handle discrepancies at startup in the protocol parameters store.
    /// In case an aggregator has been launched after some epochs of not being up or at initial startup,
    /// the discrepancies in the protocol parameters store needs to be fixed.
    /// The protocol parameters needs to be recorded for the working epoch and the next 2 epochs.
    async fn handle_discrepancies_at_startup(
        &self,
        current_epoch: Epoch,
        configuration_protocol_parameters: &ProtocolParameters,
    ) -> StdResult<()> {
        for epoch_offset in 0..=2 {
            let epoch = current_epoch + epoch_offset;
            if self.get_protocol_parameters(epoch).await?.is_none() {
                debug!("Handle discrepancies at startup of protocol parameters store, will record protocol parameters from the configuration for epoch {epoch}: {configuration_protocol_parameters:?}");
                self.save_protocol_parameters(epoch, configuration_protocol_parameters.clone())
                    .await?;
            }
        }

        Ok(())
    }
}

pub struct FakeProtocolParametersStorer {
    pub protocol_parameters: RwLock<HashMap<Epoch, ProtocolParameters>>,
}

impl FakeProtocolParametersStorer {
    #[cfg(test)]
    pub fn new(data: Vec<(Epoch, ProtocolParameters)>) -> Self {
        let protocol_parameters = RwLock::new(data.into_iter().collect());
        Self {
            protocol_parameters,
        }
    }
}

#[async_trait]
impl ProtocolParametersStorer for FakeProtocolParametersStorer {
    async fn save_protocol_parameters(
        &self,
        epoch: Epoch,
        protocol_parameters: ProtocolParameters,
    ) -> StdResult<Option<ProtocolParameters>> {
        let mut protocol_paremeters = self.protocol_parameters.write().await;
        Ok(protocol_paremeters.insert(epoch, protocol_parameters))
    }

    async fn get_protocol_parameters(&self, epoch: Epoch) -> StdResult<Option<ProtocolParameters>> {
        let protocol_paremeters = self.protocol_parameters.read().await;
        Ok(protocol_paremeters.get(&epoch).cloned())
    }
}

#[cfg(test)]
mod tests {

    use mithril_common::test_utils::fake_data;

    use super::*;

    #[tokio::test]
    async fn test_save_protocol_parameters_do_not_exist_yet() {
        let protocol_parameters = fake_data::protocol_parameters();
        let epoch = Epoch(1);
        let store = FakeProtocolParametersStorer::new(vec![]);
        let protocol_parameters_previous = store
            .save_protocol_parameters(epoch, protocol_parameters)
            .await
            .unwrap();

        assert!(protocol_parameters_previous.is_none());
    }

    #[tokio::test]
    async fn test_save_protocol_parameters_already_exist() {
        let protocol_parameters = fake_data::protocol_parameters();
        let epoch = Epoch(1);
        let store = FakeProtocolParametersStorer::new(vec![(epoch, protocol_parameters.clone())]);
        let protocol_parameters_new = ProtocolParameters {
            k: protocol_parameters.k + 1,
            ..protocol_parameters
        };
        let protocol_parameters_previous = store
            .save_protocol_parameters(epoch, protocol_parameters_new)
            .await
            .unwrap();

        assert_eq!(Some(protocol_parameters), protocol_parameters_previous);
    }

    #[tokio::test]
    async fn test_get_protocol_parameters_exist() {
        let protocol_parameters = fake_data::protocol_parameters();
        let epoch = Epoch(1);
        let store = FakeProtocolParametersStorer::new(vec![(epoch, protocol_parameters.clone())]);
        let protocol_parameters_stored = store.get_protocol_parameters(epoch).await.unwrap();

        assert_eq!(Some(protocol_parameters), protocol_parameters_stored);
    }

    #[tokio::test]
    async fn test_get_protocol_parameters_do_not_exist() {
        let protocol_parameters = fake_data::protocol_parameters();
        let epoch = Epoch(1);
        let store = FakeProtocolParametersStorer::new(vec![(epoch, protocol_parameters.clone())]);
        let protocol_parameters_stored = store.get_protocol_parameters(epoch + 1).await.unwrap();

        assert!(protocol_parameters_stored.is_none());
    }

    #[tokio::test]
    async fn test_handle_discrepandies_at_startup_should_complete_at_least_two_epochs() {
        let protocol_parameters = fake_data::protocol_parameters();
        let protocol_parameters_new = ProtocolParameters {
            k: protocol_parameters.k + 1,
            ..protocol_parameters
        };
        let epoch = Epoch(1);
        let store = FakeProtocolParametersStorer::new(vec![
            (epoch, protocol_parameters.clone()),
            (epoch + 1, protocol_parameters.clone()),
        ]);

        store
            .handle_discrepancies_at_startup(epoch, &protocol_parameters_new)
            .await
            .unwrap();

        let protocol_parameters_stored = store.get_protocol_parameters(epoch).await.unwrap();
        assert_eq!(
            Some(protocol_parameters.clone()),
            protocol_parameters_stored
        );

        let protocol_parameters_stored = store.get_protocol_parameters(epoch + 1).await.unwrap();
        assert_eq!(
            Some(protocol_parameters.clone()),
            protocol_parameters_stored
        );

        let protocol_parameters_stored = store.get_protocol_parameters(epoch + 2).await.unwrap();
        assert_eq!(
            Some(protocol_parameters_new.clone()),
            protocol_parameters_stored
        );

        let protocol_parameters_stored = store.get_protocol_parameters(epoch + 3).await.unwrap();
        assert!(protocol_parameters_stored.is_none());
    }
}