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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use super::{Threshold, VoteCount};
use chain_addr::{Discrimination, Kind};
use chain_impl_mockchain::transaction::UnspecifiedAccountIdentifier;
use jormungandr_lib::crypto::account::Identifier;
use jormungandr_lib::interfaces::Address;
use rust_decimal::Decimal;
use snapshot_lib::{registration::RewardAddress, SnapshotInfo};
use std::collections::{BTreeMap, HashMap, HashSet};
use thiserror::Error;

pub const ADA_TO_LOVELACE_FACTOR: u64 = 1_000_000;
pub type Rewards = Decimal;

#[derive(Debug, Error)]
pub enum Error {
    #[error("Value overflowed its maximum value")]
    Overflow,
    #[error("Multiple snapshot entries per voter are not supported")]
    MultipleEntries,
    #[error("Unknown voter group {0}")]
    UnknownVoterGroup(String),
    #[error("Invalid blake2b256 hash")]
    InvalidHash(Vec<u8>),
}

fn calculate_reward(
    total_stake: u64,
    stake_per_voter: HashMap<Identifier, u64>,
    total_rewards: Rewards,
) -> HashMap<Identifier, Rewards> {
    stake_per_voter
        .into_iter()
        .map(|(k, v)| {
            (
                k,
                (Rewards::from(v) / Rewards::from(total_stake) * total_rewards),
            )
        })
        .collect()
}

fn filter_active_addresses(
    vote_count: VoteCount,
    snapshot_info: Vec<SnapshotInfo>,
    threshold: Threshold,
) -> Vec<SnapshotInfo> {
    snapshot_info
        .into_iter()
        .filter(|v| {
            if let Some(votes) = vote_count.get(&v.hir.voting_key) {
                threshold.filter(votes)
            } else {
                threshold.filter(&HashSet::new())
            }
        })
        .collect()
}

pub fn account_hex_to_address(
    account_hex: String,
    discrimination: Discrimination,
) -> Result<Address, hex::FromHexError> {
    let mut buffer = [0u8; 32];
    hex::decode_to_slice(account_hex, &mut buffer)?;
    let identifier: UnspecifiedAccountIdentifier = UnspecifiedAccountIdentifier::from(buffer);
    Ok(Address::from(chain_addr::Address(
        discrimination,
        Kind::Account(
            identifier
                .to_single_account()
                .expect("Only single accounts are supported")
                .into(),
        ),
    )))
}

fn rewards_to_mainnet_addresses(
    rewards: HashMap<Identifier, Rewards>,
    voters: Vec<SnapshotInfo>,
) -> BTreeMap<RewardAddress, Rewards> {
    let mut res = BTreeMap::new();
    let snapshot_info_by_key = voters
        .into_iter()
        .map(|v| (v.hir.voting_key.clone(), v))
        .collect::<HashMap<_, _>>();
    for (addr, reward) in rewards {
        let contributions = snapshot_info_by_key
            .get(&addr)
            .map(|v| v.contributions.clone())
            .unwrap_or_default();
        let total_value = contributions
            .iter()
            .map(|c| Rewards::from(c.value))
            .sum::<Rewards>();

        for c in contributions {
            *res.entry(c.reward_address.clone()).or_default() +=
                reward * Rewards::from(c.value) / total_value;
        }
    }

    res
}

pub fn calc_voter_rewards(
    vote_count: VoteCount,
    voters: Vec<SnapshotInfo>,
    vote_threshold: Threshold,
    total_rewards: Rewards,
) -> Result<BTreeMap<RewardAddress, Rewards>, Error> {
    let unique_voters = voters
        .iter()
        .map(|s| s.hir.voting_key.clone())
        .collect::<HashSet<_>>();
    if unique_voters.len() != voters.len() {
        return Err(Error::MultipleEntries);
    }
    let active_addresses = filter_active_addresses(vote_count, voters, vote_threshold);

    let mut total_active_stake = 0u64;
    let mut stake_per_voter = HashMap::new();
    // iterative as Iterator::sum() panic on overflows
    for voter in &active_addresses {
        total_active_stake = total_active_stake
            .checked_add(voter.hir.voting_power.into())
            .ok_or(Error::Overflow)?;
        stake_per_voter.insert(voter.hir.voting_key.clone(), voter.hir.voting_power.into());
    }
    let rewards = calculate_reward(total_active_stake, stake_per_voter, total_rewards);
    Ok(rewards_to_mainnet_addresses(rewards, active_addresses))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::assert_are_close;
    use jormungandr_lib::crypto::{account::Identifier, hash::Hash};
    use snapshot_lib::registration::{Delegations, StakeAddress, VotingRegistration};
    use snapshot_lib::Snapshot;
    use snapshot_lib::{Fraction, RawSnapshot};
    use test_strategy::proptest;

    const DEFAULT_TEST_THRESHOLD: usize = 1;
    const DEFAULT_SNAPSHOT_THRESHOLD: u64 = 1;

    #[proptest]
    fn test_all_active_voters(raw_snapshot: RawSnapshot) {
        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot,
            DEFAULT_SNAPSHOT_THRESHOLD.into(),
            Fraction::from(1),
            &|_vk: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        let votes_count = snapshot
            .voting_keys()
            .map(|key| (key.clone(), HashSet::from([Hash::from([0u8; 32])])))
            .collect::<VoteCount>();

        let number_of_voters = votes_count.len();

        let voters = snapshot.to_full_snapshot_info();
        let rewards = calc_voter_rewards(
            votes_count,
            voters,
            Threshold::new(DEFAULT_TEST_THRESHOLD, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();
        if number_of_voters > 0 {
            assert_are_close(rewards.values().sum::<Rewards>(), Rewards::ONE)
        } else {
            assert_eq!(rewards.len(), 0);
        }
    }

    #[proptest]
    fn test_all_inactive_voters(raw_snapshot: RawSnapshot) {
        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot,
            DEFAULT_SNAPSHOT_THRESHOLD.into(),
            Fraction::from(1),
            &|_vk: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        let votes_count = VoteCount::new();

        let voters = snapshot.to_full_snapshot_info();
        let rewards = calc_voter_rewards(
            votes_count,
            voters,
            Threshold::new(DEFAULT_TEST_THRESHOLD, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();
        assert_eq!(rewards.len(), 0);
    }

    #[proptest]
    fn test_active_and_inactive_voters(raw_snapshot: RawSnapshot) {
        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot,
            DEFAULT_SNAPSHOT_THRESHOLD.into(),
            Fraction::from(1),
            &|_vk: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        let voting_keys = snapshot.voting_keys().collect::<Vec<_>>();

        let votes_count = voting_keys
            .iter()
            .enumerate()
            .map(|(i, &key)| {
                (
                    key.to_owned(),
                    if i % 2 == 0 {
                        // generating a random set of half active & half inactive votes
                        HashSet::from([Hash::from([0u8; 32])])
                    } else {
                        HashSet::new()
                    },
                )
            })
            .collect::<VoteCount>();

        let number_of_active_voters = votes_count
            .iter()
            .filter(|(_, votes)| !votes.is_empty())
            .count();

        let voters = snapshot.to_full_snapshot_info();

        let active_voters = voters
            .clone()
            .into_iter()
            .enumerate()
            .filter(|(i, _utxo)| i % 2 == 0)
            .map(|(_, utxo)| utxo)
            .collect::<Vec<_>>();

        let mut all_rewards = calc_voter_rewards(
            votes_count.clone(),
            voters,
            Threshold::new(1, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();

        let rewards_no_inactive = calc_voter_rewards(
            votes_count,
            active_voters,
            Threshold::new(DEFAULT_TEST_THRESHOLD, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();
        // Rewards should ignore inactive voters
        assert_eq!(all_rewards, rewards_no_inactive);
        if number_of_active_voters > 0 {
            assert_are_close(all_rewards.values().sum::<Rewards>(), Rewards::ONE);
        } else {
            assert_eq!(all_rewards.len(), 0);
        }

        let (active_voters_keys, inactive_voters_keys): (Vec<_>, Vec<_>) = voting_keys
            .into_iter()
            .enumerate()
            .partition(|(i, _vk)| i % 2 == 0);

        let active_reward_addresses = active_voters_keys
            .into_iter()
            .flat_map(|(_, vk)| {
                snapshot
                    .contributions_for_voting_key(vk.clone())
                    .into_iter()
                    .map(|c| c.reward_address)
            })
            .collect::<HashSet<_>>();

        assert!(active_reward_addresses
            .iter()
            .all(|addr| all_rewards.remove(addr).unwrap() > Rewards::ZERO));

        for (_, voting_key) in inactive_voters_keys {
            for contrib in snapshot.contributions_for_voting_key(voting_key.clone()) {
                assert!(all_rewards.get(&contrib.reward_address).is_none());
            }
        }
    }

    #[test]
    fn test_mapping() {
        let mut raw_snapshot = Vec::new();
        let voting_public_key = Identifier::from_hex(&hex::encode([0; 32])).unwrap();

        let mut total_stake = 0u64;

        for i in 1..10u64 {
            let stake_public_key = StakeAddress(i.to_string());
            let reward_address = RewardAddress(i.to_string());

            let delegations = Delegations::New(vec![(voting_public_key.clone(), 1)]);
            raw_snapshot.push(VotingRegistration {
                stake_public_key,
                voting_power: i.into(),
                reward_address,
                delegations,
                voting_purpose: Some(0),
                nonce: 0,
            });
            total_stake += i;
        }

        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot.into(),
            0.into(),
            Fraction::from(1u64),
            &|_voting_key: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        let voters = snapshot.to_full_snapshot_info();

        let rewards = calc_voter_rewards(
            VoteCount::new(),
            voters,
            Threshold::new(0, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();

        assert_eq!(rewards.values().sum::<Rewards>(), Rewards::ONE);

        for (mainnet_addresses, reward) in rewards {
            assert_eq!(
                reward,
                mainnet_addresses.parse::<Rewards>().unwrap() / Rewards::from(total_stake)
            );
        }
    }

    #[test]
    fn test_rewards_cap() {
        let mut raw_snapshot = Vec::new();

        for i in 1..10u64 {
            let voting_public_key = Identifier::from_hex(&hex::encode([i as u8; 32])).unwrap();
            let stake_public_key = StakeAddress(i.to_string());
            let reward_address = RewardAddress(i.to_string());
            let delegations = Delegations::New(vec![(voting_public_key.clone(), 1)]);
            raw_snapshot.push(VotingRegistration {
                stake_public_key,
                voting_power: i.into(),
                reward_address,
                delegations,
                voting_purpose: Some(0),
                nonce: 0,
            });
        }

        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot.into(),
            0.into(),
            Fraction::new(1u64, 9u64),
            &|_vk: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        let voters = snapshot.to_full_snapshot_info();

        let rewards = calc_voter_rewards(
            VoteCount::new(),
            voters,
            Threshold::new(0, HashMap::new(), Vec::new()).unwrap(),
            Rewards::ONE,
        )
        .unwrap();
        // The only assertion that we can make at this point is that the sum
        // of the voter rewards is equal to the total rewards.
        assert_are_close(rewards.values().sum::<Rewards>(), Rewards::ONE);
        // These assertions are invalid, as the rewards are dependent on the weighted capped voting power.
        // for (_, reward) in rewards {
        //     assert_eq!(reward, Rewards::ONE / Rewards::from(9u8));
        // }
    }

    #[proptest]
    fn test_per_category_threshold(raw_snapshot: RawSnapshot) {
        let snapshot = Snapshot::from_raw_snapshot(
            raw_snapshot,
            DEFAULT_SNAPSHOT_THRESHOLD.into(),
            Fraction::from(1),
            &|_vk: &Identifier| String::new(),
            Discrimination::Production,
            false,
        )
        .unwrap();

        use vit_servicing_station_tests::common::data::ArbitrarySnapshotGenerator;

        let voters = snapshot.to_full_snapshot_info();

        let snapshot = ArbitrarySnapshotGenerator::default().snapshot();
        let proposals = snapshot.proposals();

        let proposals_by_challenge =
            proposals
                .iter()
                .fold(<HashMap<_, Vec<_>>>::new(), |mut acc, prop| {
                    acc.entry(prop.proposal.challenge_id)
                        .or_default()
                        .push(Hash::from(
                            crate::rewards::chain_proposal_id_bytes(
                                &prop.proposal.chain_proposal_id,
                            )
                            .unwrap(),
                        ));
                    acc
                });
        let per_challenge_threshold = proposals_by_challenge
            .iter()
            .map(|(challenge, p)| (*challenge, p.len()))
            .collect::<HashMap<_, _>>();

        let mut votes_count = voters
            .iter()
            .map(|v| {
                (
                    v.hir.voting_key.clone(),
                    proposals_by_challenge
                        .values()
                        .flat_map(|p| p.iter())
                        .cloned()
                        .collect::<HashSet<_>>(),
                )
            })
            .collect::<Vec<_>>();
        let (_, inactive) = votes_count.split_at_mut(voters.len() / 2);
        for v in inactive {
            v.1.remove(&v.1.iter().next().unwrap().clone());
        }

        let only_active = votes_count
            .clone()
            .into_iter()
            .take(voters.len() / 2)
            .collect::<HashMap<_, _>>();
        let votes_count = votes_count.into_iter().collect::<HashMap<_, _>>();

        let rewards = calc_voter_rewards(
            votes_count,
            voters.clone(),
            Threshold::new(
                DEFAULT_TEST_THRESHOLD,
                per_challenge_threshold.clone(),
                proposals.clone().into_iter().map(Into::into).collect(),
            )
            .unwrap(),
            Rewards::ONE,
        )
        .unwrap();

        let rewards_only_active = calc_voter_rewards(
            only_active,
            voters,
            Threshold::new(
                DEFAULT_TEST_THRESHOLD,
                per_challenge_threshold,
                proposals.into_iter().map(Into::into).collect(),
            )
            .unwrap(),
            Rewards::ONE,
        )
        .unwrap();

        assert_eq!(rewards_only_active, rewards);
    }
}