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
use chain_addr::Discrimination;
use jormungandr_lib::crypto::account::Identifier;
use mainnet_tools::snapshot::MainnetWalletStateExtension;
use proptest::{arbitrary::Arbitrary, prelude::*, strategy::BoxedStrategy};
use snapshot_lib::{Snapshot, VoterHIR};
use std::collections::BTreeMap;
use vit_servicing_station_lib::db::models::snapshot::{Contribution, Voter};

#[derive(Debug, Default)]
pub struct VoterSnapshot {
    /// key: Tag - a unique identifier of the current snapshot
    /// value: Timestamp - for the latest update of the current snapshot
    snapshot_tags: BTreeMap<String, i64>,
    voters: Vec<Voter>,
    contributions: Vec<Contribution>,
}

impl VoterSnapshot {
    pub fn from_config_or_default(
        initials: &Option<Initials>,
    ) -> Result<Self, mainnet_tools::snapshot::Error> {
        let mut voters = vec![];
        let mut contributions = vec![];
        let mut snapshot_tags = BTreeMap::new();

        if let Some(initials) = initials {
            snapshot_tags.insert(initials.parameters.tag.to_string(), epoch_now());

            let states: Vec<MainnetWalletState> =
                block_on(build_default(initials.content.clone()))?;
            let parameters = SnapshotParameters::default();
            let snapshot = states.try_into_raw_snapshot_request(parameters.clone())?;

            let snapshot = Snapshot::from_raw_snapshot(
                snapshot.content.snapshot,
                parameters.min_stake_threshold,
                parameters.voting_power_cap,
                &|_vk: &Identifier| String::new(),
                Discrimination::Production,
                false,
            )?
            .to_full_snapshot_info();

            for snapshot_info in snapshot {
                let voter_hir = snapshot_info.hir;

                voters.push(Voter {
                    voting_key: voter_hir.voting_key.to_bech32_str(),
                    voting_power: u64::from(voter_hir.voting_power) as i64,
                    voting_group: voter_hir.voting_group.to_string(),
                    snapshot_tag: initials.parameters.tag.to_string(),
                });

                snapshot_info.contributions.iter().for_each(|contribution| {
                    contributions.push(Contribution {
                        stake_public_key: contribution.stake_public_key.as_str().to_string(),
                        reward_address: contribution.reward_address.as_str().to_string(),
                        value: contribution.value as i64,
                        voting_key: voter_hir.voting_key.to_bech32_str(),
                        voting_group: voter_hir.voting_group.to_string(),
                        snapshot_tag: initials.parameters.tag.to_string(),
                    });
                });
            }
        }

        Ok(Self {
            snapshot_tags,
            voters,
            contributions,
        })
    }

    pub fn tags(&self) -> Vec<String> {
        self.snapshot_tags.keys().cloned().collect()
    }

    pub fn put_snapshot_tag(&mut self, tag: String, timestamp: i64) {
        self.snapshot_tags.insert(tag, timestamp);
    }

    pub fn snapshot_by_tag(&self, tag: impl Into<String>) -> Option<&i64> {
        self.snapshot_tags.get(&tag.into())
    }

    pub fn contributions_by_stake_public_key_and_snapshot_tag(
        &self,
        stake_public_key: &str,
        tag: &str,
    ) -> Vec<&Contribution> {
        self.contributions
            .iter()
            .filter(|v| v.stake_public_key == stake_public_key && v.snapshot_tag == tag)
            .collect()
    }

    pub fn total_voting_power_by_voting_group_and_snapshot_tag(
        &self,
        voting_group: &str,
        snapshot_tag: &str,
    ) -> i64 {
        self.voters
            .iter()
            .filter(|v| v.voting_group == voting_group && v.snapshot_tag == snapshot_tag)
            .map(|v| v.voting_power)
            .sum()
    }

    pub fn contributions_by_voting_key_and_voter_group_and_snapshot_tag(
        &self,
        voting_key: &str,
        voting_group: &str,
        snapshot_tag: &str,
    ) -> Vec<&Contribution> {
        self.contributions
            .iter()
            .filter(|v| {
                v.voting_key == voting_key
                    && v.voting_group == voting_group
                    && v.snapshot_tag == snapshot_tag
            })
            .collect()
    }

    pub fn voters_by_voting_key_and_snapshot_tag(
        &self,
        voting_key: &str,
        snapshot_tag: &str,
    ) -> Vec<&Voter> {
        self.voters
            .iter()
            .filter(|v| v.voting_key == voting_key && v.snapshot_tag == snapshot_tag)
            .collect()
    }

    pub fn insert_voters(&mut self, voters: Vec<Voter>) {
        for voter in voters {
            if let Some(idx) = self
                .voters
                .iter()
                .enumerate()
                .find(|(_, x)| {
                    x.voting_key == voter.voting_key
                        && x.snapshot_tag == voter.snapshot_tag
                        && x.voting_group == voter.voting_group
                })
                .map(|(idx, _)| idx)
            {
                let _ = std::mem::replace(&mut self.voters[idx], voter);
            } else {
                self.voters.push(voter)
            }
        }
    }

    pub fn insert_contributions(&mut self, contributions: Vec<Contribution>) {
        for contribution in contributions {
            if let Some(idx) = self
                .contributions
                .iter()
                .enumerate()
                .find(|(_, x)| {
                    x.stake_public_key == contribution.stake_public_key
                        && x.voting_key == contribution.voting_key
                        && x.voting_group == contribution.voting_group
                        && x.snapshot_tag == contribution.snapshot_tag
                })
                .map(|(idx, _)| idx)
            {
                let _ = std::mem::replace(&mut self.contributions[idx], contribution);
            } else {
                self.contributions.push(contribution)
            }
        }
    }
}

#[derive(Debug)]
struct ArbitraryVoterHIR(VoterHIR);

impl Arbitrary for ArbitraryVoterHIR {
    type Parameters = Option<String>;
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
        if let Some(voting_group) = args {
            any::<([u8; 32], u64)>()
                .prop_map(move |(key, voting_power)| {
                    let identifier = Identifier::from_hex(&hex::encode(key)).unwrap();
                    Self(VoterHIR {
                        voting_key: identifier.clone(),
                        voting_power: voting_power.into(),
                        voting_group: voting_group.clone(),
                        address: chain_addr::Address(
                            chain_addr::Discrimination::Production,
                            chain_addr::Kind::Account(
                                identifier
                                    .to_address(chain_addr::Discrimination::Production)
                                    .public_key()
                                    .unwrap()
                                    .to_owned(),
                            ),
                        )
                        .into(),
                        overlimit: false,
                        private_key: None,
                        underthreshold: false,
                    })
                })
                .boxed()
        } else {
            any::<([u8; 32], u64, String)>()
                .prop_map(|(key, voting_power, voting_group)| {
                    let identifier = Identifier::from_hex(&hex::encode(key)).unwrap();
                    Self(VoterHIR {
                        voting_key: identifier.clone(),
                        voting_power: voting_power.into(),
                        voting_group,
                        address: chain_addr::Address(
                            chain_addr::Discrimination::Production,
                            chain_addr::Kind::Account(
                                identifier
                                    .to_address(chain_addr::Discrimination::Production)
                                    .public_key()
                                    .unwrap()
                                    .to_owned(),
                            ),
                        )
                        .into(),
                        overlimit: false,
                        private_key: None,
                        underthreshold: false,
                    })
                })
                .boxed()
        }
    }
}

use futures::executor::block_on;
use mainnet_lib::wallet_state::{build_default, MainnetWalletState};
use mainnet_lib::{Initials, SnapshotParameters};
use time::OffsetDateTime;

fn epoch_now() -> i64 {
    OffsetDateTime::now_utc().unix_timestamp()
}

impl Arbitrary for VoterSnapshot {
    type Parameters = ();
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
        let tags = vec![
            String::from("latest"),
            String::from("fund8"),
            String::from("nightly"),
        ];
        any_with::<(Vec<ArbitraryVoterHIR>, Vec<ArbitraryVoterHIR>, usize)>((
            (Default::default(), Some("direct".to_string())),
            (Default::default(), Some("dreps".to_string())),
            (),
        ))
        .prop_map(move |(dreps, voters, random)| {
            let mut snapshot_voters = vec![];

            snapshot_voters.extend(dreps.iter().map(|drep| Voter {
                voting_key: drep.0.voting_key.to_bech32_str(),
                voting_power: u64::from(drep.0.voting_power) as i64,
                voting_group: drep.0.voting_group.to_string(),
                snapshot_tag: tags[random % tags.len()].clone(),
            }));

            snapshot_voters.extend(voters.iter().map(|voter| Voter {
                voting_key: voter.0.voting_key.to_bech32_str(),
                voting_power: u64::from(voter.0.voting_power) as i64,
                voting_group: voter.0.voting_group.to_string(),
                snapshot_tag: tags[random % tags.len()].clone(),
            }));

            let mut contributions = vec![];

            contributions.extend(snapshot_voters.iter().map(|voter| Contribution {
                stake_public_key: voter.voting_key.to_string(),
                reward_address: voter.voting_key.to_string(),
                value: voter.voting_power,
                voting_key: voter.voting_key.clone(),
                voting_group: voter.voting_group.clone(),
                snapshot_tag: voter.snapshot_tag.clone(),
            }));

            Self {
                snapshot_tags: tags.iter().cloned().map(|t| (t, epoch_now())).collect(),
                voters: snapshot_voters,
                contributions,
            }
        })
        .boxed()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tags() {
        let mut voter_snapshot = VoterSnapshot::default();

        voter_snapshot.put_snapshot_tag("a".to_string(), epoch_now());
        voter_snapshot.put_snapshot_tag("b".to_string(), epoch_now());
        voter_snapshot.put_snapshot_tag("c".to_string(), epoch_now());
        assert_eq!(
            &[String::from("a"), String::from("b"), String::from("c")],
            voter_snapshot.tags().as_slice()
        );
    }
}