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
//! Rewards module types.
use std::collections::BTreeMap;

use thiserror::Error;

use crate::{
    core::consensus::beacon,
    types::{address::Address, token},
};

/// One of the time periods in the reward schedule.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct RewardStep {
    pub until: beacon::EpochTime,
    pub amount: token::BaseUnits,
}

/// A reward schedule.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct RewardSchedule {
    pub steps: Vec<RewardStep>,
}

/// Errors emitted during reward schedule validation.
#[derive(Error, Debug)]
pub enum RewardScheduleError {
    #[error("steps not sorted correctly")]
    StepsNotSorted,
}

impl RewardSchedule {
    /// Perform basic reward schedule validation.
    pub fn validate_basic(&self) -> Result<(), RewardScheduleError> {
        let mut last_epoch = Default::default();
        for step in &self.steps {
            if step.until <= last_epoch {
                return Err(RewardScheduleError::StepsNotSorted);
            }
            last_epoch = step.until;
        }
        Ok(())
    }

    /// Compute the per-entity reward amount for the given epoch based on the schedule.
    pub fn for_epoch(&self, epoch: beacon::EpochTime) -> token::BaseUnits {
        for step in &self.steps {
            if epoch < step.until {
                return step.amount.clone();
            }
        }

        // End of the schedule, default to no rewards.
        Default::default()
    }
}

/// Action that should be taken for a given address when disbursing rewards.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RewardAction {
    Reward(u64),
    NoReward,
}

impl RewardAction {
    /// Increment the reward counter associated with the reward.
    ///
    /// In case the action is `NoReward` nothing is changed.
    pub fn increment(&mut self) {
        match self {
            RewardAction::Reward(ref mut v) => *v += 1,
            RewardAction::NoReward => {
                // Do not change state as the entity has been penalized for the epoch.
            }
        }
    }

    /// Forbids any rewards from accumulating.
    pub fn forbid(&mut self) {
        *self = RewardAction::NoReward;
    }

    /// Value of the reward counter.
    pub fn value(&self) -> u64 {
        match self {
            RewardAction::Reward(v) => *v,
            RewardAction::NoReward => 0,
        }
    }
}

impl Default for RewardAction {
    fn default() -> Self {
        RewardAction::Reward(0)
    }
}

impl cbor::Encode for RewardAction {
    fn into_cbor_value(self) -> cbor::Value {
        match self {
            Self::Reward(r) => cbor::Value::Unsigned(r),
            Self::NoReward => cbor::Value::Simple(cbor::SimpleValue::NullValue),
        }
    }
}

impl cbor::Decode for RewardAction {
    fn try_default() -> Result<Self, cbor::DecodeError> {
        Ok(Self::NoReward)
    }

    fn try_from_cbor_value(value: cbor::Value) -> Result<Self, cbor::DecodeError> {
        match value {
            cbor::Value::Unsigned(v) => Ok(Self::Reward(v)),
            cbor::Value::Simple(cbor::SimpleValue::NullValue) => Ok(Self::NoReward),
            _ => Err(cbor::DecodeError::UnexpectedType),
        }
    }
}

/// Rewards for the epoch.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct EpochRewards {
    pub pending: BTreeMap<Address, RewardAction>,
}

impl EpochRewards {
    /// Returns an iterator over addresses that should be rewarded.
    pub fn for_disbursement(
        &self,
        threshold_numerator: u64,
        threshold_denominator: u64,
    ) -> impl Iterator<Item = Address> + '_ {
        let max_v = self
            .pending
            .iter()
            .fold(0, |acc, (_, action)| std::cmp::max(acc, action.value()));

        let (_, overflow) = threshold_numerator.overflowing_mul(max_v);
        let threshold = if overflow {
            max_v
                .checked_div(threshold_denominator)
                .unwrap_or(0)
                .saturating_mul(threshold_numerator)
        } else {
            threshold_numerator
                .saturating_mul(max_v)
                .checked_div(threshold_denominator)
                .unwrap_or(0)
        };

        self.pending
            .iter()
            .filter_map(move |(address, action)| match action {
                RewardAction::Reward(v) => {
                    if *v < threshold {
                        None
                    } else {
                        Some(*address)
                    }
                }
                RewardAction::NoReward => None,
            })
    }
}

#[cfg(test)]
mod test {
    use crate::testing::keys;

    use super::*;

    #[test]
    fn test_reward_action() {
        let mut act = RewardAction::default();
        act.increment();
        act.increment();
        act.increment();

        assert!(matches!(act, RewardAction::Reward(3)));

        act.forbid();

        act.increment();
        act.increment();

        assert!(matches!(act, RewardAction::NoReward));
    }

    #[test]
    fn test_reward_action_serialization() {
        let actions = vec![
            RewardAction::Reward(0),
            RewardAction::Reward(42),
            RewardAction::NoReward,
        ];
        for act in actions {
            let encoded = &cbor::to_vec(act.clone());
            let round_trip: RewardAction =
                cbor::from_slice(encoded).expect("round-trip should succeed");
            assert_eq!(round_trip, act, "reward actions should round-trip");
        }
    }

    #[test]
    fn test_reward_schedule_validation_fail_1() {
        let schedule = RewardSchedule {
            steps: vec![
                RewardStep {
                    until: 10,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 10,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 15,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
            ],
        };
        schedule
            .validate_basic()
            .expect_err("validation with duplicate steps should fail");
    }

    #[test]
    fn test_reward_schedule_validation_fail_2() {
        let schedule = RewardSchedule {
            steps: vec![
                RewardStep {
                    until: 10,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 5,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 15,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
            ],
        };
        schedule
            .validate_basic()
            .expect_err("validation with unsorted steps should fail");
    }

    #[test]
    fn test_reward_schedule_validation_ok() {
        let schedule = RewardSchedule {
            steps: vec![
                RewardStep {
                    until: 5,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 10,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 15,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
            ],
        };
        schedule
            .validate_basic()
            .expect("validation of correct schedule should not fail");
    }

    #[test]
    fn test_reward_schedule() {
        let schedule = RewardSchedule {
            steps: vec![
                RewardStep {
                    until: 5,
                    amount: token::BaseUnits::new(3000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 10,
                    amount: token::BaseUnits::new(2000, token::Denomination::NATIVE),
                },
                RewardStep {
                    until: 15,
                    amount: token::BaseUnits::new(1000, token::Denomination::NATIVE),
                },
            ],
        };

        assert_eq!(schedule.for_epoch(1).amount(), 3000);
        assert_eq!(schedule.for_epoch(3).amount(), 3000);
        assert_eq!(schedule.for_epoch(5).amount(), 2000);
        assert_eq!(schedule.for_epoch(6).amount(), 2000);
        assert_eq!(schedule.for_epoch(9).amount(), 2000);
        assert_eq!(schedule.for_epoch(10).amount(), 1000);
        assert_eq!(schedule.for_epoch(14).amount(), 1000);
        assert_eq!(schedule.for_epoch(15).amount(), 0);
        assert_eq!(schedule.for_epoch(20).amount(), 0);
        assert_eq!(schedule.for_epoch(100).amount(), 0);
    }

    #[test]
    fn test_epoch_rewards() {
        let epoch_rewards = EpochRewards {
            pending: {
                let mut pending = BTreeMap::new();
                pending.insert(keys::alice::address(), RewardAction::Reward(10));
                pending.insert(keys::bob::address(), RewardAction::NoReward);
                pending.insert(keys::charlie::address(), RewardAction::Reward(5));
                pending
            },
        };

        // Alice and Charlie have >= 0.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(0, 0).collect();
        assert_eq!(
            rewards,
            vec![keys::charlie::address(), keys::alice::address()]
        );
        // Alice and Charlie have >= 0.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(0, 0).collect();
        assert_eq!(
            rewards,
            vec![keys::charlie::address(), keys::alice::address()]
        );
        // Only Alice has >= 7.5.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(3, 4).collect();
        assert_eq!(rewards, vec![keys::alice::address()]);
    }

    #[test]
    fn test_epoch_rewards_overflow() {
        let epoch_rewards = EpochRewards {
            pending: {
                let mut pending = BTreeMap::new();
                pending.insert(keys::alice::address(), RewardAction::Reward(u64::MAX));
                pending.insert(keys::charlie::address(), RewardAction::Reward(u64::MAX / 2));
                pending
            },
        };

        // Alice and Charlie have >= 0.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(0, 0).collect();
        assert_eq!(
            rewards,
            vec![keys::charlie::address(), keys::alice::address()]
        );
        // Alice and Charlie have >= 1/2.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(1, 2).collect();
        assert_eq!(
            rewards,
            vec![keys::charlie::address(), keys::alice::address()]
        );
        // Only Alice has >= 3/4, but due to overflow both will be counted.
        let rewards: Vec<_> = epoch_rewards.for_disbursement(3, 4).collect();
        assert_eq!(rewards, vec![keys::alice::address()]);
    }
}