-
Notifications
You must be signed in to change notification settings - Fork 160
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement balance table #285
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5b45903
Implement balance table
austinabell 08774d1
Update hamt doc test and port over go actor tests
austinabell 422c3f8
Add more tests for fun
austinabell aca6f95
headers
austinabell 5840006
Merge branch 'master' into austin/actor/balancetable
austinabell b89150f
merge conflict import fixes
austinabell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,11 +6,10 @@ use super::hash_bits::HashBits; | |
use super::pointer::Pointer; | ||
use super::{Error, Hash, HashedKey, KeyValuePair, MAX_ARRAY_WIDTH}; | ||
use cid::multihash::Blake2b256; | ||
use forest_encoding::{de::Deserializer, ser::Serializer}; | ||
use forest_ipld::Ipld; | ||
use forest_ipld::{from_ipld, Ipld}; | ||
use ipld_blockstore::BlockStore; | ||
use serde::de::DeserializeOwned; | ||
use serde::{Deserialize, Serialize}; | ||
use serde::{Deserialize, Deserializer, Serialize, Serializer}; | ||
use std::borrow::Borrow; | ||
use std::fmt::Debug; | ||
|
||
|
@@ -129,6 +128,29 @@ where | |
self.pointers.is_empty() | ||
} | ||
|
||
pub(crate) fn for_each<V, S, F>(&self, store: &S, f: &mut F) -> Result<(), String> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. couldn't impl the Iterator trait instead? |
||
where | ||
V: DeserializeOwned, | ||
F: FnMut(&K, V) -> Result<(), String>, | ||
S: BlockStore, | ||
{ | ||
for p in &self.pointers { | ||
match p { | ||
Pointer::Link(cid) => match store.get::<Node<K>>(cid)? { | ||
Some(node) => node.for_each(store, f)?, | ||
None => return Err(format!("Node with cid {} not found", cid)), | ||
}, | ||
Pointer::Cache(n) => n.for_each(store, f)?, | ||
Pointer::Values(kvs) => { | ||
for kv in kvs { | ||
f(kv.0.borrow(), from_ipld(&kv.1).map_err(Error::Encoding)?)?; | ||
} | ||
} | ||
} | ||
} | ||
Ok(()) | ||
} | ||
|
||
/// Search for a key. | ||
fn search<Q: ?Sized, S: BlockStore>( | ||
&self, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
// Copyright 2020 ChainSafe Systems | ||
// SPDX-License-Identifier: Apache-2.0, MIT | ||
|
||
use crate::HAMT_BIT_WIDTH; | ||
use address::Address; | ||
use cid::Cid; | ||
use ipld_blockstore::BlockStore; | ||
use ipld_hamt::{Error, Hamt}; | ||
use num_traits::CheckedSub; | ||
use vm::TokenAmount; | ||
|
||
/// Balance table which handles getting and updating token balances specifically | ||
pub struct BalanceTable<'a, BS>(Hamt<'a, String, BS>); | ||
impl<'a, BS> BalanceTable<'a, BS> | ||
where | ||
BS: BlockStore, | ||
{ | ||
/// Initializes a new empty balance table | ||
pub fn new_empty(bs: &'a BS) -> Self { | ||
Self(Hamt::new_with_bit_width(bs, HAMT_BIT_WIDTH)) | ||
} | ||
|
||
/// Initializes a balance table from a root Cid | ||
pub fn from_root(bs: &'a BS, cid: &Cid) -> Result<Self, Error> { | ||
Ok(Self(Hamt::load_with_bit_width(cid, bs, HAMT_BIT_WIDTH)?)) | ||
} | ||
|
||
/// Retrieve root from balance table | ||
#[inline] | ||
pub fn root(&mut self) -> Result<Cid, Error> { | ||
self.0.flush() | ||
} | ||
|
||
/// Gets token amount for given address in balance table | ||
#[inline] | ||
pub fn get(&self, key: &Address) -> Result<TokenAmount, String> { | ||
Ok(self | ||
.0 | ||
.get(&key.hash_key())? | ||
// TODO investigate whether it's worth it to cache root to give better error details | ||
.ok_or("no key {} in map root")?) | ||
} | ||
|
||
/// Checks if a balance for an address exists | ||
#[inline] | ||
pub fn has(&self, key: &Address) -> Result<bool, Error> { | ||
match self.0.get::<_, TokenAmount>(&key.hash_key())? { | ||
Some(_) => Ok(true), | ||
None => Ok(false), | ||
} | ||
} | ||
|
||
/// Sets the balance for the address, overwriting previous value | ||
#[inline] | ||
pub fn set(&mut self, key: &Address, value: TokenAmount) -> Result<(), Error> { | ||
self.0.set(key.hash_key(), value) | ||
} | ||
|
||
/// Adds token amount to previously initialized account. | ||
pub fn add(&mut self, key: &Address, value: TokenAmount) -> Result<(), String> { | ||
let prev = self.get(key)?; | ||
Ok(self.0.set(key.hash_key(), prev + value)?) | ||
} | ||
|
||
/// Adds an amount to a balance. Creates entry if not exists | ||
pub fn add_create(&mut self, key: &Address, value: TokenAmount) -> Result<(), String> { | ||
let new_val = match self.0.get::<_, TokenAmount>(&key.hash_key())? { | ||
Some(v) => v + value, | ||
None => value, | ||
}; | ||
Ok(self.0.set(key.hash_key(), new_val)?) | ||
} | ||
|
||
/// Subtracts up to the specified amount from a balance, without reducing the balance | ||
/// below some minimum. | ||
/// Returns the amount subtracted (always positive or zero). | ||
pub fn subtract_with_minimum( | ||
&mut self, | ||
key: &Address, | ||
req: &TokenAmount, | ||
floor: &TokenAmount, | ||
) -> Result<TokenAmount, String> { | ||
let prev = self.get(key)?; | ||
let res = prev.checked_sub(req).unwrap_or_else(|| TokenAmount::new(0)); | ||
let new_val: TokenAmount = std::cmp::max(&res, floor).clone(); | ||
|
||
if prev > new_val { | ||
// Subtraction needed, set new value and return change | ||
self.0.set(key.hash_key(), new_val.clone())?; | ||
Ok(prev - new_val) | ||
} else { | ||
// New value is same as previous, no change needed | ||
Ok(TokenAmount::default()) | ||
} | ||
} | ||
|
||
/// Subtracts value from a balance, and errors if full amount was not substracted. | ||
pub fn must_subtract(&mut self, key: &Address, req: &TokenAmount) -> Result<(), String> { | ||
let sub_amt = self.subtract_with_minimum(key, req, &TokenAmount::new(0))?; | ||
if &sub_amt != req { | ||
return Err(format!( | ||
"Couldn't subtract value from address {} (req: {}, available: {})", | ||
key, req, sub_amt | ||
)); | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
/// Removes an entry from the table, returning the prior value. The entry must have been previously initialized. | ||
pub fn remove(&mut self, key: &Address) -> Result<TokenAmount, String> { | ||
// Ensure entry exists and get previous value | ||
let prev = self.get(key)?; | ||
|
||
// Remove entry from table | ||
self.0.delete(&key.hash_key())?; | ||
|
||
Ok(prev) | ||
} | ||
|
||
/// Returns total balance held by this balance table | ||
pub fn total(&self) -> Result<TokenAmount, String> { | ||
let mut total = TokenAmount::default(); | ||
|
||
self.0.for_each(&mut |_, v| { | ||
total += v; | ||
Ok(()) | ||
})?; | ||
|
||
Ok(total) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
// Copyright 2020 ChainSafe Systems | ||
// SPDX-License-Identifier: Apache-2.0, MIT | ||
|
||
mod balance_table; | ||
|
||
pub use self::balance_table::BalanceTable; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
// Copyright 2020 ChainSafe Systems | ||
// SPDX-License-Identifier: Apache-2.0, MIT | ||
|
||
use actor::BalanceTable; | ||
use address::Address; | ||
use vm::TokenAmount; | ||
|
||
// Ported test from specs-actors | ||
#[test] | ||
fn add_create() { | ||
let addr = Address::new_id(100).unwrap(); | ||
let store = db::MemoryDB::default(); | ||
let mut bt = BalanceTable::new_empty(&store); | ||
|
||
assert_eq!(bt.has(&addr), Ok(false)); | ||
|
||
bt.add_create(&addr, TokenAmount::new(10)).unwrap(); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(10))); | ||
|
||
bt.add_create(&addr, TokenAmount::new(20)).unwrap(); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(30))); | ||
} | ||
|
||
// Ported test from specs-actors | ||
#[test] | ||
fn total() { | ||
let addr1 = Address::new_id(100).unwrap(); | ||
let addr2 = Address::new_id(101).unwrap(); | ||
let store = db::MemoryDB::default(); | ||
let mut bt = BalanceTable::new_empty(&store); | ||
|
||
assert_eq!(bt.total(), Ok(TokenAmount::new(0))); | ||
|
||
struct TotalTestCase<'a> { | ||
amount: u64, | ||
addr: &'a Address, | ||
total: u64, | ||
} | ||
let test_vectors = [ | ||
TotalTestCase { | ||
amount: 10, | ||
addr: &addr1, | ||
total: 10, | ||
}, | ||
TotalTestCase { | ||
amount: 20, | ||
addr: &addr1, | ||
total: 30, | ||
}, | ||
TotalTestCase { | ||
amount: 40, | ||
addr: &addr2, | ||
total: 70, | ||
}, | ||
TotalTestCase { | ||
amount: 50, | ||
addr: &addr2, | ||
total: 120, | ||
}, | ||
]; | ||
|
||
for t in test_vectors.iter() { | ||
bt.add_create(t.addr, TokenAmount::new(t.amount)).unwrap(); | ||
|
||
assert_eq!(bt.total(), Ok(TokenAmount::new(t.total))); | ||
} | ||
} | ||
|
||
#[test] | ||
fn balance_subtracts() { | ||
let addr = Address::new_id(100).unwrap(); | ||
let store = db::MemoryDB::default(); | ||
let mut bt = BalanceTable::new_empty(&store); | ||
|
||
bt.set(&addr, TokenAmount::new(80)).unwrap(); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(80))); | ||
// Test subtracting past minimum only subtracts correct amount | ||
assert_eq!( | ||
bt.subtract_with_minimum(&addr, &TokenAmount::new(20), &TokenAmount::new(70)), | ||
Ok(TokenAmount::new(10)) | ||
); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(70))); | ||
|
||
// Test subtracting to limit | ||
assert_eq!( | ||
bt.subtract_with_minimum(&addr, &TokenAmount::new(10), &TokenAmount::new(60)), | ||
Ok(TokenAmount::new(10)) | ||
); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(60))); | ||
|
||
// Test must subtract success | ||
bt.must_subtract(&addr, &TokenAmount::new(10)).unwrap(); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(50))); | ||
|
||
// Test subtracting more than available | ||
assert!(bt.must_subtract(&addr, &TokenAmount::new(100)).is_err()); | ||
} | ||
|
||
#[test] | ||
fn remove() { | ||
let addr = Address::new_id(100).unwrap(); | ||
let store = db::MemoryDB::default(); | ||
let mut bt = BalanceTable::new_empty(&store); | ||
|
||
bt.set(&addr, TokenAmount::new(1)).unwrap(); | ||
assert_eq!(bt.get(&addr), Ok(TokenAmount::new(1))); | ||
bt.remove(&addr).unwrap(); | ||
assert!(bt.get(&addr).is_err()); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
couldn't impl the Iterator trait instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no because all of the elements are not in memory. Also this would be done on top of this, the reason for this is to be able to more closely match the spec.