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
use crate::certificate::PoolId;
use imhamt::{Hamt, HamtIter, InsertError};
use std::collections::hash_map::DefaultHasher;

/// Count how many blocks have been created by a specific Pool
#[derive(Clone, PartialEq, Eq)]
pub struct LeadersParticipationRecord {
    total: u32,
    log: Hamt<DefaultHasher, PoolId, u32>,
}

impl Default for LeadersParticipationRecord {
    fn default() -> Self {
        Self::new()
    }
}

impl LeadersParticipationRecord {
    pub fn total(&self) -> u32 {
        self.total
    }

    pub fn nb_participants(&self) -> usize {
        self.log.size()
    }

    /// new empty leader log
    pub fn new() -> Self {
        Self {
            total: 0,
            log: Hamt::new(),
        }
    }

    /// Add one count to a pool. if the pool doesn't exist, then set it to 1
    pub fn increase_for(&mut self, pool: &PoolId) {
        self.total += 1;
        self.log = self
            .log
            .insert_or_update_simple(pool.clone(), 1, |v| Some(v + 1));
    }

    /// Set a pool id to a specific value.
    ///
    /// if the value already exists, then it returns an insert error.
    /// This should only be used related to the iterator construction,
    pub fn set_for(&mut self, pool: PoolId, v: u32) -> Result<(), InsertError> {
        self.log = self.log.insert(pool, v)?;
        self.total += v;
        Ok(())
    }

    /// Iterate over all known pool record
    pub fn iter(&self) -> HamtIter<'_, PoolId, u32> {
        self.log.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{certificate::PoolId, testing::builders::StakePoolBuilder};

    #[test]
    pub fn test_total() {
        let leaders_participation_record = create_log(vec![
            (new_stake_pool_id(), 10),
            (new_stake_pool_id(), 0),
            (new_stake_pool_id(), 11),
            (new_stake_pool_id(), 5),
        ]);
        verify_participants_count(&leaders_participation_record, 4);
        verify_total(&leaders_participation_record, 26);
    }

    #[test]
    pub fn test_increase_for_existing_pool() {
        let stake_pool_id = new_stake_pool_id();

        let mut leaders_participation_record = create_log(vec![(stake_pool_id.clone(), 1)]);

        leaders_participation_record.increase_for(&stake_pool_id);

        assert_eq!(
            2,
            get_count(&leaders_participation_record, &stake_pool_id).unwrap(),
            "wrong count for existing stake pool"
        );
        verify_participants_count(&leaders_participation_record, 1);
        verify_total(&leaders_participation_record, 2);
    }

    #[test]
    pub fn test_increase_for_non_existing_pool() {
        let stake_pool_id = new_stake_pool_id();
        let non_existing_stake_pool_id = new_stake_pool_id();

        let mut leaders_participation_record = create_log(vec![(stake_pool_id.clone(), 1)]);

        leaders_participation_record.increase_for(&non_existing_stake_pool_id);

        assert_eq!(
            1,
            get_count(&leaders_participation_record, &non_existing_stake_pool_id).unwrap(),
            "wrong count for new stake pool"
        );
        assert_eq!(
            1,
            get_count(&leaders_participation_record, &stake_pool_id).unwrap(),
            "wrong count for existing stake pool"
        );

        verify_participants_count(&leaders_participation_record, 2);
        verify_total(&leaders_participation_record, 2);
    }

    #[test]
    pub fn test_set_new_value_for_existing_stake_pool() {
        let stake_pool_id = new_stake_pool_id();

        let mut leaders_participation_record = create_log(vec![(stake_pool_id.clone(), 1)]);

        assert_eq!(
            InsertError::EntryExists,
            leaders_participation_record
                .set_for(stake_pool_id.clone(), 10)
                .err()
                .unwrap()
        );

        assert_eq!(
            1,
            get_count(&leaders_participation_record, &stake_pool_id).unwrap(),
            "wrong count for new stake pool"
        );

        verify_participants_count(&leaders_participation_record, 1);
        verify_total(&leaders_participation_record, 1);
    }

    #[test]
    pub fn test_set_duplicated_value_for_existing_stake_pool() {
        let first_stake_pool_id = new_stake_pool_id();

        let mut leaders_participation_record = create_log(vec![(first_stake_pool_id.clone(), 1)]);

        assert_eq!(
            InsertError::EntryExists,
            leaders_participation_record
                .set_for(first_stake_pool_id, 1)
                .err()
                .unwrap()
        );
        verify_total(&leaders_participation_record, 1);
    }

    #[test]
    pub fn test_set_new_value_for_non_existing_stake_pool() {
        let stake_pool_id = new_stake_pool_id();

        let mut leaders_participation_record = create_log(vec![(new_stake_pool_id(), 1)]);

        leaders_participation_record
            .set_for(stake_pool_id.clone(), 10)
            .expect("unexpected panic when set for first stake pool");

        assert_eq!(
            10,
            get_count(&leaders_participation_record, &stake_pool_id).unwrap(),
            "wrong count for new stake pool"
        );

        verify_participants_count(&leaders_participation_record, 2);
        verify_total(&leaders_participation_record, 11);
    }

    fn create_log(records: Vec<(PoolId, u32)>) -> LeadersParticipationRecord {
        let mut leaders_participation_record = LeadersParticipationRecord::new();
        for (pool_id, count) in records.iter() {
            leaders_participation_record
                .set_for(pool_id.clone(), *count)
                .expect("panic when filling records");
        }
        leaders_participation_record
    }

    fn get_count(
        leaders_participation_record: &LeadersParticipationRecord,
        stake_pool_id: &PoolId,
    ) -> Option<u32> {
        leaders_participation_record
            .iter()
            .find(|x| *x.0 == *stake_pool_id)
            .map(|x| *x.1)
    }

    fn new_stake_pool_id() -> PoolId {
        StakePoolBuilder::new().build().id()
    }

    fn verify_total(leaders_participation_record: &LeadersParticipationRecord, count: u32) {
        let actual = leaders_participation_record.total();
        assert_eq!(actual, count, "wrong total value {} vs {}", actual, count);
    }

    fn verify_participants_count(
        leaders_participation_record: &LeadersParticipationRecord,
        count: u32,
    ) {
        let actual = leaders_participation_record.nb_participants();
        assert_eq!(
            actual, count as usize,
            "wrong no of participants {} vs {}",
            actual, count
        );
    }
}