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
use imhamt::{Hamt, HamtIter, InsertError, RemoveError};
use std::collections::hash_map::DefaultHasher;
use thiserror::Error;

use super::declaration::{Declaration, DeclarationError, Identifier};
use crate::accounting::account::{self, DelegationType, Iter, SpendingCounter};
use crate::value::{Value, ValueError};

#[derive(Clone, PartialEq, Eq, Default)]
pub struct Ledger {
    // TODO : investigate about merging the declarations and the accounts in
    // one with an extension on the account::Ledger
    accounts: account::Ledger<Identifier, ()>,
    declarations: Hamt<DefaultHasher, Identifier, Declaration>,
}

#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum LedgerError {
    #[error("Too many participant in the multisig account")]
    ParticipantOutOfBound,
    #[error("Multisig account already exists")]
    AlreadyExist,
    #[error("Multisig account does not exist")]
    DoesntExist,
    #[error("Multisig declaration error or invalid")]
    DeclarationError(#[from] DeclarationError),
    #[error("Multisig account error or invalid")]
    AccountError(#[from] account::LedgerError),
    #[error("Multisig identifier mismatched")]
    IdentifierMismatch,
    #[error("Multisig account's threshold not met")]
    ThresholdNotMet,
}

impl From<InsertError> for LedgerError {
    fn from(_: InsertError) -> Self {
        LedgerError::AlreadyExist
    }
}

impl From<RemoveError> for LedgerError {
    fn from(_: RemoveError) -> Self {
        LedgerError::DoesntExist
    }
}

impl Ledger {
    /// Create a new empty account ledger
    pub fn new() -> Self {
        Ledger {
            accounts: account::Ledger::new(),
            declarations: Hamt::new(),
        }
    }

    pub fn restore(
        accounts: Vec<(Identifier, account::AccountState<()>)>,
        declarations: Vec<(Identifier, Declaration)>,
    ) -> Self {
        Ledger {
            accounts: accounts.into_iter().collect(),
            declarations: declarations.into_iter().collect(),
        }
    }

    /// Add a new multisig declaration into the ledger.
    ///
    /// If the identifier is already present, error out.
    pub fn add_account(&self, declaration: &Declaration) -> Result<Self, LedgerError> {
        // check if declaration is valid here
        declaration.is_valid()?;

        let identifier = declaration.to_identifier();
        let new_decls = self
            .declarations
            .insert(identifier.clone(), declaration.clone())?;
        let new_accts = self.accounts.add_account(identifier, Value::zero(), ())?;
        Ok(Self {
            accounts: new_accts,
            declarations: new_decls,
        })
    }

    /// Remove a declaration from this ledger
    pub fn remove_account(&self, ident: &Identifier) -> Result<Self, LedgerError> {
        let new_decls = self.declarations.remove(ident)?;
        let new_accts = self.accounts.remove_account(ident)?;
        Ok(Self {
            accounts: new_accts,
            declarations: new_decls,
        })
    }

    pub fn add_value(&self, identifier: &Identifier, value: Value) -> Result<Self, LedgerError> {
        let new_accounts = self.accounts.add_value(identifier, value)?;
        Ok(Self {
            accounts: new_accounts,
            declarations: self.declarations.clone(),
        })
    }

    pub fn iter_accounts(&self) -> Iter<'_, Identifier, ()> {
        self.accounts.iter()
    }

    pub fn iter_declarations(&self) -> HamtIter<'_, Identifier, Declaration> {
        self.declarations.iter()
    }

    /// 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: &Identifier,
        counter: SpendingCounter,
        value: Value,
    ) -> Result<Self, LedgerError> {
        let new_accts = self.accounts.spend(identifier, counter, value)?;
        Ok(Self {
            accounts: new_accts,
            declarations: self.declarations.clone(),
        })
    }

    /// 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: &Identifier,
        counter: SpendingCounter,
        value: Value,
    ) -> Result<Self, LedgerError> {
        let new_accts = self
            .accounts
            .spend_with_no_counter_check(identifier, counter, value)?;
        Ok(Self {
            accounts: new_accts,
            declarations: self.declarations.clone(),
        })
    }

    /// Gets the `&Declaration` for the given `&Identifier`.
    pub(crate) fn get_declaration_by_id(
        &self,
        identifier: &Identifier,
    ) -> Result<&Declaration, LedgerError> {
        let decl = self
            .declarations
            .lookup(identifier)
            .ok_or(LedgerError::DoesntExist)?;
        Ok(decl)
    }

    /// Set the delegation of an account in this ledger
    pub fn set_delegation(
        &self,
        identifier: &Identifier,
        delegation: &DelegationType,
    ) -> Result<Self, LedgerError> {
        let new_accounts = self.accounts.set_delegation(identifier, delegation)?;
        Ok(Self {
            accounts: new_accounts,
            declarations: self.declarations.clone(),
        })
    }

    pub fn get_total_value(&self) -> Result<Value, ValueError> {
        self.accounts.get_total_value()
    }
}