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
//! A ledger is used to keep track of the books for multiple accounts.
//!
//! For testing, this permits us to perform a kind of double booking.

use ethereum_types::{Address, U256};
use std::collections::{hash_map, HashMap};
use {error, evm};

#[derive(Debug)]
pub struct Ledger<S>
where
    S: LedgerState,
{
    state: S,
    entries: HashMap<Address, S::Entry>,
}

impl<'a> Ledger<AccountBalance<'a>> {
    /// Construct a new empty ledger that doesn't have any specialized state.
    pub fn account_balance(evm: &'a evm::Evm) -> Ledger<AccountBalance<'a>> {
        Self::new(AccountBalance(evm))
    }
}

impl<S> Ledger<S>
where
    S: LedgerState,
{
    /// Construct a new ledger.
    ///
    /// To construct a ledger without state, use `Ledger::empty()`.
    pub fn new(state: S) -> Ledger<S> {
        Ledger {
            state,
            entries: HashMap::new(),
        }
    }

    /// Synchronize the ledger against the current state of the virtual machine.
    pub fn sync(&mut self, address: Address) -> Result<(), error::Error> {
        match self.entries.entry(address) {
            hash_map::Entry::Vacant(entry) => {
                let mut state = self.state.new_instance();
                self.state.sync(address, &mut state)?;
                entry.insert(state);
            }
            hash_map::Entry::Occupied(entry) => {
                self.state.sync(address, entry.into_mut())?;
            }
        }

        Ok(())
    }

    /// Sync multiple addresses.
    pub fn sync_all(&mut self, addresses: Vec<Address>) -> Result<(), error::Error> {
        for a in addresses {
            self.sync(a)?;
        }

        Ok(())
    }

    /// Go through each registered account, and verify their invariants.
    pub fn verify(self) -> Result<(), error::Error> {
        use std::fmt::Write;

        let mut errors = Vec::new();

        let state = self.state;

        // Check that all verifiable entries are matching expectations.
        for (address, s) in self.entries {
            if let Err(e) = state.verify(address, s) {
                errors.push((address, e));
            }
        }

        if !errors.is_empty() {
            let mut msg = String::new();

            writeln!(msg, "Errors in ledger:")?;

            for (address, e) in errors {
                writeln!(msg, "{}: {}", address, e)?;
            }

            return Err(msg.into());
        }

        Ok(())
    }

    /// Access the mutable state for the given address.
    pub fn entry(&mut self, address: Address) -> &mut S::Entry {
        match self.entries.entry(address) {
            hash_map::Entry::Vacant(entry) => {
                let mut state = self.state.new_instance();
                entry.insert(state)
            }
            hash_map::Entry::Occupied(entry) => entry.into_mut(),
        }
    }
}

impl<S> Ledger<S>
where
    S: LedgerState<Entry = U256>,
{
    /// Add to the balance for the given address.
    pub fn add<V>(&mut self, address: Address, value: V)
    where
        V: Into<U256>,
    {
        let current = self.entries.entry(address).or_insert_with(U256::default);
        let value = value.into();

        match current.checked_add(value) {
            None => {
                panic!(
                    "{}: adding {} to the account would overflow the balance",
                    address, value
                );
            }
            Some(update) => {
                *current = update;
            }
        }
    }

    /// Subtract from the balance for the given address.
    pub fn sub<V>(&mut self, address: Address, value: V)
    where
        V: Into<U256>,
    {
        let current = self.entries.entry(address).or_insert_with(U256::default);
        let value = value.into();

        match current.checked_sub(value) {
            None => {
                panic!(
                    "{}: subtracting {} would set account to negative balance",
                    address, value
                );
            }
            Some(update) => {
                *current = update;
            }
        }
    }
}

/// A state that can be verified with a virtual machine.
pub trait LedgerState {
    type Entry;

    /// Construct a new instance.
    fn new_instance(&self) -> Self::Entry;

    /// Verify the given state.
    fn verify(&self, address: Address, instance: Self::Entry) -> Result<(), error::Error>;

    /// Synchronize the given state.
    fn sync(&self, address: Address, instance: &mut Self::Entry) -> Result<(), error::Error>;
}

/// A ledger state checking account balances against the EVM.
pub struct AccountBalance<'a>(&'a evm::Evm);

impl<'a> LedgerState for AccountBalance<'a> {
    type Entry = U256;

    fn new_instance(&self) -> U256 {
        U256::default()
    }

    fn verify(&self, address: Address, expected_balance: Self::Entry) -> Result<(), error::Error> {
        let actual_balance = self.0.balance(address)?;

        if expected_balance != actual_balance {
            return Err(format!(
                "expected account wei balance {}, but was {}",
                expected_balance, actual_balance
            ).into());
        }

        Ok(())
    }

    fn sync(&self, address: Address, balance: &mut Self::Entry) -> Result<(), error::Error> {
        *balance = self.0.balance(address)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{Ledger, LedgerState};
    use error;
    use ethereum_types::{Address, U256};

    #[test]
    fn simple_u256_ledger() {
        let mut ledger = Ledger::new(Simple(0.into(), 42.into()));

        let a = Address::random();

        ledger.sync(a).expect("bad sync");

        ledger.add(a, 10);
        ledger.add(a, 32);

        ledger.verify().expect("ledger not balanced");

        pub struct Simple(U256, U256);

        impl LedgerState for Simple {
            type Entry = U256;

            fn new_instance(&self) -> U256 {
                U256::default()
            }

            fn verify(
                &self,
                _address: Address,
                expected_balance: Self::Entry,
            ) -> Result<(), error::Error> {
                let actual_balance = self.1;

                if expected_balance != actual_balance {
                    return Err(format!(
                        "expected account wei balance {}, but was {}",
                        expected_balance, actual_balance
                    ).into());
                }

                Ok(())
            }

            fn sync(
                &self,
                _address: Address,
                balance: &mut Self::Entry,
            ) -> Result<(), error::Error> {
                *balance = self.0;
                Ok(())
            }
        }
    }
}