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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Generic account like accounting
//!
//! This is effectively an immutable clonable-HAMT of bank style account,
//! which contains a non negative value representing your balance with the
//! identifier of this account as key.

pub mod account_state;
pub mod last_rewards;
pub mod spending;

use crate::tokens::identifier::TokenIdentifier;
use crate::{date::Epoch, value::*};
use imhamt::{Hamt, InsertError, UpdateError};
use std::collections::hash_map::DefaultHasher;
use std::fmt::{self, Debug};
use std::hash::Hash;
use thiserror::Error;

pub use account_state::*;
pub use last_rewards::LastRewards;
pub use spending::{SpendingCounter, SpendingCounterIncreasing};

#[cfg(any(test, feature = "property-test-api"))]
pub mod test;

#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum LedgerError {
    #[error("Account does not exist")]
    NonExistent,
    #[error("Account already exists")]
    AlreadyExists,
    #[error("Removed account is not empty")]
    NonZero,
    #[error("Value calculation failed")]
    ValueError(#[from] ValueError),
    #[error(transparent)]
    SpendingCounterError(#[from] spending::Error),
}

impl From<UpdateError<LedgerError>> for LedgerError {
    fn from(e: UpdateError<LedgerError>) -> Self {
        match e {
            UpdateError::KeyNotFound => LedgerError::NonExistent,
            UpdateError::ValueCallbackError(v) => v,
        }
    }
}

impl From<InsertError> for LedgerError {
    fn from(e: InsertError) -> Self {
        match e {
            InsertError::EntryExists => LedgerError::AlreadyExists,
        }
    }
}

/// The public ledger of all accounts associated with their current state
#[derive(Clone, PartialEq, Eq)]
pub struct Ledger<ID: Hash + Eq, Extra>(Hamt<DefaultHasher, ID, AccountState<Extra>>);

impl<ID: Clone + Eq + Hash, Extra: Clone> Default for Ledger<ID, Extra> {
    fn default() -> Self {
        Self::new()
    }
}

impl<ID: Clone + Eq + Hash, Extra: Clone> Ledger<ID, Extra> {
    /// Create a new empty account ledger
    pub fn new() -> Self {
        Ledger(Hamt::new())
    }

    /// Add a new account into this ledger.
    ///
    /// If the identifier is already present, error out.
    pub fn add_account(
        &self,
        identifier: ID,
        initial_value: Value,
        extra: Extra,
    ) -> Result<Self, LedgerError> {
        self.0
            .insert(identifier, AccountState::new(initial_value, extra))
            .map(Ledger)
            .map_err(|e| e.into())
    }

    /// Set the delegation of an account in this ledger
    pub fn set_delegation(
        &self,
        identifier: &ID,
        delegation: &DelegationType,
    ) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| {
                Ok(Some(st.set_delegation(delegation.clone())))
            })
            .map(Ledger)
            .map_err(|e| e.into())
    }

    /// check if an account already exist
    #[inline]
    pub fn exists(&self, identifier: &ID) -> bool {
        self.0.contains_key(identifier)
    }

    /// Get account state
    ///
    /// If the identifier does not match any account, error out
    pub fn get_state(&self, account: &ID) -> Result<&AccountState<Extra>, LedgerError> {
        self.0.lookup(account).ok_or(LedgerError::NonExistent)
    }

    /// Remove an account from this ledger
    ///
    /// If the account still have value > 0, then error
    pub fn remove_account(&self, identifier: &ID) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| {
                if st.value == Value::zero() {
                    Ok(None)
                } else {
                    Err(LedgerError::NonZero)
                }
            })
            .map(Ledger)
            .map_err(|e| e.into())
    }

    /// Add value to an existing account.
    ///
    /// If the account doesn't exist, error out.
    pub fn add_value(&self, identifier: &ID, value: Value) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| st.add(value).map(Some))
            .map(Ledger)
            .map_err(|e| e.into())
    }

    /// Add value to an existing account.
    ///
    /// If the account doesn't exist, it creates it with the value
    pub fn add_value_or_account(
        &self,
        identifier: &ID,
        value: Value,
        extra: Extra,
    ) -> Result<Self, ValueError> {
        self.0
            .insert_or_update(identifier.clone(), AccountState::new(value, extra), |st| {
                st.add_value(value).map(Some)
            })
            .map(Ledger)
    }

    /// Add rewards to an existing account.
    ///
    /// If the account doesn't exist, it creates it with the value
    pub fn add_rewards_to_account(
        &self,
        identifier: &ID,
        epoch: Epoch,
        value: Value,
        extra: Extra,
    ) -> Result<Self, ValueError> {
        self.0
            .insert_or_update(
                identifier.clone(),
                AccountState::new_reward(epoch, value, extra),
                |st| st.add_rewards(epoch, value).map(Some),
            )
            .map(Ledger)
    }

    /// Spend value from an existing account.
    ///
    /// If the account doesn't exist, or if the value is too much to spend,
    /// or if the spending counter doesn't match, it throws a `LedgerError`.
    pub fn spend(
        &self,
        identifier: &ID,
        counter: SpendingCounter,
        value: Value,
    ) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| st.spend(counter, value))
            .map(Ledger)
            .map_err(|e| e.into())
    }

    /// Spend value from an existing account without spending counter check.
    ///
    /// If the account doesn't exist, or if the value is too much to spend,
    /// it throws a `LedgerError`.
    pub(crate) fn spend_with_no_counter_check(
        &self,
        identifier: &ID,
        counter: SpendingCounter,
        value: Value,
    ) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| st.spend_unchecked(counter, value))
            .map(Ledger)
            .map_err(|e| e.into())
    }

    pub fn get_total_value(&self) -> Result<Value, ValueError> {
        let values = self
            .0
            .iter()
            .map(|(_, account_state)| account_state.value());
        Value::sum(values)
    }

    pub fn token_add(
        &self,
        identifier: &ID,
        token: TokenIdentifier,
        value: Value,
    ) -> Result<Self, LedgerError> {
        self.0
            .update(identifier, |st| st.token_add(token, value).map(Some))
            .map(Ledger)
            .map_err(|e| e.into())
    }

    pub fn iter(&self) -> Iter<'_, ID, Extra> {
        Iter(self.0.iter())
    }
}

impl<ID: Clone + Eq + Hash + Debug, Extra: Clone + Debug> Debug for Ledger<ID, Extra> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:?}",
            self.0
                .iter()
                .map(|(id, account)| (id.clone(), account.clone()))
                .collect::<Vec<(ID, AccountState<Extra>)>>()
        )
    }
}

impl<ID: Clone + Eq + Hash, Extra: Clone> std::iter::FromIterator<(ID, AccountState<Extra>)>
    for Ledger<ID, Extra>
{
    fn from_iter<I: IntoIterator<Item = (ID, AccountState<Extra>)>>(iter: I) -> Self {
        Ledger(Hamt::from_iter(iter))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::{
        account::{Identifier, Ledger},
        certificate::{PoolId, PoolRegistration},
        testing::{arbitrary::utils as arbitrary_utils, arbitrary::AverageValue, TestGen},
        value::Value,
    };

    use quickcheck::{Arbitrary, Gen, TestResult};
    use quickcheck_macros::quickcheck;
    use std::collections::HashSet;
    use std::iter;

    impl Arbitrary for Ledger {
        fn arbitrary<G: Gen>(gen: &mut G) -> Self {
            let account_size = std::cmp::max(usize::arbitrary(gen), 1);
            let stake_pool_size =
                std::cmp::min(account_size, usize::arbitrary(gen) % account_size + 1);
            let arbitrary_accounts_ids = iter::from_fn(|| Some(Identifier::arbitrary(gen)))
                .take(account_size)
                .collect::<HashSet<Identifier>>();

            let arbitrary_stake_pools = iter::from_fn(|| Some(PoolRegistration::arbitrary(gen)))
                .take(stake_pool_size)
                .collect::<Vec<_>>();

            let voting_tokens_size = usize::arbitrary(gen);
            let arbitrary_voting_tokens = iter::from_fn(|| Some(TokenIdentifier::arbitrary(gen)))
                .take(voting_tokens_size)
                .collect::<HashSet<_>>();

            let mut ledger = Ledger::new();

            // Add all arbitrary accounts
            for account_id in arbitrary_accounts_ids.iter() {
                ledger = ledger
                    .add_account(account_id.clone(), AverageValue::arbitrary(gen).into(), ())
                    .unwrap();

                for token in &arbitrary_voting_tokens {
                    // TODO: maybe less probability is better (for performance)
                    if bool::arbitrary(gen) {
                        ledger = ledger
                            .token_add(account_id, token.clone(), Value::arbitrary(gen))
                            .unwrap();
                    }
                }
            }

            // Choose random subset of arbitraty accounts and delegate stake to random stake pools
            for account_id in
                arbitrary_utils::choose_random_set_subset(&arbitrary_accounts_ids, gen)
            {
                let random_stake_pool =
                    arbitrary_utils::choose_random_item(&arbitrary_stake_pools, gen);
                ledger = ledger
                    .set_delegation(
                        &account_id,
                        &DelegationType::Full(random_stake_pool.to_id()),
                    )
                    .unwrap();
            }
            ledger
        }
    }

    #[quickcheck]
    fn account_ledger_test(
        mut ledger: Ledger,
        account_id: Identifier,
        value: Value,
        stake_pool_id: PoolId,
    ) -> TestResult {
        if value == Value::zero() || ledger.exists(&account_id) {
            return TestResult::discard();
        }

        let initial_total_value = ledger.get_total_value().unwrap();

        // add new account
        ledger = match ledger.add_account(account_id.clone(), value, ()) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Add account with id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        // add account again should throw an error
        if ledger.add_account(account_id.clone(), value, ()).is_ok() {
            return TestResult::error(format!(
                "Account with id {} again should should",
                account_id
            ));
        }
        assert!(
            ledger.exists(&account_id),
            "Account with id {} should exist",
            account_id
        );
        assert!(
            ledger.iter().any(|(x, _)| *x == account_id),
            "Account with id {} should be listed amongst other",
            account_id
        );

        // verify total value was increased
        let test_result = test_total_value(
            (initial_total_value + value).unwrap(),
            ledger.get_total_value().unwrap(),
        );
        if test_result.is_error() {
            return test_result;
        }

        // set delegation to stake pool
        ledger = match ledger
            .set_delegation(&account_id, &DelegationType::Full(stake_pool_id.clone()))
        {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Set delegation operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        // verify total value is still the same
        assert!(!test_total_value(
            (initial_total_value + value).unwrap(),
            ledger.get_total_value().unwrap(),
        )
        .is_failure());

        // add value to account
        ledger = match ledger.add_value(&account_id, value) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Add value to account operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        // verify total value was increased
        let test_result = test_total_value(
            (initial_total_value + (value + value).unwrap()).unwrap(),
            ledger.get_total_value().unwrap(),
        );
        if test_result.is_error() {
            return test_result;
        }

        //add reward to account
        ledger = match ledger.add_rewards_to_account(&account_id, 0, value, ()) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Add rewards to account operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        let value_after_reward = Value(value.0 * 3);
        // verify total value was increased
        let test_result = test_total_value(
            (initial_total_value + value_after_reward).unwrap(),
            ledger.get_total_value().unwrap(),
        );
        if test_result.is_error() {
            return test_result;
        }

        let mut spending_counter = SpendingCounter::zero();
        //verify account state
        match ledger.get_state(&account_id) {
            Ok(account_state) => {
                let expected_account_state = AccountState {
                    spending: SpendingCounterIncreasing::default(),
                    last_rewards: LastRewards {
                        epoch: 0,
                        reward: value,
                    },
                    delegation: DelegationType::Full(stake_pool_id),
                    value: value_after_reward,
                    tokens: Hamt::new(),
                    extra: (),
                };

                if *account_state != expected_account_state {
                    return TestResult::error(format!(
                        "Account state is incorrect expected {:?} but got {:?}",
                        expected_account_state, account_state
                    ));
                }
            }
            Err(err) => {
                return TestResult::error(format!(
                    "Get state for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        }

        // remove value from account
        ledger = match ledger.spend(&account_id, spending_counter, value) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Removew value operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };
        spending_counter = spending_counter.increment();
        let value_before_reward = Value(value.0 * 2);
        // verify total value was decreased
        let test_result = test_total_value(
            (initial_total_value + value_before_reward).unwrap(),
            ledger.get_total_value().unwrap(),
        );
        if test_result.is_error() {
            return test_result;
        }

        // verify remove account fails beause account still got some founds
        if ledger.remove_account(&account_id).is_ok() {
            return TestResult::error(format!(
                "Remove account should be unsuccesfull... account for id {} still got funds",
                account_id
            ));
        }

        // removes all funds from account
        ledger = match ledger.spend(&account_id, spending_counter, value_before_reward) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Remove all funds operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        // commented line to prevent a warning, but it should be updated to reflect the correct state of spending credential
        // spending_counter = spending_counter.increment();

        // removes account
        ledger = match ledger.remove_account(&account_id) {
            Ok(ledger) => ledger,
            Err(err) => {
                return TestResult::error(format!(
                    "Remove account operation for id {} should be successful: {:?}",
                    account_id, err
                ))
            }
        };

        assert!(!ledger.exists(&account_id), "account should not exist");
        assert!(
            !ledger.iter().any(|(x, _)| *x == account_id),
            "Account with id {:?} should not be listed amongst accounts",
            account_id
        );
        assert_eq!(
            initial_total_value,
            ledger.get_total_value().unwrap(),
            "total funds is not equal to initial total_value"
        );

        //Account state is should be none
        TestResult::from_bool(ledger.get_state(&account_id).is_err())
    }

    fn test_total_value(expected: Value, actual: Value) -> TestResult {
        if actual == expected {
            TestResult::passed()
        } else {
            TestResult::error(format!(
                "Wrong total value expected {} but got {}",
                expected, actual
            ))
        }
    }

    #[quickcheck]
    pub fn ledger_total_value_is_correct_after_spend(
        id: Identifier,
        account_state: AccountState<()>,
        value_to_remove: Value,
    ) -> TestResult {
        let mut ledger = Ledger::new();
        ledger = ledger
            .add_account(id.clone(), account_state.value(), ())
            .unwrap();
        let result = ledger.spend(&id, SpendingCounter::zero(), value_to_remove);
        let expected_result = account_state.value() - value_to_remove;
        match (result, expected_result) {
            (Err(_), Err(_)) => verify_total_value(ledger, account_state.value()),
            (Ok(_), Err(_)) => TestResult::failed(),
            (Err(_), Ok(_)) => TestResult::failed(),
            (Ok(ledger), Ok(value)) => verify_total_value(ledger, value),
        }
    }

    fn verify_total_value(ledger: Ledger, value: Value) -> TestResult {
        if ledger.get_total_value().unwrap() == value {
            TestResult::passed()
        } else {
            TestResult::error(format!(
                "Wrong total value got {:?}, while expecting {:?}",
                ledger.get_total_value(),
                value
            ))
        }
    }

    #[quickcheck]
    pub fn ledger_removes_account_only_if_zeroed(
        id: Identifier,
        account_state: AccountState<()>,
    ) -> TestResult {
        let mut ledger = Ledger::new();
        ledger = ledger
            .add_account(id.clone(), account_state.value(), ())
            .unwrap();
        let result = ledger.remove_account(&id);
        let expected_zero = account_state.value() == Value::zero();
        match (result, expected_zero) {
            (Err(_), false) => verify_account_exists(&ledger, &id),
            (Ok(_), false) => TestResult::failed(),
            (Err(_), true) => TestResult::failed(),
            (Ok(ledger), true) => verify_account_does_not_exist(&ledger, &id),
        }
    }

    fn verify_account_exists(ledger: &Ledger, id: &Identifier) -> TestResult {
        if ledger.exists(id) {
            TestResult::passed()
        } else {
            TestResult::error(format!(
                "Account ({:?}) does not exist, while it should",
                &id
            ))
        }
    }

    fn verify_account_does_not_exist(ledger: &Ledger, id: &Identifier) -> TestResult {
        if ledger.exists(id) {
            TestResult::error(format!("Account ({:?}) exists, while it should not", &id))
        } else {
            TestResult::passed()
        }
    }

    #[test]
    pub fn add_value_or_account_test() {
        let ledger = Ledger::new();
        assert!(ledger
            .add_value_or_account(&TestGen::identifier(), Value(10), ())
            .is_ok());
    }
}