Skip to content
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

Change ChainEpoch and TokenAmount types #309

Merged
merged 3 commits into from
Mar 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions blockchain/blocks/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use std::time::{SystemTime, UNIX_EPOCH};
/// use forest_blocks::{BlockHeader, TipSetKeys, Ticket};
/// use address::Address;
/// use cid::Cid;
/// use clock::ChainEpoch;
/// use num_bigint::BigUint;
/// use crypto::Signature;
///
Expand All @@ -36,7 +35,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
/// .bls_aggregate(Signature::new_bls(vec![])) // optional
/// .parents(TipSetKeys::default()) // optional
/// .weight(BigUint::from(0u8)) // optional
/// .epoch(ChainEpoch::default()) // optional
/// .epoch(0) // optional
/// .messages(Cid::default()) // optional
/// .message_receipts(Cid::default()) // optional
/// .state_root(Cid::default()) // optional
Expand Down Expand Up @@ -197,8 +196,8 @@ impl BlockHeader {
&self.weight
}
/// Getter for BlockHeader epoch
pub fn epoch(&self) -> &ChainEpoch {
&self.epoch
pub fn epoch(&self) -> ChainEpoch {
self.epoch
}
/// Getter for BlockHeader miner_address
pub fn miner_address(&self) -> &Address {
Expand Down Expand Up @@ -284,7 +283,7 @@ impl BlockHeader {
// check that it is appropriately delayed from its parents including null blocks
if self.timestamp()
< base_tipset.tipset()?.min_timestamp()?
+ FIXED_BLOCK_DELAY * (*self.epoch() - *base_tipset.tipset()?.epoch()).as_u64()
+ FIXED_BLOCK_DELAY * (self.epoch() - base_tipset.tipset()?.epoch())
{
return Err(Error::Validation(
"Header was generated too soon".to_string(),
Expand Down Expand Up @@ -324,7 +323,6 @@ mod tests {
use address::Address;
use base64;
use cid::Cid;
use clock::ChainEpoch;
use crypto::{Signature, VRFResult};
use encoding::from_slice;
use encoding::to_vec;
Expand Down Expand Up @@ -442,7 +440,7 @@ mod tests {
.bls_aggregate(Signature::new_bls(base64::decode("lLZtMQuT27qNPC4a4AJ8fgdpfMaH1KGlndt+YppQsAdDAK1m4VYIlrY6wtbSAdQEAb1AswRaLdlt9YfJFCg/+mVVhFU648UqnvhRYeBtBZlEA+XMEaim1889O8Ca73PR").unwrap()))
.parents(TipSetKeys{ cids: parents})
.weight(BigUint::from(91439483u64))
.epoch(ChainEpoch::new(7205).unwrap())
.epoch(7205)
.messages(Cid::try_from("BAFY2BZACECEESIZT2Q67TZB3WZMZLLTIHENHZ37AW4B24KFCUBR3AF42DIMRS".to_owned()).unwrap())
.state_root(Cid::try_from("BAFY2BZACEDZ5KXJ6XLNYGKCNFQ6EFZMANDC4VF7NASPXXRHJOOKZEAJUVGFC4".to_owned()).unwrap())
.message_receipts(Cid::try_from("BAFY2BZACECAE6NZYPUOHWAQOVMRP4A7HO6SPBC5QLWW4FKL25OREPPUKBEO2M".to_owned()).unwrap())
Expand Down
4 changes: 2 additions & 2 deletions blockchain/blocks/src/tipset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ impl Tipset {
})
}
/// Returns epoch of the tipset
pub fn epoch(&self) -> &ChainEpoch {
&self.blocks[0].epoch()
pub fn epoch(&self) -> ChainEpoch {
self.blocks[0].epoch()
}
/// Returns all blocks in tipset
pub fn blocks(&self) -> &[BlockHeader] {
Expand Down
2 changes: 1 addition & 1 deletion blockchain/chain/src/store/chain_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ mod tests {

let cs = ChainStore::new(Arc::new(db));
let gen_block = BlockHeader::builder()
.epoch(1.into())
.epoch(1)
.weight((2 as u32).into())
.build_and_validate()
.unwrap();
Expand Down
4 changes: 2 additions & 2 deletions blockchain/chain_sync/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ where
}

const REQUEST_WINDOW: u64 = 100;
let epoch_diff = u64::from(cur_ts.epoch() - to_epoch);
let epoch_diff = cur_ts.epoch() - to_epoch;
let window = min(epoch_diff, REQUEST_WINDOW);

// TODO change from using random peerID to managed
Expand Down Expand Up @@ -519,7 +519,7 @@ where

for i in 0..tips.len() {
while ts.epoch() > tips[i].epoch() {
if *ts.epoch().as_u64() == 0 {
if ts.epoch() == 0 {
return Err(Error::Other(
"Synced chain forked at genesis, refusing to sync".to_string(),
));
Expand Down
9 changes: 9 additions & 0 deletions math/bigint/src/bigint_ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ impl Serialize for BigIntSer<'_> {
}
}

impl Serialize for BigIntDe {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serialize(&self.0, serializer)
}
}

impl<'de> Deserialize<'de> for BigIntDe {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down
9 changes: 9 additions & 0 deletions math/bigint/src/biguint_ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ impl Serialize for BigUintSer<'_> {
}
}

impl Serialize for BigUintDe {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serialize(&self.0, serializer)
}
}

impl<'de> Deserialize<'de> for BigUintDe {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down
55 changes: 2 additions & 53 deletions node/clock/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,13 @@
// SPDX-License-Identifier: Apache-2.0, MIT

use chrono::{DateTime, NaiveDateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::num::TryFromIntError;
use std::ops::{Add, Sub};

const _ISO_FORMAT: &str = "%FT%X.%.9F";
const EPOCH_DURATION: i32 = 15;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, PartialOrd, Serialize, Deserialize)]
/// An epoch represents a single valid state in the blockchain
pub struct ChainEpoch(pub u64);

impl From<u64> for ChainEpoch {
fn from(num: u64) -> ChainEpoch {
ChainEpoch(num)
}
}
pub type ChainEpoch = u64;

/// ChainEpochClock is used by the system node to assume weak clock synchrony amongst the other
/// systems.
Expand Down Expand Up @@ -54,48 +45,6 @@ impl ChainEpochClock {
let epochs = (difference / EPOCH_DURATION)
.num_nanoseconds()
.expect("Epoch_at_time failed");
Ok(ChainEpoch(epochs.try_into()?))
}
}

impl Add for ChainEpoch {
type Output = Self;

fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}

// TODO revisit usage of the Sub impls, these will panic (checked sub or floored sub would be safer)
impl Sub for ChainEpoch {
type Output = ChainEpoch;

fn sub(self, other: ChainEpoch) -> ChainEpoch {
ChainEpoch(self.0 - other.0)
}
}

impl Sub for &ChainEpoch {
type Output = ChainEpoch;

fn sub(self, other: &ChainEpoch) -> ChainEpoch {
ChainEpoch(self.0 - other.0)
}
}

impl From<ChainEpoch> for u64 {
fn from(ce: ChainEpoch) -> u64 {
ce.0
}
}

impl ChainEpoch {
/// Returns ChainEpoch based on the given unix timestamp
pub fn new(timestamp: i64) -> Result<ChainEpoch, TryFromIntError> {
Ok(ChainEpoch(timestamp.try_into()?))
}
// Returns chain epoch as u64
pub fn as_u64(&self) -> &u64 {
&self.0
Ok(epochs.try_into()?)
}
}
4 changes: 2 additions & 2 deletions node/forest_libp2p/tests/decode_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@ fn convert_single_tipset_bundle() {
#[test]
fn tipset_bundle_to_full_tipset() {
let h0 = BlockHeader::builder()
.weight(BigUint::from(1 as u32))
.weight(BigUint::from(1u32))
.build()
.unwrap();
let h1 = BlockHeader::builder()
.weight(BigUint::from(2 as u32))
.weight(BigUint::from(2u32))
.build()
.unwrap();
let ua = UnsignedMessage::builder()
Expand Down
3 changes: 1 addition & 2 deletions node/forest_libp2p/tests/hello_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
mod rpc_test_utils;

use self::rpc_test_utils::*;
use clock::ChainEpoch;
use forest_cid::Cid;
use forest_libp2p::hello::{HelloMessage, HelloResponse};
use forest_libp2p::rpc::{RPCEvent, RPCMessage, RPCRequest, RPCResponse};
Expand All @@ -18,7 +17,7 @@ fn test_empty_rpc() {
let rpc_request = RPCRequest::Hello(HelloMessage {
heaviest_tip_set: vec![Cid::default()],
heaviest_tipset_weight: BigInt::from(1),
heaviest_tipset_height: ChainEpoch::from(2),
heaviest_tipset_height: 2,
genesis_hash: Cid::default(),
});

Expand Down
2 changes: 1 addition & 1 deletion vm/actor/src/builtin/cron/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl Actor {
&entry.receiver,
entry.method_num,
&Serialized::default(),
&TokenAmount::new(0),
&TokenAmount::from(0u8),
)?;
}
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions vm/actor/src/builtin/multisig/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,13 @@ impl Actor {
signers: params.signers,
num_approvals_threshold: params.num_approvals_threshold,
pending_txs: empty_root,
initial_balance: TokenAmount::new(0),
initial_balance: TokenAmount::from(0u8),
next_tx_id: Default::default(),
start_epoch: Default::default(),
unlock_duration: Default::default(),
};

if params.unlock_duration.0 != 0 {
if params.unlock_duration != 0 {
st.initial_balance = rt.message().value().clone();
st.unlock_duration = params.unlock_duration;
st.start_epoch = rt.curr_epoch();
Expand Down
21 changes: 11 additions & 10 deletions vm/actor/src/builtin/multisig/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use clock::ChainEpoch;
use encoding::Cbor;
use ipld_blockstore::BlockStore;
use ipld_hamt::Hamt;
use num_bigint::biguint_ser::{BigUintDe, BigUintSer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::TokenAmount;

Expand All @@ -29,10 +30,10 @@ impl State {
/// Returns amount locked in multisig contract
pub fn amount_locked(&self, elapsed_epoch: ChainEpoch) -> TokenAmount {
if elapsed_epoch >= self.unlock_duration {
return TokenAmount::new(0);
return TokenAmount::from(0u8);
}
let unit_locked = self.initial_balance.0.clone() / self.unlock_duration.0;
TokenAmount(unit_locked * (self.unlock_duration.0 - elapsed_epoch.0))
let unit_locked = self.initial_balance.clone() / self.unlock_duration;
unit_locked * (self.unlock_duration - elapsed_epoch)
}

pub(crate) fn is_signer(&self, addr: &Address) -> bool {
Expand All @@ -51,19 +52,19 @@ impl State {
curr_epoch: ChainEpoch,
) -> Result<(), String> {
// * Note `< 0` check skipped because `TokenAmount` is big uint
if balance.0 < amount_to_spend.0 {
if balance < amount_to_spend {
return Err(format!(
"current balance {} less than amount to spend {}",
balance.0, amount_to_spend.0
balance, amount_to_spend
));
}

let remaining_balance = balance.0 - amount_to_spend.0;
let remaining_balance = balance - amount_to_spend;
let amount_locked = self.amount_locked(curr_epoch - self.start_epoch);
if remaining_balance < amount_locked.0 {
if remaining_balance < amount_locked {
return Err(format!(
"actor balance if spent {} would be less than required locked amount {}",
remaining_balance, amount_locked.0
remaining_balance, amount_locked
));
}
Ok(())
Expand Down Expand Up @@ -118,7 +119,7 @@ impl Serialize for State {
&self.signers,
&self.num_approvals_threshold,
&self.next_tx_id,
&self.initial_balance,
BigUintSer(&self.initial_balance),
&self.start_epoch,
&self.unlock_duration,
&self.pending_txs,
Expand All @@ -136,7 +137,7 @@ impl<'de> Deserialize<'de> for State {
signers,
num_approvals_threshold,
next_tx_id,
initial_balance,
BigUintDe(initial_balance),
start_epoch,
unlock_duration,
pending_txs,
Expand Down
16 changes: 12 additions & 4 deletions vm/actor/src/builtin/multisig/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use address::Address;
use clock::ChainEpoch;
use num_bigint::biguint_ser::{BigUintDe, BigUintSer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::{MethodNum, Serialized, TokenAmount};

Expand Down Expand Up @@ -54,7 +55,7 @@ impl Serialize for Transaction {
{
(
&self.to,
&self.value,
BigUintSer(&self.value),
&self.method,
&self.params,
&self.approved,
Expand All @@ -68,7 +69,8 @@ impl<'de> Deserialize<'de> for Transaction {
where
D: Deserializer<'de>,
{
let (to, value, method, params, approved) = Deserialize::deserialize(deserializer)?;
let (to, BigUintDe(value), method, params, approved) =
Deserialize::deserialize(deserializer)?;
Ok(Self {
to,
value,
Expand Down Expand Up @@ -128,7 +130,13 @@ impl Serialize for ProposeParams {
where
S: Serializer,
{
(&self.to, &self.value, &self.method, &self.params).serialize(serializer)
(
&self.to,
BigUintSer(&self.value),
&self.method,
&self.params,
)
.serialize(serializer)
}
}

Expand All @@ -137,7 +145,7 @@ impl<'de> Deserialize<'de> for ProposeParams {
where
D: Deserializer<'de>,
{
let (to, value, method, params) = Deserialize::deserialize(deserializer)?;
let (to, BigUintDe(value), method, params) = Deserialize::deserialize(deserializer)?;
Ok(Self {
to,
value,
Expand Down
Loading