From 14ec981173d6d69fe4e3d3fd54a557d465436d8b Mon Sep 17 00:00:00 2001 From: Seulgi Kim Date: Sat, 26 Oct 2019 23:38:47 +0900 Subject: [PATCH 1/3] Distinguish BlockHash from H256 --- core/src/blockchain/block_info.rs | 8 +- core/src/blockchain/blockchain.rs | 38 +++--- core/src/blockchain/body_db.rs | 15 +-- core/src/blockchain/extras.rs | 50 ++++---- core/src/blockchain/headerchain.rs | 63 +++++----- core/src/blockchain/route.rs | 20 ++-- core/src/blockchain_info.rs | 10 +- core/src/client/chain_notify.rs | 23 ++-- core/src/client/client.rs | 42 +++---- core/src/client/importer.rs | 10 +- core/src/client/mod.rs | 16 +-- core/src/client/test_client.rs | 35 +++--- core/src/consensus/blake_pow/mod.rs | 2 +- core/src/consensus/cuckoo/mod.rs | 2 +- core/src/consensus/mod.rs | 14 +-- core/src/consensus/simple_poa/mod.rs | 3 +- core/src/consensus/stake/actions.rs | 31 ++--- core/src/consensus/tendermint/backup.rs | 8 +- core/src/consensus/tendermint/chain_notify.rs | 12 +- core/src/consensus/tendermint/engine.rs | 13 +-- core/src/consensus/tendermint/message.rs | 23 ++-- core/src/consensus/tendermint/mod.rs | 3 - core/src/consensus/tendermint/network.rs | 21 +++- core/src/consensus/tendermint/types.rs | 30 ++--- .../consensus/tendermint/vote_collector.rs | 16 +-- .../tendermint/vote_regression_checker.rs | 34 +++--- core/src/consensus/tendermint/worker.rs | 55 +++++---- .../validator_set/dynamic_validator.rs | 26 ++--- core/src/consensus/validator_set/mod.rs | 20 ++-- .../consensus/validator_set/validator_list.rs | 20 ++-- core/src/encoded.rs | 12 +- core/src/error.rs | 6 +- core/src/miner/miner.rs | 20 ++-- core/src/miner/mod.rs | 13 ++- core/src/miner/stratum.rs | 2 +- core/src/scheme/genesis.rs | 5 +- core/src/scheme/scheme.rs | 4 +- core/src/service.rs | 5 +- core/src/tests/helpers.rs | 6 +- core/src/transaction.rs | 4 +- core/src/types/ids.rs | 8 +- core/src/verification/queue/kind.rs | 27 ++--- core/src/verification/queue/mod.rs | 19 +-- core/src/views/block.rs | 4 +- core/src/views/body.rs | 10 +- core/src/views/header.rs | 10 +- rpc/src/v1/impls/chain.rs | 8 +- rpc/src/v1/impls/miner.rs | 4 +- rpc/src/v1/traits/chain.rs | 8 +- rpc/src/v1/traits/miner.rs | 4 +- rpc/src/v1/types/block.rs | 8 +- rpc/src/v1/types/transaction.rs | 3 +- sync/src/block/downloader/body.rs | 20 ++-- sync/src/block/downloader/header.rs | 19 +-- sync/src/block/extension.rs | 48 ++++---- sync/src/block/message/mod.rs | 14 ++- sync/src/block/message/request.rs | 14 +-- sync/src/snapshot/service.rs | 15 ++- types/src/block_hash.rs | 109 ++++++++++++++++++ types/src/header.rs | 16 +-- types/src/lib.rs | 4 + 61 files changed, 637 insertions(+), 475 deletions(-) create mode 100644 types/src/block_hash.rs diff --git a/core/src/blockchain/block_info.rs b/core/src/blockchain/block_info.rs index a91b5de88a..eac929b1f4 100644 --- a/core/src/blockchain/block_info.rs +++ b/core/src/blockchain/block_info.rs @@ -16,7 +16,9 @@ use super::route::TreeRoute; use crate::views::{BlockView, HeaderView}; -use primitives::{Bytes, H256}; + +use ctypes::BlockHash; +use primitives::Bytes; /// Describes how best block is changed #[derive(Debug, Clone, PartialEq)] @@ -37,7 +39,7 @@ pub enum BestBlockChanged { } impl BestBlockChanged { - pub fn new_best_hash(&self) -> Option { + pub fn new_best_hash(&self) -> Option { Some(self.best_block()?.hash()) } @@ -76,7 +78,7 @@ pub enum BestHeaderChanged { } impl BestHeaderChanged { - pub fn new_best_hash(&self) -> Option { + pub fn new_best_hash(&self) -> Option { Some(self.header()?.hash()) } diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index 948ee0c3b4..9e99ff4f9f 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -16,7 +16,7 @@ use std::sync::Arc; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::RwLock; use primitives::H256; @@ -44,16 +44,16 @@ const BEST_PROPOSAL_BLOCK_KEY: &[u8] = b"best-proposal-block"; /// **Does not do input data verification.** pub struct BlockChain { /// The hash of the best block of the canonical chain. - best_block_hash: RwLock, + best_block_hash: RwLock, /// The hash of the block which has the best score among the proposal blocks - best_proposal_block_hash: RwLock, + best_proposal_block_hash: RwLock, headerchain: HeaderChain, body_db: BodyDB, invoice_db: InvoiceDB, - pending_best_block_hash: RwLock>, - pending_best_proposal_block_hash: RwLock>, + pending_best_block_hash: RwLock>, + pending_best_proposal_block_hash: RwLock>, } impl BlockChain { @@ -63,7 +63,7 @@ impl BlockChain { // load best block let best_block_hash = match db.get(db::COL_EXTRA, BEST_BLOCK_KEY).unwrap() { - Some(hash) => H256::from_slice(&hash), + Some(hash) => H256::from_slice(&hash).into(), None => { let hash = genesis_block.hash(); @@ -75,7 +75,7 @@ impl BlockChain { }; let best_proposal_block_hash = match db.get(db::COL_EXTRA, BEST_PROPOSAL_BLOCK_KEY).unwrap() { - Some(hash) => H256::from_slice(&hash), + Some(hash) => H256::from_slice(&hash).into(), None => { let hash = genesis_block.hash(); let mut batch = DBTransaction::new(); @@ -235,7 +235,7 @@ impl BlockChain { /// The new best block should be a child of the current best block. /// This will not change the best proposal block chain. This means it is possible /// to have the best block and the best proposal block in different branches. - pub fn update_best_as_committed(&self, batch: &mut DBTransaction, block_hash: H256) -> ImportRoute { + pub fn update_best_as_committed(&self, batch: &mut DBTransaction, block_hash: BlockHash) -> ImportRoute { // FIXME: If it is possible, double check with the consensus engine. ctrace!(BLOCKCHAIN, "Update the best block to {}", block_hash); @@ -311,12 +311,12 @@ impl BlockChain { } /// Get best block hash. - pub fn best_block_hash(&self) -> H256 { + pub fn best_block_hash(&self) -> BlockHash { *self.best_block_hash.read() } /// Get best_proposal block hash. - pub fn best_proposal_block_hash(&self) -> H256 { + pub fn best_proposal_block_hash(&self) -> BlockHash { *self.best_proposal_block_hash.read() } @@ -349,12 +349,12 @@ impl BlockChain { pub trait BlockProvider: HeaderProvider + BodyProvider + InvoiceProvider { /// Returns true if the given block is known /// (though not necessarily a part of the canon chain). - fn is_known(&self, hash: &H256) -> bool { + fn is_known(&self, hash: &BlockHash) -> bool { self.is_known_header(hash) && self.is_known_body(hash) } /// Get raw block data - fn block(&self, hash: &H256) -> Option { + fn block(&self, hash: &BlockHash) -> Option { let header = self.block_header_data(hash)?; let body = self.block_body(hash)?; @@ -377,7 +377,7 @@ pub trait BlockProvider: HeaderProvider + BodyProvider + InvoiceProvider { /// Get a list of transactions for a given block. /// Returns None if block does not exist. - fn transactions(&self, block_hash: &H256) -> Option> { + fn transactions(&self, block_hash: &BlockHash) -> Option> { self.block_body(block_hash) .and_then(|body| self.block_number(block_hash).map(|n| body.view().localized_transactions(block_hash, n))) } @@ -386,28 +386,28 @@ pub trait BlockProvider: HeaderProvider + BodyProvider + InvoiceProvider { impl HeaderProvider for BlockChain { /// Returns true if the given block is known /// (though not necessarily a part of the canon chain). - fn is_known_header(&self, hash: &H256) -> bool { + fn is_known_header(&self, hash: &BlockHash) -> bool { self.headerchain.is_known_header(hash) } /// Get the familial details concerning a block. - fn block_details(&self, hash: &H256) -> Option { + fn block_details(&self, hash: &BlockHash) -> Option { self.headerchain.block_details(hash) } /// Get the hash of given block's number. - fn block_hash(&self, index: BlockNumber) -> Option { + fn block_hash(&self, index: BlockNumber) -> Option { self.headerchain.block_hash(index) } /// Get the header RLP of a block. - fn block_header_data(&self, hash: &H256) -> Option { + fn block_header_data(&self, hash: &BlockHash) -> Option { self.headerchain.block_header_data(hash) } } impl BodyProvider for BlockChain { - fn is_known_body(&self, hash: &H256) -> bool { + fn is_known_body(&self, hash: &BlockHash) -> bool { self.body_db.is_known_body(hash) } @@ -419,7 +419,7 @@ impl BodyProvider for BlockChain { self.body_db.transaction_address_by_tracker(tracker) } - fn block_body(&self, hash: &H256) -> Option { + fn block_body(&self, hash: &BlockHash) -> Option { self.body_db.block_body(hash) } } diff --git a/core/src/blockchain/body_db.rs b/core/src/blockchain/body_db.rs index a97a591989..6a016eba18 100644 --- a/core/src/blockchain/body_db.rs +++ b/core/src/blockchain/body_db.rs @@ -18,6 +18,7 @@ use std::collections::{HashMap, HashSet}; use std::mem; use std::sync::Arc; +use ctypes::BlockHash; use kvdb::{DBTransaction, KeyValueDB}; use lru_cache::LruCache; use parking_lot::{Mutex, RwLock}; @@ -35,7 +36,7 @@ const BODY_CACHE_SIZE: usize = 1000; pub struct BodyDB { // block cache - body_cache: Mutex>, + body_cache: Mutex>, parcel_address_cache: RwLock>, pending_parcel_addresses: RwLock>>, @@ -280,7 +281,7 @@ impl BodyDB { pub trait BodyProvider { /// Returns true if the given block is known /// (though not necessarily a part of the canon chain). - fn is_known_body(&self, hash: &H256) -> bool; + fn is_known_body(&self, hash: &BlockHash) -> bool; /// Get the address of parcel with given hash. fn transaction_address(&self, hash: &H256) -> Option; @@ -288,11 +289,11 @@ pub trait BodyProvider { fn transaction_address_by_tracker(&self, tracker: &H256) -> Option; /// Get the block body (uncles and parcels). - fn block_body(&self, hash: &H256) -> Option; + fn block_body(&self, hash: &BlockHash) -> Option; } impl BodyProvider for BodyDB { - fn is_known_body(&self, hash: &H256) -> bool { + fn is_known_body(&self, hash: &BlockHash) -> bool { self.block_body(hash).is_some() } @@ -308,7 +309,7 @@ impl BodyProvider for BodyDB { } /// Get block body data - fn block_body(&self, hash: &H256) -> Option { + fn block_body(&self, hash: &BlockHash) -> Option { // Check cache first { let mut lock = self.body_cache.lock(); @@ -330,7 +331,7 @@ impl BodyProvider for BodyDB { } fn parcel_address_entries( - block_hash: H256, + block_hash: BlockHash, parcel_hashes: impl IntoIterator, ) -> impl Iterator)> { parcel_hashes.into_iter().enumerate().map(move |(index, parcel_hash)| { @@ -345,7 +346,7 @@ fn parcel_address_entries( } fn transaction_address_entries( - block_hash: H256, + block_hash: BlockHash, parcel_hashes: impl IntoIterator, ) -> impl Iterator { parcel_hashes.into_iter().enumerate().filter_map(move |(parcel_index, parcel)| { diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index 8f86d1919c..a48555d33b 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -16,7 +16,7 @@ use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::{H256, H264, U256}; use crate::db::Key; @@ -55,7 +55,7 @@ impl Deref for BlockNumberKey { } -impl Key for BlockNumber { +impl Key for BlockNumber { type Target = BlockNumberKey; fn key(&self) -> Self::Target { @@ -69,7 +69,7 @@ impl Key for BlockNumber { } } -impl Key for H256 { +impl Key for BlockHash { type Target = H264; fn key(&self) -> H264 { @@ -101,14 +101,14 @@ pub struct BlockDetails { /// Total score of the block and all its parents pub total_score: U256, /// Parent block hash - pub parent: H256, + pub parent: BlockHash, } /// Represents address of certain transaction within block #[derive(Debug, PartialEq, Clone, Copy, RlpEncodable, RlpDecodable)] pub struct TransactionAddress { /// Block hash - pub block_hash: H256, + pub block_hash: BlockHash, /// Parcel index within the block pub index: usize, } @@ -191,7 +191,7 @@ mod tests { #[test] fn encode_and_decode_transaction_address_with_single_address() { rlp_encode_and_decode_test!(TransactionAddresses::new(TransactionAddress { - block_hash: H256::random(), + block_hash: H256::random().into(), index: 0, })); } @@ -206,15 +206,15 @@ mod tests { rlp_encode_and_decode_test!(TransactionAddresses { addresses: vec![ TransactionAddress { - block_hash: H256::random(), + block_hash: H256::random().into(), index: 0, }, TransactionAddress { - block_hash: H256::random(), + block_hash: H256::random().into(), index: 3, }, TransactionAddress { - block_hash: H256::random(), + block_hash: H256::random().into(), index: 1, }, ], @@ -225,24 +225,24 @@ mod tests { fn add() { let t1 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }], }; let t2 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 1.into(), + block_hash: H256::from(1).into(), index: 0, }], }; assert_eq!( vec![ TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }, TransactionAddress { - block_hash: 1.into(), + block_hash: H256::from(1).into(), index: 0, } ], @@ -254,19 +254,19 @@ mod tests { fn do_not_add_duplicated_item() { let t1 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }], }; let t2 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }], }; assert_eq!( vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, },], (t1 + t2).addresses @@ -278,33 +278,33 @@ mod tests { let t1 = TransactionAddresses { addresses: vec![ TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }, TransactionAddress { - block_hash: 1.into(), + block_hash: H256::from(1).into(), index: 0, }, TransactionAddress { - block_hash: 2.into(), + block_hash: H256::from(2).into(), index: 0, }, ], }; let t2 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 1.into(), + block_hash: H256::from(1).into(), index: 0, }], }; assert_eq!( vec![ TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }, TransactionAddress { - block_hash: 2.into(), + block_hash: H256::from(2).into(), index: 0, } ], @@ -316,19 +316,19 @@ mod tests { fn remove_dont_touch_unmatched_item() { let t1 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, }], }; let t2 = TransactionAddresses { addresses: vec![TransactionAddress { - block_hash: 1.into(), + block_hash: H256::from(1).into(), index: 0, }], }; assert_eq!( vec![TransactionAddress { - block_hash: 0.into(), + block_hash: H256::zero().into(), index: 0, },], (t1 - t2).addresses diff --git a/core/src/blockchain/headerchain.rs b/core/src/blockchain/headerchain.rs index 31831893c5..2451bfc0b6 100644 --- a/core/src/blockchain/headerchain.rs +++ b/core/src/blockchain/headerchain.rs @@ -19,7 +19,7 @@ use std::mem; use std::sync::Arc; use ctypes::header::{Header, Seal}; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use kvdb::{DBTransaction, KeyValueDB}; use lru_cache::LruCache; use parking_lot::{Mutex, RwLock}; @@ -44,21 +44,21 @@ const HEADER_CACHE_SIZE: usize = 1000; pub struct HeaderChain { // All locks must be captured in the order declared here. /// The hash of the best block of the canonical chain. - best_header_hash: RwLock, + best_header_hash: RwLock, /// The hash of the block which has the best score among the proposal blocks - best_proposal_header_hash: RwLock, + best_proposal_header_hash: RwLock, // cache - header_cache: Mutex>, - detail_cache: RwLock>, - hash_cache: Mutex>, + header_cache: Mutex>, + detail_cache: RwLock>, + hash_cache: Mutex>, db: Arc, - pending_best_header_hash: RwLock>, - pending_best_proposal_block_hash: RwLock>, - pending_hashes: RwLock>, - pending_details: RwLock>, + pending_best_header_hash: RwLock>, + pending_best_proposal_block_hash: RwLock>, + pending_hashes: RwLock>, + pending_details: RwLock>, } impl HeaderChain { @@ -66,7 +66,7 @@ impl HeaderChain { pub fn new(genesis: &HeaderView, db: Arc) -> Self { // load best header let best_header_hash = match db.get(db::COL_EXTRA, BEST_HEADER_KEY).unwrap() { - Some(hash) => H256::from_slice(&hash), + Some(hash) => H256::from_slice(&hash).into(), None => { // best header does not exist // we need to insert genesis into the cache @@ -95,7 +95,8 @@ impl HeaderChain { &db.get(db::COL_EXTRA, BEST_PROPOSAL_HEADER_KEY) .unwrap() .expect("best proposal header is set by best header"), - ); + ) + .into(); Self { best_header_hash: RwLock::new(best_header_hash), @@ -189,7 +190,7 @@ impl HeaderChain { } /// This function returns modified block hashes. - fn new_hash_entries(&self, best_header_changed: &BestHeaderChanged) -> HashMap { + fn new_hash_entries(&self, best_header_changed: &BestHeaderChanged) -> HashMap { let mut hashes = HashMap::new(); match best_header_changed { @@ -221,7 +222,7 @@ impl HeaderChain { /// This function returns modified block details. /// Uses the given parent details or attempts to load them from the database. - fn new_detail_entries(&self, header: &HeaderView) -> HashMap { + fn new_detail_entries(&self, header: &HeaderView) -> HashMap { let parent_hash = header.parent_hash(); let parent_details = self.block_details(&parent_hash).expect("Invalid parent hash"); @@ -292,7 +293,7 @@ impl HeaderChain { /// in Tendermint. /// /// Used in BlockChain::update_best_as_committed(). - pub fn update_best_as_committed(&self, batch: &mut DBTransaction, block_hash: H256) { + pub fn update_best_as_committed(&self, batch: &mut DBTransaction, block_hash: BlockHash) { assert!(self.pending_best_header_hash.read().is_none()); let prev_best_header_number = self.best_header().number(); @@ -320,11 +321,11 @@ impl HeaderChain { } /// Get best block hash. - pub fn best_header_hash(&self) -> H256 { + pub fn best_header_hash(&self) -> BlockHash { *self.best_header_hash.read() } - pub fn best_proposal_header_hash(&self) -> H256 { + pub fn best_proposal_header_hash(&self) -> BlockHash { *self.best_proposal_header_hash.read() } @@ -345,29 +346,29 @@ impl HeaderChain { pub trait HeaderProvider { /// Returns true if the given block is known /// (though not necessarily a part of the canon chain). - fn is_known_header(&self, hash: &H256) -> bool; + fn is_known_header(&self, hash: &BlockHash) -> bool; /// Get the familial details concerning a block. - fn block_details(&self, hash: &H256) -> Option; + fn block_details(&self, hash: &BlockHash) -> Option; /// Get the hash of given block's number. - fn block_hash(&self, index: BlockNumber) -> Option; + fn block_hash(&self, index: BlockNumber) -> Option; /// Get the partial-header of a block. - fn block_header(&self, hash: &H256) -> Option
{ + fn block_header(&self, hash: &BlockHash) -> Option
{ self.block_header_data(hash).map(|header| header.decode()) } /// Get the header RLP of a block. - fn block_header_data(&self, hash: &H256) -> Option; + fn block_header_data(&self, hash: &BlockHash) -> Option; /// Get the number of given block's hash. - fn block_number(&self, hash: &H256) -> Option { + fn block_number(&self, hash: &BlockHash) -> Option { self.block_details(hash).map(|details| details.number) } /// Returns reference to genesis hash. - fn genesis_hash(&self) -> H256 { + fn genesis_hash(&self) -> BlockHash { self.block_hash(0).expect("Genesis hash should always exist") } @@ -378,18 +379,18 @@ pub trait HeaderProvider { } impl HeaderProvider for HeaderChain { - fn is_known_header(&self, hash: &H256) -> bool { + fn is_known_header(&self, hash: &BlockHash) -> bool { self.db.exists_with_cache(db::COL_EXTRA, &self.detail_cache, hash) } /// Get the familial details concerning a block. - fn block_details(&self, hash: &H256) -> Option { + fn block_details(&self, hash: &BlockHash) -> Option { let result = self.db.read_with_cache(db::COL_EXTRA, &mut *self.detail_cache.write(), hash)?; Some(result) } /// Get the hash of given block's number. - fn block_hash(&self, index: BlockNumber) -> Option { + fn block_hash(&self, index: BlockNumber) -> Option { // Highest block should not be accessed by block number. if self.best_header().number() < index { return None @@ -399,7 +400,7 @@ impl HeaderProvider for HeaderChain { } /// Get block header data - fn block_header_data(&self, hash: &H256) -> Option { + fn block_header_data(&self, hash: &BlockHash) -> Option { let result = block_header_data(hash, &self.header_cache, &*self.db).map(encoded::Header::new); if let Some(header) = &result { debug_assert_eq!(*hash, header.hash()); @@ -409,7 +410,11 @@ impl HeaderProvider for HeaderChain { } /// Get block header data -fn block_header_data(hash: &H256, header_cache: &Mutex>, db: &dyn KeyValueDB) -> Option> { +fn block_header_data( + hash: &BlockHash, + header_cache: &Mutex>, + db: &dyn KeyValueDB, +) -> Option> { // Check cache first { let mut lock = header_cache.lock(); diff --git a/core/src/blockchain/route.rs b/core/src/blockchain/route.rs index 553680bb60..7d7d7aa9ef 100644 --- a/core/src/blockchain/route.rs +++ b/core/src/blockchain/route.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use primitives::H256; +use ctypes::BlockHash; use super::block_info::{BestBlockChanged, BestHeaderChanged}; use super::headerchain::HeaderProvider; @@ -23,13 +23,13 @@ use super::headerchain::HeaderProvider; #[derive(Clone, Debug, PartialEq)] pub struct TreeRoute { /// Best common ancestor of these blocks. - pub ancestor: H256, + pub ancestor: BlockHash, /// A vector of enacted block hashes /// First item of list must be child of ancestor - pub enacted: Vec, + pub enacted: Vec, /// A vector of retracted block hashes /// Last item of list must be child of ancestor - pub retracted: Vec, + pub retracted: Vec, } /// Returns a tree route between `from` and `to`, which is a tuple of: @@ -71,7 +71,7 @@ pub struct TreeRoute { /// /// If the tree route verges into pruned or unknown blocks, /// `None` is returned. -pub fn tree_route(db: &dyn HeaderProvider, from: H256, to: H256) -> Option { +pub fn tree_route(db: &dyn HeaderProvider, from: BlockHash, to: BlockHash) -> Option { let mut retracted = vec![]; let mut enacted = vec![]; @@ -112,15 +112,15 @@ pub fn tree_route(db: &dyn HeaderProvider, from: H256, to: H256) -> Option, + pub retracted: Vec, /// Blocks that were validated by new block. - pub enacted: Vec, + pub enacted: Vec, /// Blocks which are neither retracted nor enacted. - pub omitted: Vec, + pub omitted: Vec, } impl ImportRoute { - pub fn new(new_block_hash: H256, best_block_changed: &BestBlockChanged) -> Self { + pub fn new(new_block_hash: BlockHash, best_block_changed: &BestBlockChanged) -> Self { let mut omitted = Vec::new(); if best_block_changed.new_best_hash() != Some(new_block_hash) { omitted.push(new_block_hash); @@ -159,7 +159,7 @@ impl ImportRoute { } } - pub fn new_from_best_header_changed(new_block_hash: H256, best_header_changed: &BestHeaderChanged) -> Self { + pub fn new_from_best_header_changed(new_block_hash: BlockHash, best_header_changed: &BestHeaderChanged) -> Self { let mut omitted = Vec::new(); if best_header_changed.new_best_hash() != Some(new_block_hash) { omitted.push(new_block_hash); diff --git a/core/src/blockchain_info.rs b/core/src/blockchain_info.rs index 32c620d087..065605543b 100644 --- a/core/src/blockchain_info.rs +++ b/core/src/blockchain_info.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::BlockNumber; -use primitives::{H256, U256}; +use ctypes::{BlockHash, BlockNumber}; +use primitives::U256; /// Information about the blockchain gathered together. #[derive(Clone, Debug)] @@ -27,11 +27,11 @@ pub struct BlockChainInfo { /// Block queue score. pub pending_total_score: U256, /// Genesis block hash. - pub genesis_hash: H256, + pub genesis_hash: BlockHash, /// Best blockchain block hash. - pub best_block_hash: H256, + pub best_block_hash: BlockHash, /// Best blockchain proposal block hash. - pub best_proposal_block_hash: H256, + pub best_proposal_block_hash: BlockHash, /// Best blockchain block number. pub best_block_number: BlockNumber, /// Best blockchain block timestamp. diff --git a/core/src/client/chain_notify.rs b/core/src/client/chain_notify.rs index 03ce1f6ae3..dfbdba5d56 100644 --- a/core/src/client/chain_notify.rs +++ b/core/src/client/chain_notify.rs @@ -15,6 +15,7 @@ // along with this program. If not, see . use cnetwork::NodeId; +use ctypes::BlockHash; use primitives::H256; /// Represents what has to be handled by actor listening to chain events @@ -22,13 +23,13 @@ pub trait ChainNotify: Send + Sync { /// fires when chain has new headers. fn new_headers( &self, - _imported: Vec, - _invalid: Vec, - _enacted: Vec, - _retracted: Vec, - _sealed: Vec, + _imported: Vec, + _invalid: Vec, + _enacted: Vec, + _retracted: Vec, + _sealed: Vec, _duration: u64, - _new_best_proposal: Option, + _new_best_proposal: Option, ) { // does nothing by default } @@ -36,11 +37,11 @@ pub trait ChainNotify: Send + Sync { /// fires when chain has new blocks. fn new_blocks( &self, - _imported: Vec, - _invalid: Vec, - _enacted: Vec, - _retracted: Vec, - _sealed: Vec, + _imported: Vec, + _invalid: Vec, + _enacted: Vec, + _retracted: Vec, + _sealed: Vec, _duration: u64, ) { // does nothing by default diff --git a/core/src/client/client.rs b/core/src/client/client.rs index 9c3fb6824c..846a031ec4 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -28,7 +28,7 @@ use cstate::{ }; use ctimer::{TimeoutHandler, TimerApi, TimerScheduleError, TimerToken}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId}; use cvm::{decode, execute, ChainTimeInfo, ScriptResult, VMConfig}; use hashdb::AsHashDB; use journaldb; @@ -101,7 +101,7 @@ impl Client { // Sets the correct state root. state_db = scheme.ensure_genesis_state(state_db)?; let mut batch = DBTransaction::new(); - state_db.journal_under(&mut batch, 0, scheme.genesis_header().hash())?; + state_db.journal_under(&mut batch, 0, *scheme.genesis_header().hash())?; db.write(batch).map_err(ClientError::Database)?; } @@ -150,11 +150,11 @@ impl Client { pub fn new_blocks( &self, - imported: &[H256], - invalid: &[H256], - enacted: &[H256], - retracted: &[H256], - sealed: &[H256], + imported: &[BlockHash], + invalid: &[BlockHash], + enacted: &[BlockHash], + retracted: &[BlockHash], + sealed: &[BlockHash], duration: u64, ) { self.notify(|notify| { @@ -171,13 +171,13 @@ impl Client { pub fn new_headers( &self, - imported: &[H256], - invalid: &[H256], - enacted: &[H256], - retracted: &[H256], - sealed: &[H256], + imported: &[BlockHash], + invalid: &[BlockHash], + enacted: &[BlockHash], + retracted: &[BlockHash], + sealed: &[BlockHash], duration: u64, - new_best_proposal: Option, + new_best_proposal: Option, ) { self.notify(|notify| { notify.new_headers( @@ -217,7 +217,7 @@ impl Client { self.importer.miner.update_sealing(self, parent_block, allow_empty_block); } - fn block_hash(chain: &BlockChain, id: &BlockId) -> Option { + fn block_hash(chain: &BlockChain, id: &BlockId) -> Option { match id { BlockId::Hash(hash) => Some(*hash), BlockId::Number(number) => chain.block_hash(*number), @@ -257,7 +257,7 @@ impl Client { /// This is triggered by a message coming from the Tendermint engine when a block is committed. /// See EngineClient::update_best_as_committed() for details. - pub fn update_best_as_committed(&self, block_hash: H256) { + pub fn update_best_as_committed(&self, block_hash: BlockHash) { ctrace!(CLIENT, "Update the best block to the hash({}), as requested", block_hash); let start = Instant::now(); let route = { @@ -557,7 +557,7 @@ impl EngineClient for Client { } /// Submit a seal for a block in the mining queue. - fn submit_seal(&self, block_hash: H256, seal: Vec) { + fn submit_seal(&self, block_hash: BlockHash, seal: Vec) { if self.importer.miner.submit_seal(self, block_hash, seal).is_err() { cwarn!(CLIENT, "Wrong internal seal submission!") } @@ -571,7 +571,7 @@ impl EngineClient for Client { /// Update the best block as the given block hash. /// /// Used in Tendermint, when going to the commit step. - fn update_best_as_committed(&self, block_hash: H256) { + fn update_best_as_committed(&self, block_hash: BlockHash) { ctrace!(ENGINE, "Requesting a best block update (block hash: {})", block_hash); match self.io_channel.lock().send(ClientIoMessage::UpdateBestAsCommitted(block_hash)) { Ok(_) => {} @@ -625,7 +625,7 @@ impl BlockChainTrait for Client { Self::block_hash(&chain, id).and_then(|hash| chain.block(&hash)) } - fn transaction_block(&self, id: &TransactionId) -> Option { + fn transaction_block(&self, id: &TransactionId) -> Option { self.transaction_address(id).map(|addr| addr.block_hash) } @@ -635,7 +635,7 @@ impl BlockChainTrait for Client { } impl ImportBlock for Client { - fn import_block(&self, bytes: Bytes) -> Result { + fn import_block(&self, bytes: Bytes) -> Result { use crate::verification::queue::kind::blocks::Unverified; use crate::verification::queue::kind::BlockLike; @@ -648,7 +648,7 @@ impl ImportBlock for Client { Ok(self.importer.block_queue.import(unverified)?) } - fn import_header(&self, bytes: Bytes) -> Result { + fn import_header(&self, bytes: Bytes) -> Result { let unverified = ::encoded::Header::new(bytes).decode(); { if self.block_chain().is_known_header(&unverified.hash()) { @@ -781,7 +781,7 @@ impl BlockChainClient for Client { Self::block_hash(&chain, id).and_then(|hash| chain.block_details(&hash)).map(|d| d.total_score) } - fn block_hash(&self, id: &BlockId) -> Option { + fn block_hash(&self, id: &BlockId) -> Option { let chain = self.block_chain(); Self::block_hash(&chain, id) } diff --git a/core/src/client/importer.rs b/core/src/client/importer.rs index d4cd457afc..b9bf9479a5 100644 --- a/core/src/client/importer.rs +++ b/core/src/client/importer.rs @@ -21,9 +21,9 @@ use std::time::Instant; use cio::IoChannel; use ctypes::header::Header; +use ctypes::BlockHash; use kvdb::DBTransaction; use parking_lot::{Mutex, MutexGuard}; -use primitives::H256; use rlp::Encodable; use super::{BlockChainTrait, Client, ClientConfig}; @@ -125,7 +125,7 @@ impl Importer { } let imported = imported_blocks.len(); - let invalid_blocks = invalid_blocks.into_iter().collect::>(); + let invalid_blocks = invalid_blocks.into_iter().collect::>(); if !invalid_blocks.is_empty() { self.block_queue.mark_as_bad(&invalid_blocks); @@ -153,8 +153,8 @@ impl Importer { imported } - pub fn calculate_enacted_retracted(&self, import_results: &[ImportRoute]) -> (Vec, Vec) { - fn map_to_vec(map: Vec<(H256, bool)>) -> Vec { + pub fn calculate_enacted_retracted(&self, import_results: &[ImportRoute]) -> (Vec, Vec) { + fn map_to_vec(map: Vec<(BlockHash, bool)>) -> Vec { map.into_iter().map(|(k, _v)| k).collect() } @@ -332,7 +332,7 @@ impl Importer { } let parent_header = client - .block_header(&BlockId::Hash(*header.parent_hash())) + .block_header(&(*header.parent_hash()).into()) .unwrap_or_else(|| panic!("Parent of importing header must exist {:?}", header.parent_hash())) .decode(); if client.block_header(&BlockId::Hash(hash)).is_some() { diff --git a/core/src/client/mod.rs b/core/src/client/mod.rs index d80f5b0301..bdbd712716 100644 --- a/core/src/client/mod.rs +++ b/core/src/client/mod.rs @@ -37,7 +37,7 @@ use cmerkle::Result as TrieResult; use cnetwork::NodeId; use cstate::{AssetScheme, FindActionHandler, OwnedAsset, StateResult, Text, TopLevelState, TopStateView}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; use primitives::{Bytes, H160, H256, U256}; @@ -73,7 +73,7 @@ pub trait BlockChainTrait { fn block(&self, id: &BlockId) -> Option; /// Get the hash of block that contains the transaction, if any. - fn transaction_block(&self, id: &TransactionId) -> Option; + fn transaction_block(&self, id: &TransactionId) -> Option; fn transaction_header(&self, tracker: &H256) -> Option<::encoded::Header>; @@ -101,7 +101,7 @@ pub trait EngineClient: Sync + Send + BlockChainTrait + ImportBlock { fn update_sealing(&self, parent_block: BlockId, allow_empty_block: bool); /// Submit a seal for a block in the mining queue. - fn submit_seal(&self, block_hash: H256, seal: Vec); + fn submit_seal(&self, block_hash: BlockHash, seal: Vec); /// Convert PoW difficulty to target. fn score_to_target(&self, score: &U256) -> U256; @@ -109,7 +109,7 @@ pub trait EngineClient: Sync + Send + BlockChainTrait + ImportBlock { /// Update the best block as the given block hash /// /// Used in Tendermint, when going to the commit step. - fn update_best_as_committed(&self, block_hash: H256); + fn update_best_as_committed(&self, block_hash: BlockHash); fn get_kvdb(&self) -> Arc; } @@ -195,10 +195,10 @@ pub trait Shard { /// Provides methods to import block into blockchain pub trait ImportBlock { /// Import a block into the blockchain. - fn import_block(&self, bytes: Bytes) -> Result; + fn import_block(&self, bytes: Bytes) -> Result; /// Import a header into the blockchain - fn import_header(&self, bytes: Bytes) -> Result; + fn import_header(&self, bytes: Bytes) -> Result; /// Import sealed block. Skips all verifications. fn import_sealed_block(&self, block: &SealedBlock) -> ImportResult; @@ -244,7 +244,7 @@ pub trait BlockChainClient: Sync + Send + AccountData + BlockChainTrait + Import fn block_total_score(&self, id: &BlockId) -> Option; /// Get block hash. - fn block_hash(&self, id: &BlockId) -> Option; + fn block_hash(&self, id: &BlockId) -> Option; /// Get transaction with given hash. fn transaction(&self, id: &TransactionId) -> Option; @@ -259,7 +259,7 @@ pub trait BlockChainClient: Sync + Send + AccountData + BlockChainTrait + Import } /// Result of import block operation. -pub type ImportResult = Result; +pub type ImportResult = Result; /// Provides methods used for sealing new state pub trait BlockProducer { diff --git a/core/src/client/test_client.rs b/core/src/client/test_client.rs index af2791e459..2afaaba3b4 100644 --- a/core/src/client/test_client.rs +++ b/core/src/client/test_client.rs @@ -43,7 +43,7 @@ use cstate::tests::helpers::empty_top_state; use cstate::{FindActionHandler, StateDB, TopLevelState}; use ctimer::{TimeoutHandler, TimerToken}; use ctypes::transaction::{Action, Transaction}; -use ctypes::{BlockNumber, CommonParams, Header as BlockHeader}; +use ctypes::{BlockHash, BlockNumber, CommonParams, Header as BlockHeader}; use cvm::ChainTimeInfo; use journaldb; use kvdb::KeyValueDB; @@ -73,13 +73,13 @@ use client::ConsensusClient; /// Test client. pub struct TestBlockChainClient { /// Blocks. - pub blocks: RwLock>, + pub blocks: RwLock>, /// Mapping of numbers to hashes. - pub numbers: RwLock>, + pub numbers: RwLock>, /// Genesis block hash. - pub genesis_hash: H256, + pub genesis_hash: BlockHash, /// Last block hash. - pub last_hash: RwLock, + pub last_hash: RwLock, /// Last transactions_root pub last_transactions_root: RwLock, /// Extra data do set for each block @@ -203,7 +203,7 @@ impl TestBlockChainClient { } } /// Add a block to test client with designated author. - pub fn add_block_with_author(&self, author: Option
, n: usize, transaction_length: usize) -> H256 { + pub fn add_block_with_author(&self, author: Option
, n: usize, transaction_length: usize) -> BlockHash { let mut header = BlockHeader::new(); header.set_score(From::from(n)); header.set_parent_hash(*self.last_hash.read()); @@ -257,7 +257,7 @@ impl TestBlockChainClient { let block_id = n.into(); let hash = self.block_hash(&block_id).unwrap(); let mut header: BlockHeader = self.block_header(&block_id).unwrap().decode(); - header.set_parent_hash(H256::from(42)); + header.set_parent_hash(H256::from(42).into()); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); @@ -266,13 +266,13 @@ impl TestBlockChainClient { } /// TODO: - pub fn block_hash_delta_minus(&mut self, delta: usize) -> H256 { + pub fn block_hash_delta_minus(&mut self, delta: usize) -> BlockHash { let blocks_read = self.numbers.read(); let index = blocks_read.len() - delta; blocks_read[&index] } - fn block_hash(&self, id: &BlockId) -> Option { + fn block_hash(&self, id: &BlockId) -> Option { match id { BlockId::Hash(hash) => Some(*hash), BlockId::Number(n) => self.numbers.read().get(&(*n as usize)).cloned(), @@ -455,7 +455,7 @@ impl BlockChainTrait for TestBlockChainClient { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).cloned()).map(encoded::Block::new) } - fn transaction_block(&self, _id: &TransactionId) -> Option { + fn transaction_block(&self, _id: &TransactionId) -> Option { None // Simple default. } @@ -465,7 +465,7 @@ impl BlockChainTrait for TestBlockChainClient { } impl ImportBlock for TestBlockChainClient { - fn import_block(&self, b: Bytes) -> Result { + fn import_block(&self, b: Bytes) -> Result { let header = Rlp::new(&b).val_at::(0); let h = header.hash(); let number: usize = header.number() as usize; @@ -487,7 +487,8 @@ impl ImportBlock for TestBlockChainClient { *score += *header.score(); } mem::replace(&mut *self.last_hash.write(), h); - mem::replace(&mut *self.last_transactions_root.write(), h); + // FIXME: The transactions root is not related to block hash. + mem::replace(&mut *self.last_transactions_root.write(), *h); self.blocks.write().insert(h, b); self.numbers.write().insert(number, h); let mut parent_hash = *header.parent_hash(); @@ -505,12 +506,12 @@ impl ImportBlock for TestBlockChainClient { Ok(h) } - fn import_header(&self, _bytes: Bytes) -> Result { + fn import_header(&self, _bytes: Bytes) -> Result { unimplemented!() } fn import_sealed_block(&self, _block: &SealedBlock) -> ImportResult { - Ok(H256::default()) + Ok(H256::default().into()) } fn set_min_timer(&self) {} @@ -584,7 +585,7 @@ impl BlockChainClient for TestBlockChainClient { Some(U256::zero()) } - fn block_hash(&self, id: &BlockId) -> Option { + fn block_hash(&self, id: &BlockId) -> Option { Self::block_hash(self, id) } @@ -626,7 +627,7 @@ impl super::EngineClient for TestBlockChainClient { self.miner.update_sealing(self, parent_block, allow_empty_block) } - fn submit_seal(&self, block_hash: H256, seal: Vec) { + fn submit_seal(&self, block_hash: BlockHash, seal: Vec) { if self.miner.submit_seal(self, block_hash, seal).is_err() { cwarn!(CLIENT, "Wrong internal seal submission!") } @@ -636,7 +637,7 @@ impl super::EngineClient for TestBlockChainClient { U256::zero() } - fn update_best_as_committed(&self, _block_hash: H256) {} + fn update_best_as_committed(&self, _block_hash: BlockHash) {} fn get_kvdb(&self) -> Arc { let db = kvdb_memorydb::create(NUM_COLUMNS.unwrap_or(0)); diff --git a/core/src/consensus/blake_pow/mod.rs b/core/src/consensus/blake_pow/mod.rs index 52ef3056d1..0f20eb2455 100644 --- a/core/src/consensus/blake_pow/mod.rs +++ b/core/src/consensus/blake_pow/mod.rs @@ -148,7 +148,7 @@ impl ConsensusEngine for BlakePoW { if header.score() != &expected_score { return Err(From::from(BlockError::InvalidScore(Mismatch { expected: expected_score, - found: U256::from(header.hash()), + found: U256::from(*header.hash()), }))) } diff --git a/core/src/consensus/cuckoo/mod.rs b/core/src/consensus/cuckoo/mod.rs index d2c49f04e4..14bcc29780 100644 --- a/core/src/consensus/cuckoo/mod.rs +++ b/core/src/consensus/cuckoo/mod.rs @@ -158,7 +158,7 @@ impl ConsensusEngine for Cuckoo { if header.score() != &expected_score { return Err(From::from(BlockError::InvalidScore(Mismatch { expected: expected_score, - found: U256::from(header.hash()), + found: U256::from(*header.hash()), }))) } diff --git a/core/src/consensus/mod.rs b/core/src/consensus/mod.rs index bc8babf156..8ba08b2069 100644 --- a/core/src/consensus/mod.rs +++ b/core/src/consensus/mod.rs @@ -45,8 +45,8 @@ use cstate::ActionHandler; use ctypes::errors::SyntaxError; use ctypes::transaction::Action; use ctypes::util::unexpected::{Mismatch, OutOfBounds}; -use ctypes::{CommonParams, Header}; -use primitives::{Bytes, H256, U256}; +use ctypes::{BlockHash, CommonParams, Header}; +use primitives::{Bytes, U256}; use self::bit_set::BitSet; use crate::account_provider::AccountProvider; @@ -262,7 +262,7 @@ pub trait ConsensusEngine: Sync + Send { fn register_chain_notify(&self, _: &Client) {} - fn get_best_block_from_best_proposal_header(&self, header: &HeaderView) -> H256 { + fn get_best_block_from_best_proposal_header(&self, header: &HeaderView) -> BlockHash { header.hash() } @@ -271,10 +271,10 @@ pub trait ConsensusEngine: Sync + Send { /// Only the descendant of the current best block could be the next best block in Tendermint consensus. fn can_change_canon_chain( &self, - _new_block_hash: H256, - _parent_hash_of_new_header: H256, - _grandparent_hash_of_new_header: H256, - _previous_best_hash: H256, + _new_block_hash: BlockHash, + _parent_hash_of_new_header: BlockHash, + _grandparent_hash_of_new_header: BlockHash, + _previous_best_hash: BlockHash, ) -> bool { true } diff --git a/core/src/consensus/simple_poa/mod.rs b/core/src/consensus/simple_poa/mod.rs index d2a2633ef8..a06109ca33 100644 --- a/core/src/consensus/simple_poa/mod.rs +++ b/core/src/consensus/simple_poa/mod.rs @@ -21,6 +21,7 @@ use std::sync::{Arc, Weak}; use ckey::{public_to_address, recover, Address, Signature}; use ctypes::{CommonParams, Header}; use parking_lot::RwLock; +use primitives::H256; use self::params::SimplePoAParams; use super::signer::EngineSigner; @@ -149,7 +150,7 @@ impl ConsensusEngine for SimplePoA { fn possible_authors(&self, _block_number: Option) -> Result>, EngineError> { // TODO: It works because the round robin validator doesn't use the parent hash. - let parent = 0.into(); + let parent = H256::from(0).into(); Ok(Some(self.validators.addresses(&parent))) } } diff --git a/core/src/consensus/stake/actions.rs b/core/src/consensus/stake/actions.rs index 013bda7180..7290c8c54a 100644 --- a/core/src/consensus/stake/actions.rs +++ b/core/src/consensus/stake/actions.rs @@ -361,6 +361,7 @@ mod tests { use ckey::sign_schnorr; use client::TestBlockChainClient; use consensus::{ConsensusMessage, DynamicValidator, Step, VoteOn, VoteStep}; + use ctypes::BlockHash; use rlp::rlp_encode_and_decode_test; #[test] @@ -392,7 +393,7 @@ mod tests { pub height: u64, pub view: u64, pub step: Step, - pub block_hash: Option, + pub block_hash: Option, pub signer_index: usize, } @@ -404,7 +405,7 @@ mod tests { ) -> ConsensusMessage where F: Fn(VoteStep) -> VoteStep, - G: Fn(Option) -> Option, { + G: Fn(Option) -> Option, { let ConsensusMessageInfo { height, view, @@ -441,7 +442,7 @@ mod tests { ) -> Result<(), SyntaxError> where F: Fn(VoteStep) -> VoteStep, - G: Fn(Option) -> Option, { + G: Fn(Option) -> Option, { let mut test_client = TestBlockChainClient::default(); test_client.add_blocks(10, 1); test_client.set_random_validators(10); @@ -475,7 +476,7 @@ mod tests { height: 2, view: 0, step: Step::Precommit, - block_hash: Some(H256::random()), + block_hash: Some(H256::random().into()), signer_index: 0, }, &|v| v, @@ -486,7 +487,7 @@ mod tests { #[test] fn double_vote_verify_same_message() { - let block_hash = Some(H256::random()); + let block_hash = Some(H256::random().into()); let result = double_vote_verification_result( ConsensusMessageInfo { height: 3, @@ -511,7 +512,7 @@ mod tests { #[test] fn double_vote_verify_different_height() { - let block_hash = Some(H256::random()); + let block_hash = Some(H256::random().into()); let result = double_vote_verification_result( ConsensusMessageInfo { height: 3, @@ -549,7 +550,7 @@ mod tests { height: 2, view: 0, step: Step::Precommit, - block_hash: Some(H256::random()), + block_hash: Some(H256::random().into()), signer_index: 0, }, &|v| v, @@ -564,10 +565,10 @@ mod tests { #[test] fn double_vote_verify_different_message_and_signer() { - let hash1 = Some(H256::random()); - let mut hash2 = Some(H256::random()); + let hash1 = Some(H256::random().into()); + let mut hash2 = Some(H256::random().into()); while hash1 == hash2 { - hash2 = Some(H256::random()); + hash2 = Some(H256::random().into()); } let result = double_vote_verification_result( ConsensusMessageInfo { @@ -613,7 +614,7 @@ mod tests { height: 2, view: 0, step: Step::Precommit, - block_hash: Some(H256::random()), + block_hash: Some(H256::random().into()), signer_index: 0, }, &vote_step_twister, @@ -625,13 +626,13 @@ mod tests { #[test] fn double_vote_verify_strange_sig2() { - let block_hash_twister = |original: Option| { + let block_hash_twister = |original: Option| { original.map(|hash| { let mut twisted = H256::random(); - while twisted == hash { + while twisted == *hash { twisted = H256::random(); } - twisted + BlockHash::from(twisted) }) }; let result = double_vote_verification_result( @@ -646,7 +647,7 @@ mod tests { height: 2, view: 0, step: Step::Precommit, - block_hash: Some(H256::random()), + block_hash: Some(H256::random().into()), signer_index: 0, }, &|v| v, diff --git a/core/src/consensus/tendermint/backup.rs b/core/src/consensus/tendermint/backup.rs index 1f8c45b5c7..9dacf0a5dd 100644 --- a/core/src/consensus/tendermint/backup.rs +++ b/core/src/consensus/tendermint/backup.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use ctypes::BlockHash; use kvdb::{DBTransaction, KeyValueDB}; -use primitives::H256; use super::message::ConsensusMessage; use super::types::{Height, Step, View}; @@ -39,7 +39,7 @@ pub struct BackupDataV0 { pub view: View, pub step: Step, pub votes: Vec, - pub proposal: Option, + pub proposal: Option, pub last_confirmed_view: View, } @@ -48,7 +48,7 @@ pub struct BackupDataV1 { pub view: View, pub step: Step, pub votes: Vec, - pub proposal: Option, + pub proposal: Option, pub finalized_view_of_previous_block: View, pub finalized_view_of_current_block: Option, } @@ -86,7 +86,7 @@ pub fn restore(db: &dyn KeyValueDB) -> Option { load_v1(db) } -fn find_proposal(votes: &[ConsensusMessage], height: Height, view: View) -> Option { +fn find_proposal(votes: &[ConsensusMessage], height: Height, view: View) -> Option { votes .iter() .rev() diff --git a/core/src/consensus/tendermint/chain_notify.rs b/core/src/consensus/tendermint/chain_notify.rs index 4d631ef632..b368510b5b 100644 --- a/core/src/consensus/tendermint/chain_notify.rs +++ b/core/src/consensus/tendermint/chain_notify.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . use crossbeam_channel as crossbeam; -use primitives::H256; +use ctypes::BlockHash; use super::worker; use crate::client::ChainNotify; @@ -36,11 +36,11 @@ impl ChainNotify for TendermintChainNotify { /// fires when chain has new blocks. fn new_blocks( &self, - imported: Vec, - _invalid: Vec, - enacted: Vec, - _retracted: Vec, - _sealed: Vec, + imported: Vec, + _invalid: Vec, + enacted: Vec, + _retracted: Vec, + _sealed: Vec, _duration: u64, ) { self.inner diff --git a/core/src/consensus/tendermint/engine.rs b/core/src/consensus/tendermint/engine.rs index 63943bf72a..3261e087a5 100644 --- a/core/src/consensus/tendermint/engine.rs +++ b/core/src/consensus/tendermint/engine.rs @@ -25,9 +25,8 @@ use ckey::{public_to_address, Address}; use cnetwork::NetworkService; use crossbeam_channel as crossbeam; use cstate::{ActionHandler, TopStateView}; -use ctypes::{BlockNumber, CommonParams, Header}; +use ctypes::{BlockHash, BlockNumber, CommonParams, Header}; use num_rational::Ratio; -use primitives::H256; use super::super::stake; use super::super::{ConsensusEngine, EngineError, Seal}; @@ -304,17 +303,17 @@ impl ConsensusEngine for Tendermint { client.add_notify(Arc::downgrade(&self.chain_notify) as Weak); } - fn get_best_block_from_best_proposal_header(&self, header: &HeaderView) -> H256 { + fn get_best_block_from_best_proposal_header(&self, header: &HeaderView) -> BlockHash { header.parent_hash() } fn can_change_canon_chain( &self, - _new_header_hash: H256, - parent_hash_of_new_header: H256, - grandparent_hash_of_new_header: H256, - prev_best_hash: H256, + _new_header_hash: BlockHash, + parent_hash_of_new_header: BlockHash, + grandparent_hash_of_new_header: BlockHash, + prev_best_hash: BlockHash, ) -> bool { parent_hash_of_new_header == prev_best_hash || grandparent_hash_of_new_header == prev_best_hash } diff --git a/core/src/consensus/tendermint/message.rs b/core/src/consensus/tendermint/message.rs index 65cd5dfbcc..89b49f97f2 100644 --- a/core/src/consensus/tendermint/message.rs +++ b/core/src/consensus/tendermint/message.rs @@ -18,12 +18,13 @@ use std::cmp; use ccrypto::blake256; use ckey::{verify_schnorr, Error as KeyError, Public, SchnorrSignature}; +use ctypes::BlockHash; use primitives::{Bytes, H256}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use snap; use super::super::BitSet; -use super::{BlockHash, Height, Step, View}; +use super::{Height, Step, View}; /// Complete step of the consensus process. #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RlpDecodable, RlpEncodable)] @@ -89,7 +90,7 @@ pub enum TendermintMessage { }, StepState { vote_step: VoteStep, - proposal: Option, + proposal: Option, lock_view: Option, known_votes: BitSet, }, @@ -337,7 +338,7 @@ impl ConsensusMessage { self.signer_index } - pub fn block_hash(&self) -> Option { + pub fn block_hash(&self) -> Option { self.on.block_hash } @@ -434,9 +435,9 @@ mod tests { signer_index: 0x1234, on: VoteOn { step: VoteStep::new(2, 3, Step::Commit), - block_hash: Some(H256::from( - "07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050" - )), + block_hash: Some( + H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050").into() + ), }, }, ConsensusMessage { @@ -444,9 +445,9 @@ mod tests { signer_index: 0x1235, on: VoteOn { step: VoteStep::new(2, 3, Step::Commit), - block_hash: Some(H256::from( - "07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050" - )), + block_hash: Some( + H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050").into() + ), }, } ] @@ -466,7 +467,7 @@ mod tests { signer_index: 0x1234, on: VoteOn { step: VoteStep::new(2, 3, Step::Commit), - block_hash: Some(H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050")), + block_hash: Some(H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050").into()), }, }; rlp_encode_and_decode_test!(message); @@ -479,7 +480,7 @@ mod tests { let step = Step::Commit; let signature = SchnorrSignature::random(); let signer_index = 0x1234; - let block_hash = Some(H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050")); + let block_hash = Some(H256::from("07feab4c39250abf60b77d7589a5b61fdf409bd837e936376381d19db1e1f050").into()); let consensus_message = ConsensusMessage { signature, signer_index, diff --git a/core/src/consensus/tendermint/mod.rs b/core/src/consensus/tendermint/mod.rs index a5ca75668d..4e9ae0cd3a 100644 --- a/core/src/consensus/tendermint/mod.rs +++ b/core/src/consensus/tendermint/mod.rs @@ -33,7 +33,6 @@ use crossbeam_channel as crossbeam; use cstate::ActionHandler; use ctimer::TimerToken; use parking_lot::RwLock; -use primitives::H256; use self::chain_notify::TendermintChainNotify; pub use self::message::{ConsensusMessage, VoteOn, VoteStep}; @@ -54,8 +53,6 @@ const ENGINE_TIMEOUT_BROADCAST_STEP_STATE: TimerToken = 21; /// Unit: second const ENGINE_TIMEOUT_BROADCAT_STEP_STATE_INTERVAL: u64 = 1; -pub type BlockHash = H256; - /// ConsensusEngine using `Tendermint` consensus algorithm pub struct Tendermint { client: RwLock>>, diff --git a/core/src/consensus/tendermint/network.rs b/core/src/consensus/tendermint/network.rs index d1746d51fa..0dffd9495c 100644 --- a/core/src/consensus/tendermint/network.rs +++ b/core/src/consensus/tendermint/network.rs @@ -24,7 +24,8 @@ use ckey::SchnorrSignature; use cnetwork::{Api, NetworkExtension, NodeId}; use crossbeam_channel as crossbeam; use ctimer::TimerToken; -use primitives::{Bytes, H256}; +use ctypes::BlockHash; +use primitives::Bytes; use rand::prelude::SliceRandom; use rand::thread_rng; use rlp::{Encodable, UntrustedRlp}; @@ -69,7 +70,13 @@ impl TendermintExtension { } } - fn update_peer_state(&mut self, token: &NodeId, vote_step: VoteStep, proposal: Option, messages: BitSet) { + fn update_peer_state( + &mut self, + token: &NodeId, + vote_step: VoteStep, + proposal: Option, + messages: BitSet, + ) { let peer_state = match self.peers.get_mut(token) { Some(peer_state) => peer_state, // update_peer_state could be called after the peer is disconnected @@ -104,7 +111,13 @@ impl TendermintExtension { self.api.send(token, message); } - fn broadcast_state(&self, vote_step: VoteStep, proposal: Option, lock_view: Option, votes: BitSet) { + fn broadcast_state( + &self, + vote_step: VoteStep, + proposal: Option, + lock_view: Option, + votes: BitSet, + ) { ctrace!(ENGINE, "Broadcast state {:?} {:?} {:?}", vote_step, proposal, votes); let tokens = self.select_random_peers(); let message = Arc::new( @@ -456,7 +469,7 @@ pub enum Event { }, BroadcastState { vote_step: VoteStep, - proposal: Option, + proposal: Option, lock_view: Option, votes: BitSet, }, diff --git a/core/src/consensus/tendermint/types.rs b/core/src/consensus/tendermint/types.rs index 373c9e7d33..83e4524afd 100644 --- a/core/src/consensus/tendermint/types.rs +++ b/core/src/consensus/tendermint/types.rs @@ -17,13 +17,13 @@ use std::fmt; use ckey::SchnorrSignature; -use primitives::{Bytes, H256}; +use ctypes::BlockHash; +use primitives::Bytes; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use super::super::BitSet; use super::message::VoteStep; use crate::block::{IsBlock, SealedBlock}; -use consensus::tendermint::BlockHash; pub type Height = u64; pub type View = u64; @@ -32,7 +32,7 @@ pub type View = u64; pub enum TendermintState { Propose, ProposeWaitBlockGeneration { - parent_hash: H256, + parent_hash: BlockHash, }, ProposeWaitImported { block: Box, @@ -44,11 +44,11 @@ pub enum TendermintState { Precommit, Commit { view: View, - block_hash: H256, + block_hash: BlockHash, }, CommitTimedout { view: View, - block_hash: H256, + block_hash: BlockHash, }, } @@ -199,7 +199,7 @@ impl Encodable for Step { pub struct PeerState { pub vote_step: VoteStep, - pub proposal: Option, + pub proposal: Option, pub messages: BitSet, } @@ -270,12 +270,12 @@ impl<'a> TendermintSealView<'a> { #[derive(Copy, Clone)] pub enum TwoThirdsMajority { Empty, - Lock(View, H256), + Lock(View, BlockHash), Unlock(View), } impl TwoThirdsMajority { - pub fn from_message(view: View, block_hash: Option) -> Self { + pub fn from_message(view: View, block_hash: Option) -> Self { match block_hash { Some(block_hash) => TwoThirdsMajority::Lock(view, block_hash), None => TwoThirdsMajority::Unlock(view), @@ -290,7 +290,7 @@ impl TwoThirdsMajority { } } - pub fn block_hash(&self) -> Option { + pub fn block_hash(&self) -> Option { match self { TwoThirdsMajority::Empty => None, TwoThirdsMajority::Lock(_, block_hash) => Some(*block_hash), @@ -301,21 +301,21 @@ impl TwoThirdsMajority { #[derive(Debug, PartialEq)] pub enum Proposal { - ProposalReceived(H256, Bytes, SchnorrSignature), - ProposalImported(H256), + ProposalReceived(BlockHash, Bytes, SchnorrSignature), + ProposalImported(BlockHash), None, } impl Proposal { - pub fn new_received(hash: H256, block: Bytes, signature: SchnorrSignature) -> Self { + pub fn new_received(hash: BlockHash, block: Bytes, signature: SchnorrSignature) -> Self { Proposal::ProposalReceived(hash, block, signature) } - pub fn new_imported(hash: H256) -> Self { + pub fn new_imported(hash: BlockHash) -> Self { Proposal::ProposalImported(hash) } - pub fn block_hash(&self) -> Option { + pub fn block_hash(&self) -> Option { match self { Proposal::ProposalReceived(hash, ..) => Some(*hash), Proposal::ProposalImported(hash) => Some(*hash), @@ -323,7 +323,7 @@ impl Proposal { } } - pub fn imported_block_hash(&self) -> Option { + pub fn imported_block_hash(&self) -> Option { match self { Proposal::ProposalReceived(..) => None, Proposal::ProposalImported(hash) => Some(*hash), diff --git a/core/src/consensus/tendermint/vote_collector.rs b/core/src/consensus/tendermint/vote_collector.rs index d93fef2e86..f96216fa66 100644 --- a/core/src/consensus/tendermint/vote_collector.rs +++ b/core/src/consensus/tendermint/vote_collector.rs @@ -18,7 +18,7 @@ use std::collections::{BTreeMap, HashMap}; use std::iter::Iterator; use ckey::SchnorrSignature; -use primitives::H256; +use ctypes::BlockHash; use rlp::{Encodable, RlpStream}; use super::stake::Action; @@ -34,7 +34,7 @@ pub struct VoteCollector { #[derive(Debug, Default)] struct StepCollector { voted: HashMap, - block_votes: HashMap, BTreeMap>, + block_votes: HashMap, BTreeMap>, messages: Vec, } @@ -87,7 +87,7 @@ impl StepCollector { } /// Count all votes for the given block hash at this round. - fn count_block(&self, block_hash: &Option) -> BitSet { + fn count_block(&self, block_hash: &Option) -> BitSet { let mut result = BitSet::new(); if let Some(votes) = self.block_votes.get(block_hash) { for index in votes.keys() { @@ -157,7 +157,7 @@ impl VoteCollector { pub fn round_signatures_and_indices( &self, round: &VoteStep, - block_hash: &H256, + block_hash: &BlockHash, ) -> (Vec, Vec) { self.votes .get(round) @@ -171,7 +171,7 @@ impl VoteCollector { /// Returns the first signature and the index of its signer for a given round and hash if exists. - pub fn round_signature(&self, round: &VoteStep, block_hash: &H256) -> Option { + pub fn round_signature(&self, round: &VoteStep, block_hash: &BlockHash) -> Option { self.votes .get(round) .and_then(|c| c.block_votes.get(&Some(*block_hash))) @@ -187,7 +187,7 @@ impl VoteCollector { } } - pub fn block_round_votes(&self, round: &VoteStep, block_hash: &Option) -> BitSet { + pub fn block_round_votes(&self, round: &VoteStep, block_hash: &Option) -> BitSet { if let Some(votes) = self.votes.get(round) { votes.count_block(block_hash) } else { @@ -204,14 +204,14 @@ impl VoteCollector { } } - pub fn get_block_hashes(&self, round: &VoteStep) -> Vec { + pub fn get_block_hashes(&self, round: &VoteStep) -> Vec { self.votes .get(round) .map(|c| c.block_votes.keys().cloned().filter_map(|x| x).collect()) .unwrap_or_else(Vec::new) } - pub fn has_votes_for(&self, round: &VoteStep, block_hash: H256) -> bool { + pub fn has_votes_for(&self, round: &VoteStep, block_hash: BlockHash) -> bool { let votes = self .votes .get(round) diff --git a/core/src/consensus/tendermint/vote_regression_checker.rs b/core/src/consensus/tendermint/vote_regression_checker.rs index 5538c9ea45..c9aea69563 100644 --- a/core/src/consensus/tendermint/vote_regression_checker.rs +++ b/core/src/consensus/tendermint/vote_regression_checker.rs @@ -49,7 +49,7 @@ mod tests { let mut checker = VoteRegressionChecker::new(); let random_step = VoteStep::new(100, 10, Step::Prevote); - let random_hash = Some(H256::random()); + let random_hash = Some(H256::random().into()); assert!(checker.check(&VoteOn { step: random_step, block_hash: random_hash @@ -62,7 +62,7 @@ mod tests { let mut checker = VoteRegressionChecker::new(); let random_commit_step = VoteStep::new(100, 10, Step::Commit); - let random_hash = Some(H256::random()); + let random_hash = Some(H256::random().into()); checker.check(&VoteOn { step: random_commit_step, block_hash: random_hash, @@ -75,12 +75,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(checker.check(&VoteOn { step: VoteStep::new(101, 10, Step::Prevote), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -90,12 +90,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(!checker.check(&VoteOn { step: VoteStep::new(99, 10, Step::Prevote), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -105,12 +105,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(checker.check(&VoteOn { step: VoteStep::new(100, 11, Step::Prevote), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -120,12 +120,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(!checker.check(&VoteOn { step: VoteStep::new(100, 9, Step::Prevote), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -135,12 +135,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Precommit), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -150,12 +150,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(!checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Propose), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } @@ -163,7 +163,7 @@ mod tests { fn test_allow_same_hash() { let mut checker = VoteRegressionChecker::new(); - let block_hash = Some(H256::random()); + let block_hash = Some(H256::random().into()); checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), block_hash, @@ -181,12 +181,12 @@ mod tests { checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(1)), + block_hash: Some(H256::from(1).into()), }); assert!(!checker.check(&VoteOn { step: VoteStep::new(100, 10, Step::Prevote), - block_hash: Some(H256::from(2)) + block_hash: Some(H256::from(2).into()) })) } } diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index c881cc443e..d2b7da7ef2 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -26,8 +26,8 @@ use cnetwork::{EventSender, NodeId}; use crossbeam_channel as crossbeam; use ctypes::transaction::{Action, Transaction}; use ctypes::util::unexpected::Mismatch; -use ctypes::{BlockNumber, Header}; -use primitives::{u256_from_u128, Bytes, H256, U256}; +use ctypes::{BlockHash, BlockNumber, Header}; +use primitives::{u256_from_u128, Bytes, U256}; use rlp::{Encodable, UntrustedRlp}; use super::super::BitSet; @@ -40,8 +40,7 @@ use super::types::{Height, Proposal, Step, TendermintSealView, TendermintState, use super::vote_collector::{DoubleVote, VoteCollector}; use super::vote_regression_checker::VoteRegressionChecker; use super::{ - BlockHash, ENGINE_TIMEOUT_BROADCAST_STEP_STATE, ENGINE_TIMEOUT_EMPTY_PROPOSAL, ENGINE_TIMEOUT_TOKEN_NONCE_BASE, - SEAL_FIELDS, + ENGINE_TIMEOUT_BROADCAST_STEP_STATE, ENGINE_TIMEOUT_EMPTY_PROPOSAL, ENGINE_TIMEOUT_TOKEN_NONCE_BASE, SEAL_FIELDS, }; use crate::account_provider::AccountProvider; use crate::block::*; @@ -102,12 +101,12 @@ struct Worker { pub enum Event { NewBlocks { - imported: Vec, - enacted: Vec, + imported: Vec, + enacted: Vec, }, GenerateSeal { block_number: Height, - parent_hash: H256, + parent_hash: BlockHash, result: crossbeam::Sender, }, ProposalGenerated(Box), @@ -130,7 +129,7 @@ pub enum Event { }, IsProposal { block_number: BlockNumber, - block_hash: H256, + block_hash: BlockHash, result: crossbeam::Sender, }, SetSigner { @@ -147,7 +146,7 @@ pub enum Event { StepState { token: NodeId, vote_step: VoteStep, - proposal: Option, + proposal: Option, lock_view: Option, known_votes: Box, result: crossbeam::Sender, @@ -384,14 +383,14 @@ impl Worker { } /// Get previous block hash to determine validator set - fn prev_block_hash(&self) -> H256 { + fn prev_block_hash(&self) -> BlockHash { self.prev_block_header_of_height(self.height) .expect("Height is increased when previous block is imported") .hash() } /// Get the index of the proposer of a block to check the new proposer is valid. - fn block_proposer_idx(&self, block_hash: H256) -> Option { + fn block_proposer_idx(&self, block_hash: BlockHash) -> Option { self.client().block_header(&BlockId::Hash(block_hash)).map(|header| { let proposer = header.author(); let parent = if header.number() == 0 { @@ -445,7 +444,7 @@ impl Worker { } /// Find the designated for the given view. - fn view_proposer(&self, prev_block_hash: &H256, view: View) -> Option
{ + fn view_proposer(&self, prev_block_hash: &BlockHash, view: View) -> Option
{ self.validators.next_block_proposer(prev_block_hash, view) } @@ -507,7 +506,7 @@ impl Worker { /// Check if address is a proposer for given view. fn check_view_proposer( &self, - parent: &H256, + parent: &BlockHash, height: Height, view: View, address: &Address, @@ -526,7 +525,7 @@ impl Worker { } /// Check if current signer is the current proposer. - fn is_signer_proposer(&self, bh: &H256) -> bool { + fn is_signer_proposer(&self, bh: &BlockHash) -> bool { self.view_proposer(bh, self.view).map_or(false, |proposer| self.signer.is_address(&proposer)) } @@ -534,7 +533,7 @@ impl Worker { message.on.step.is_step(self.height, self.view, self.step.to_step()) } - fn is_authority(&self, prev_hash: &H256, address: &Address) -> bool { + fn is_authority(&self, prev_hash: &BlockHash, address: &Address) -> bool { self.validators.contains_address(&prev_hash, address) } @@ -558,7 +557,7 @@ impl Worker { self.validators.check_enough_votes(&parent_hash, &aligned_votes).is_ok() } - fn has_enough_precommit_votes(&self, block_hash: H256) -> bool { + fn has_enough_precommit_votes(&self, block_hash: BlockHash) -> bool { let vote_step = VoteStep::new(self.height, self.view, Step::Precommit); let votes = self.votes.block_round_votes(&vote_step, &Some(block_hash)); self.validators.check_enough_votes(&self.prev_block_hash(), &votes).is_ok() @@ -573,7 +572,13 @@ impl Worker { .unwrap(); } - fn broadcast_state(&self, vote_step: VoteStep, proposal: Option, lock_view: Option, votes: &BitSet) { + fn broadcast_state( + &self, + vote_step: VoteStep, + proposal: Option, + lock_view: Option, + votes: &BitSet, + ) { self.extension .send(network::Event::BroadcastState { vote_step, @@ -602,7 +607,7 @@ impl Worker { .unwrap(); } - fn update_sealing(&self, parent_block_hash: H256) { + fn update_sealing(&self, parent_block_hash: BlockHash) { self.client().update_sealing(BlockId::Hash(parent_block_hash), true); } @@ -815,7 +820,11 @@ impl Worker { } } - fn locked_proposal_block(&self, locked_view: View, locked_proposal_hash: H256) -> Result { + fn locked_proposal_block( + &self, + locked_view: View, + locked_proposal_hash: BlockHash, + ) -> Result { let vote_step = VoteStep::new(self.height, locked_view, Step::Propose); let received_locked_block = self.votes.has_votes_for(&vote_step, locked_proposal_hash); @@ -1058,7 +1067,7 @@ impl Worker { SEAL_FIELDS } - fn generate_seal(&self, height: Height, parent_hash: H256) -> Seal { + fn generate_seal(&self, height: Height, parent_hash: BlockHash) -> Seal { // Block is received from other nodes while creating a block if height < self.height { return Seal::None @@ -1466,7 +1475,7 @@ impl Worker { } } - fn is_proposal(&self, block_number: BlockNumber, block_hash: H256) -> bool { + fn is_proposal(&self, block_number: BlockNumber, block_hash: BlockHash) -> bool { if self.height > block_number { return false } @@ -1595,7 +1604,7 @@ impl Worker { self.signer.public().and_then(|public| self.validators.get_index(&parent, public)) } - fn new_blocks(&mut self, imported: Vec, enacted: Vec) { + fn new_blocks(&mut self, imported: Vec, enacted: Vec) { let c = match self.client.upgrade() { Some(client) => client, None => { @@ -1825,7 +1834,7 @@ impl Worker { &self, token: &NodeId, peer_vote_step: VoteStep, - peer_proposal: Option, + peer_proposal: Option, peer_lock_view: Option, peer_known_votes: BitSet, result: crossbeam::Sender, diff --git a/core/src/consensus/validator_set/dynamic_validator.rs b/core/src/consensus/validator_set/dynamic_validator.rs index b9b95a09c4..c440295365 100644 --- a/core/src/consensus/validator_set/dynamic_validator.rs +++ b/core/src/consensus/validator_set/dynamic_validator.rs @@ -18,8 +18,8 @@ use std::sync::{Arc, Weak}; use ckey::{public_to_address, Address, Public}; use ctypes::util::unexpected::OutOfBounds; +use ctypes::BlockHash; use parking_lot::RwLock; -use primitives::H256; use super::{RoundRobinValidator, ValidatorSet}; use crate::client::ConsensusClient; @@ -41,7 +41,7 @@ impl DynamicValidator { } } - fn validators(&self, parent: H256) -> Option> { + fn validators(&self, parent: BlockHash) -> Option> { let client: Arc = self.client.read().as_ref().and_then(Weak::upgrade).expect("Client is not initialized"); let block_id = parent.into(); @@ -64,11 +64,11 @@ impl DynamicValidator { } } - fn validators_pubkey(&self, parent: H256) -> Option> { + fn validators_pubkey(&self, parent: BlockHash) -> Option> { self.validators(parent).map(|validators| validators.into_iter().map(|val| *val.pubkey()).collect()) } - pub fn proposer_index(&self, parent: H256, prev_proposer_index: usize, proposed_view: usize) -> usize { + pub fn proposer_index(&self, parent: BlockHash, prev_proposer_index: usize, proposed_view: usize) -> usize { if let Some(validators) = self.validators(parent) { let num_validators = validators.len(); proposed_view % num_validators @@ -80,7 +80,7 @@ impl DynamicValidator { } impl ValidatorSet for DynamicValidator { - fn contains(&self, parent: &H256, public: &Public) -> bool { + fn contains(&self, parent: &BlockHash, public: &Public) -> bool { if let Some(validators) = self.validators_pubkey(*parent) { validators.into_iter().any(|pubkey| pubkey == *public) } else { @@ -88,7 +88,7 @@ impl ValidatorSet for DynamicValidator { } } - fn contains_address(&self, parent: &H256, address: &Address) -> bool { + fn contains_address(&self, parent: &BlockHash, address: &Address) -> bool { if let Some(validators) = self.validators_pubkey(*parent) { validators.into_iter().any(|pubkey| public_to_address(&pubkey) == *address) } else { @@ -96,7 +96,7 @@ impl ValidatorSet for DynamicValidator { } } - fn get(&self, parent: &H256, index: usize) -> Public { + fn get(&self, parent: &BlockHash, index: usize) -> Public { if let Some(validators) = self.validators_pubkey(*parent) { let n_validators = validators.len(); *validators.get(index % n_validators).unwrap() @@ -105,7 +105,7 @@ impl ValidatorSet for DynamicValidator { } } - fn get_index(&self, parent: &H256, public: &Public) -> Option { + fn get_index(&self, parent: &BlockHash, public: &Public) -> Option { if let Some(validators) = self.validators_pubkey(*parent) { validators.into_iter().enumerate().find(|(_index, pubkey)| pubkey == public).map(|(index, _)| index) } else { @@ -113,7 +113,7 @@ impl ValidatorSet for DynamicValidator { } } - fn get_index_by_address(&self, parent: &H256, address: &Address) -> Option { + fn get_index_by_address(&self, parent: &BlockHash, address: &Address) -> Option { if let Some(validators) = self.validators_pubkey(*parent) { validators .into_iter() @@ -125,7 +125,7 @@ impl ValidatorSet for DynamicValidator { } } - fn next_block_proposer(&self, parent: &H256, view: u64) -> Option
{ + fn next_block_proposer(&self, parent: &BlockHash, view: u64) -> Option
{ if let Some(validators) = self.validators_pubkey(*parent) { let n_validators = validators.len(); let index = view as usize % n_validators; @@ -135,7 +135,7 @@ impl ValidatorSet for DynamicValidator { } } - fn count(&self, parent: &H256) -> usize { + fn count(&self, parent: &BlockHash) -> usize { if let Some(validators) = self.validators(*parent) { validators.len() } else { @@ -143,7 +143,7 @@ impl ValidatorSet for DynamicValidator { } } - fn check_enough_votes(&self, parent: &H256, votes: &BitSet) -> Result<(), EngineError> { + fn check_enough_votes(&self, parent: &BlockHash, votes: &BitSet) -> Result<(), EngineError> { if let Some(validators) = self.validators(*parent) { let mut voted_delegation = 0u64; let n_validators = validators.len(); @@ -181,7 +181,7 @@ impl ValidatorSet for DynamicValidator { *client_lock = Some(client); } - fn addresses(&self, parent: &H256) -> Vec
{ + fn addresses(&self, parent: &BlockHash) -> Vec
{ if let Some(validators) = self.validators_pubkey(*parent) { validators.iter().map(public_to_address).collect() } else { diff --git a/core/src/consensus/validator_set/mod.rs b/core/src/consensus/validator_set/mod.rs index b86f8d9d14..ba8127fac3 100644 --- a/core/src/consensus/validator_set/mod.rs +++ b/core/src/consensus/validator_set/mod.rs @@ -17,7 +17,7 @@ use std::sync::Weak; use ckey::{Address, Public}; -use primitives::H256; +use ctypes::BlockHash; use self::validator_list::RoundRobinValidator; use super::BitSet; @@ -33,29 +33,29 @@ pub use self::dynamic_validator::DynamicValidator; pub trait ValidatorSet: Send + Sync { /// Checks if a given public key is a validator, /// using underlying, default call mechanism. - fn contains(&self, parent: &H256, public: &Public) -> bool; + fn contains(&self, parent: &BlockHash, public: &Public) -> bool; /// Checks if a given address is a validator. - fn contains_address(&self, parent: &H256, address: &Address) -> bool; + fn contains_address(&self, parent: &BlockHash, address: &Address) -> bool; /// Draws a validator from index modulo number of validators. - fn get(&self, parent: &H256, index: usize) -> Public; + fn get(&self, parent: &BlockHash, index: usize) -> Public; /// Draws a validator from nonce modulo number of validators. - fn get_index(&self, parent: &H256, public: &Public) -> Option; + fn get_index(&self, parent: &BlockHash, public: &Public) -> Option; /// Draws a validator index from validator address. - fn get_index_by_address(&self, parent: &H256, address: &Address) -> Option; + fn get_index_by_address(&self, parent: &BlockHash, address: &Address) -> Option; - fn next_block_proposer(&self, parent: &H256, view: u64) -> Option
; + fn next_block_proposer(&self, parent: &BlockHash, view: u64) -> Option
; /// Returns the current number of validators. - fn count(&self, parent: &H256) -> usize; + fn count(&self, parent: &BlockHash) -> usize; - fn check_enough_votes(&self, parent: &H256, votes: &BitSet) -> Result<(), EngineError>; + fn check_enough_votes(&self, parent: &BlockHash, votes: &BitSet) -> Result<(), EngineError>; /// Allows blockchain state access. fn register_client(&self, _client: Weak) {} - fn addresses(&self, _parent: &H256) -> Vec
; + fn addresses(&self, _parent: &BlockHash) -> Vec
; } diff --git a/core/src/consensus/validator_set/validator_list.rs b/core/src/consensus/validator_set/validator_list.rs index cdec5664e5..2c56efd72b 100644 --- a/core/src/consensus/validator_set/validator_list.rs +++ b/core/src/consensus/validator_set/validator_list.rs @@ -19,8 +19,8 @@ use std::sync::{Arc, Weak}; use ckey::{public_to_address, Address, Public}; use ctypes::util::unexpected::OutOfBounds; +use ctypes::BlockHash; use parking_lot::RwLock; -use primitives::H256; use super::super::BitSet; use super::ValidatorSet; @@ -47,29 +47,29 @@ impl RoundRobinValidator { } impl ValidatorSet for RoundRobinValidator { - fn contains(&self, _bh: &H256, public: &Public) -> bool { + fn contains(&self, _bh: &BlockHash, public: &Public) -> bool { self.validators.contains(public) } - fn contains_address(&self, _bh: &H256, address: &Address) -> bool { + fn contains_address(&self, _bh: &BlockHash, address: &Address) -> bool { self.addresses.contains(address) } - fn get(&self, _bh: &H256, index: usize) -> Public { + fn get(&self, _bh: &BlockHash, index: usize) -> Public { let validator_n = self.validators.len(); assert_ne!(0, validator_n, "Cannot operate with an empty validator set."); *self.validators.get(index % validator_n).expect("There are validator_n authorities; taking number modulo validator_n gives number in validator_n range; qed") } - fn get_index(&self, _bh: &H256, public: &Public) -> Option { + fn get_index(&self, _bh: &BlockHash, public: &Public) -> Option { self.validators.iter().position(|v| v == public) } - fn get_index_by_address(&self, _bh: &H256, address: &Address) -> Option { + fn get_index_by_address(&self, _bh: &BlockHash, address: &Address) -> Option { self.validators.iter().position(|v| public_to_address(v) == *address) } - fn next_block_proposer(&self, parent: &H256, view: u64) -> Option
{ + fn next_block_proposer(&self, parent: &BlockHash, view: u64) -> Option
{ let client: Arc = self.client.read().as_ref().and_then(Weak::upgrade)?; client.block_header(&BlockId::from(*parent)).map(|header| { let proposer = header.author(); @@ -82,11 +82,11 @@ impl ValidatorSet for RoundRobinValidator { }) } - fn count(&self, _bh: &H256) -> usize { + fn count(&self, _bh: &BlockHash) -> usize { self.validators.len() } - fn check_enough_votes(&self, parent: &H256, votes: &BitSet) -> Result<(), EngineError> { + fn check_enough_votes(&self, parent: &BlockHash, votes: &BitSet) -> Result<(), EngineError> { let validator_count = self.count(parent); let voted = votes.count(); if voted * 3 > validator_count * 2 { @@ -105,7 +105,7 @@ impl ValidatorSet for RoundRobinValidator { *self.client.write() = Some(client); } - fn addresses(&self, _parent: &H256) -> Vec
{ + fn addresses(&self, _parent: &BlockHash) -> Vec
{ self.validators.iter().map(public_to_address).collect() } } diff --git a/core/src/encoded.rs b/core/src/encoded.rs index 06f592c0fe..375a6505fd 100644 --- a/core/src/encoded.rs +++ b/core/src/encoded.rs @@ -25,7 +25,7 @@ use ccrypto::blake256; use ckey::Address; -use ctypes::{BlockNumber, Header as FullHeader}; +use ctypes::{BlockHash, BlockNumber, Header as FullHeader}; use primitives::{H256, U256}; use rlp::Rlp; @@ -71,12 +71,12 @@ impl Header { // forwarders to borrowed view. impl Header { /// Returns the header hash. - pub fn hash(&self) -> H256 { - blake256(&self.0) + pub fn hash(&self) -> BlockHash { + blake256(&self.0).into() } /// Returns the parent hash. - pub fn parent_hash(&self) -> H256 { + pub fn parent_hash(&self) -> BlockHash { self.view().parent_hash() } @@ -230,12 +230,12 @@ impl Block { // forwarders to borrowed header view. impl Block { /// Returns the header hash. - pub fn hash(&self) -> H256 { + pub fn hash(&self) -> BlockHash { self.header_view().hash() } /// Returns the parent hash. - pub fn parent_hash(&self) -> H256 { + pub fn parent_hash(&self) -> BlockHash { self.header_view().parent_hash() } diff --git a/core/src/error.rs b/core/src/error.rs index 47458b2d52..77ff4486d6 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -22,7 +22,7 @@ use cmerkle::TrieError; use cstate::StateError; use ctypes::errors::{HistoryError, RuntimeError, SyntaxError}; use ctypes::util::unexpected::{Mismatch, OutOfBounds}; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::{H256, U256}; use util_error::UtilError; @@ -104,7 +104,7 @@ pub enum BlockError { TemporarilyInvalid(OutOfBounds), /// Parent hash field of header is invalid; this is an invalid error indicating a logic flaw in the codebase. /// TODO: remove and favour an assert!/panic!. - InvalidParentHash(Mismatch), + InvalidParentHash(Mismatch), /// Number field of header is invalid. InvalidNumber(Mismatch), /// Block number isn't sensible. @@ -112,7 +112,7 @@ pub enum BlockError { /// Too many transactions from a particular address. TooManyTransactions(Address), /// Parent given is unknown. - UnknownParent(H256), + UnknownParent(BlockHash), /// Body size limit is exceeded. BodySizeIsTooBig, } diff --git a/core/src/miner/miner.rs b/core/src/miner/miner.rs index 09a8b5ee63..f4795b50ff 100644 --- a/core/src/miner/miner.rs +++ b/core/src/miner/miner.rs @@ -26,7 +26,7 @@ use ckey::{public_to_address, Address, Password, PlatformAddress, Public}; use cstate::{FindActionHandler, TopLevelState}; use ctypes::errors::{HistoryError, RuntimeError}; use ctypes::transaction::{Action, IncompleteTransaction, Timelock}; -use ctypes::{BlockNumber, Header}; +use ctypes::{BlockHash, BlockNumber, Header}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; use parking_lot::{Mutex, RwLock}; @@ -442,10 +442,10 @@ impl Miner { "prepare_work: Pushing a new, refreshed or borrowed pending {}...", block.block().header().hash() ); - let pow_hash = block.block().header().hash(); + let pow_hash = *block.block().header().hash(); let number = block.block().header().number(); let score = *block.block().header().score(); - let is_new = original_work_hash.map_or(true, |h| block.block().header().hash() != h); + let is_new = original_work_hash.map_or(true, |h| *block.block().header().hash() != h); sealing_work.queue.push(block); // If push notifications are enabled we assume all work items are used. if !self.notifiers.read().is_empty() && is_new { @@ -483,7 +483,7 @@ impl Miner { let (transactions, mut open_block, original_work_hash, block_number) = { let sealing_work = self.sealing_work.lock(); - let last_work_hash = sealing_work.queue.peek_last_ref().map(|pb| pb.block().header().hash()); + let last_work_hash = sealing_work.queue.peek_last_ref().map(|pb| *pb.block().header().hash()); ctrace!(MINER, "prepare_block: No existing work - making new block"); let params = self.params.read().clone(); let open_block = chain.prepare_open_block(parent_block_id, params.author, params.extra_data); @@ -774,10 +774,10 @@ impl MinerService for Miner { fn chain_new_blocks( &self, chain: &C, - _imported: &[H256], - _invalid: &[H256], - _enacted: &[H256], - retracted: &[H256], + _imported: &[BlockHash], + _invalid: &[BlockHash], + _enacted: &[BlockHash], + retracted: &[BlockHash], ) where C: AccountData + BlockChainTrait + BlockProducer + EngineInfo + ImportBlock, { ctrace!(MINER, "chain_new_blocks"); @@ -937,8 +937,8 @@ impl MinerService for Miner { } } - fn submit_seal(&self, chain: &C, block_hash: H256, seal: Vec) -> Result<(), Error> { - let result = if let Some(b) = self.sealing_work.lock().queue.take_used_if(|b| b.hash() == block_hash) { + fn submit_seal(&self, chain: &C, block_hash: BlockHash, seal: Vec) -> Result<(), Error> { + let result = if let Some(b) = self.sealing_work.lock().queue.take_used_if(|b| b.hash() == *block_hash) { ctrace!( MINER, "Submitted block {}={}={} with seal {:?}", diff --git a/core/src/miner/mod.rs b/core/src/miner/mod.rs index 1922977013..867ec2a4eb 100644 --- a/core/src/miner/mod.rs +++ b/core/src/miner/mod.rs @@ -28,6 +28,7 @@ use std::ops::Range; use ckey::{Address, Password, PlatformAddress}; use cstate::{FindActionHandler, TopStateView}; use ctypes::transaction::IncompleteTransaction; +use ctypes::BlockHash; use cvm::ChainTimeInfo; use primitives::{Bytes, H256}; @@ -73,8 +74,14 @@ pub trait MinerService: Send + Sync { fn set_transactions_limit(&self, limit: usize); /// Called when blocks are imported to chain, updates transactions queue. - fn chain_new_blocks(&self, chain: &C, imported: &[H256], invalid: &[H256], enacted: &[H256], retracted: &[H256]) - where + fn chain_new_blocks( + &self, + chain: &C, + imported: &[BlockHash], + invalid: &[BlockHash], + enacted: &[BlockHash], + retracted: &[BlockHash], + ) where C: AccountData + BlockChainTrait + BlockProducer + EngineInfo + ImportBlock; /// PoW chain - can produce work package @@ -102,7 +109,7 @@ pub trait MinerService: Send + Sync { /// Submit `seal` as a valid solution for the header of `pow_hash`. /// Will check the seal, but not actually insert the block into the chain. - fn submit_seal(&self, chain: &C, pow_hash: H256, seal: Vec) -> Result<(), Error>; + fn submit_seal(&self, chain: &C, pow_hash: BlockHash, seal: Vec) -> Result<(), Error>; /// Get the sealing work package and if `Some`, apply some transform. fn map_sealing_work(&self, client: &C, f: F) -> Option diff --git a/core/src/miner/stratum.rs b/core/src/miner/stratum.rs index 167c9525d4..ce61e49240 100644 --- a/core/src/miner/stratum.rs +++ b/core/src/miner/stratum.rs @@ -60,7 +60,7 @@ impl JobDispatcher for StratumJobDispatcher { return Err(StratumServiceError::InternalError) } - match self.miner.submit_seal(&*self.client, pow_hash, seal) { + match self.miner.submit_seal(&*self.client, pow_hash.into(), seal) { Ok(_) => Ok(()), Err(e) => { cwarn!(STRATUM, "submit_seal error: {:?}", e); diff --git a/core/src/scheme/genesis.rs b/core/src/scheme/genesis.rs index 30623f00d9..cb03c27d5a 100644 --- a/core/src/scheme/genesis.rs +++ b/core/src/scheme/genesis.rs @@ -17,6 +17,7 @@ use ccrypto::BLAKE_NULL_RLP; use cjson; use ckey::{Address, PlatformAddress}; +use ctypes::BlockHash; use primitives::{Bytes, H256, U256}; use super::seal::Seal; @@ -32,7 +33,7 @@ pub struct Genesis { /// Timestamp. pub timestamp: u64, /// Parent hash. - pub parent_hash: H256, + pub parent_hash: BlockHash, /// Transactions root. pub transactions_root: H256, /// State root. @@ -48,7 +49,7 @@ impl From for Genesis { score: g.score.into(), author: g.author.map_or_else(Address::default, PlatformAddress::into_address), timestamp: g.timestamp.map_or(0, Into::into), - parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into), + parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into).into(), transactions_root: g.transactions_root.map_or_else(|| BLAKE_NULL_RLP, Into::into), state_root: g.state_root.map(Into::into), extra_data: g.extra_data.map_or_else(Vec::new, Into::into), diff --git a/core/src/scheme/scheme.rs b/core/src/scheme/scheme.rs index 69a425a5a5..68d8aefe8d 100644 --- a/core/src/scheme/scheme.rs +++ b/core/src/scheme/scheme.rs @@ -23,7 +23,7 @@ use ckey::Address; use cmerkle::TrieFactory; use cstate::{Metadata, MetadataAddress, Shard, ShardAddress, StateDB, StateResult, StateWithCache, TopLevelState}; use ctypes::errors::SyntaxError; -use ctypes::{CommonParams, Header, ShardId}; +use ctypes::{BlockHash, CommonParams, Header, ShardId}; use hashdb::{AsHashDB, HashDB}; use parking_lot::RwLock; use primitives::{Bytes, H256, U256}; @@ -52,7 +52,7 @@ pub struct Scheme { pub nodes: Vec, /// The genesis block's parent hash field. - pub parent_hash: H256, + pub parent_hash: BlockHash, /// The genesis block's author field. pub author: Address, /// The genesis block's score field. diff --git a/core/src/service.rs b/core/src/service.rs index 78e3a1e4ef..52e956d522 100644 --- a/core/src/service.rs +++ b/core/src/service.rs @@ -19,8 +19,9 @@ use std::sync::Arc; use cio::{IoContext, IoHandler, IoHandlerResult, IoService}; use cnetwork::NodeId; use ctimer::TimerApi; +use ctypes::BlockHash; use kvdb::KeyValueDB; -use primitives::{Bytes, H256}; +use primitives::Bytes; use crate::client::{Client, ClientConfig}; use crate::error::Error; @@ -80,7 +81,7 @@ pub enum ClientIoMessage { }, /// Update the best block by the given hash /// Only used in Tendermint - UpdateBestAsCommitted(H256), + UpdateBestAsCommitted(BlockHash), } /// IO interface for the Client handler diff --git a/core/src/tests/helpers.rs b/core/src/tests/helpers.rs index 003c0d45dc..31e79a43c9 100644 --- a/core/src/tests/helpers.rs +++ b/core/src/tests/helpers.rs @@ -15,8 +15,8 @@ // along with this program. If not, see . use cstate::StateDB; -use ctypes::Header; -use primitives::{Bytes, H256, U256}; +use ctypes::{BlockHash, Header}; +use primitives::{Bytes, U256}; use rlp::{self, RlpStream}; use crate::scheme::Scheme; @@ -46,7 +46,7 @@ pub fn get_good_dummy_block() -> Bytes { bytes } -pub fn get_good_dummy_block_hash() -> (H256, Bytes) { +pub fn get_good_dummy_block_hash() -> (BlockHash, Bytes) { let mut block_header = Header::new(); let test_scheme = Scheme::new_test(); block_header.set_score(U256::from(0x20000)); diff --git a/core/src/transaction.rs b/core/src/transaction.rs index 5820a3ff5f..2749e12955 100644 --- a/core/src/transaction.rs +++ b/core/src/transaction.rs @@ -20,7 +20,7 @@ use ccrypto::blake256; use ckey::{self, public_to_address, recover, sign, Private, Public, Signature}; use ctypes::errors::SyntaxError; use ctypes::transaction::Transaction; -use ctypes::{BlockNumber, CommonParams}; +use ctypes::{BlockHash, BlockNumber, CommonParams}; use primitives::H256; use rlp::{self, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -231,7 +231,7 @@ pub struct LocalizedTransaction { /// Block number. pub block_number: BlockNumber, /// Block hash. - pub block_hash: H256, + pub block_hash: BlockHash, /// Transaction index within block. pub transaction_index: usize, /// Cached public diff --git a/core/src/types/ids.rs b/core/src/types/ids.rs index 66b4e5b22f..1aa6ca8f5d 100644 --- a/core/src/types/ids.rs +++ b/core/src/types/ids.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::H256; /// Uniquely identifies block. @@ -22,7 +22,7 @@ use primitives::H256; pub enum BlockId { /// Block's blake256. /// Querying by hash is always faster. - Hash(H256), + Hash(BlockHash), /// Block number within canon blockchain. Number(BlockNumber), /// Earliest block (genesis). @@ -33,8 +33,8 @@ pub enum BlockId { ParentOfLatest, } -impl From for BlockId { - fn from(hash: H256) -> Self { +impl From for BlockId { + fn from(hash: BlockHash) -> Self { BlockId::Hash(hash) } } diff --git a/core/src/verification/queue/kind.rs b/core/src/verification/queue/kind.rs index 7140d38a5b..5e42af309a 100644 --- a/core/src/verification/queue/kind.rs +++ b/core/src/verification/queue/kind.rs @@ -14,7 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use primitives::{H256, U256}; +use ctypes::BlockHash; +use primitives::U256; use rlp::*; pub use self::blocks::Blocks; @@ -27,10 +28,10 @@ use crate::service::ClientIoMessage; /// Something which can produce a hash and a parent hash. pub trait BlockLike { /// Get the hash of this item. - fn hash(&self) -> H256; + fn hash(&self) -> BlockHash; /// Get the hash of this item's parent. - fn parent_hash(&self) -> H256; + fn parent_hash(&self) -> BlockHash; /// Get the score of this item. fn score(&self) -> U256; @@ -84,8 +85,8 @@ pub trait Kind: 'static + Sized + Send + Sync { /// Verification for headers. pub mod headers { - use ctypes::Header; - use primitives::{H256, U256}; + use ctypes::{BlockHash, Header}; + use primitives::U256; use super::super::super::verification::verify_header_basic; use super::{BlockLike, Kind}; @@ -95,11 +96,11 @@ pub mod headers { use verification::verify_header_with_engine; impl BlockLike for Header { - fn hash(&self) -> H256 { + fn hash(&self) -> BlockHash { self.hash() } - fn parent_hash(&self) -> H256 { + fn parent_hash(&self) -> BlockHash { *self.parent_hash() } @@ -147,8 +148,8 @@ pub mod headers { /// The blocks verification module. pub mod blocks { - use ctypes::Header; - use primitives::{Bytes, H256, U256}; + use ctypes::{BlockHash, Header}; + use primitives::{Bytes, U256}; use super::super::super::verification::{ verify_block_basic, verify_block_seal, verify_header_with_engine, PreverifiedBlock, @@ -225,11 +226,11 @@ pub mod blocks { } impl BlockLike for Unverified { - fn hash(&self) -> H256 { + fn hash(&self) -> BlockHash { self.header.hash() } - fn parent_hash(&self) -> H256 { + fn parent_hash(&self) -> BlockHash { *self.header.parent_hash() } @@ -239,11 +240,11 @@ pub mod blocks { } impl BlockLike for PreverifiedBlock { - fn hash(&self) -> H256 { + fn hash(&self) -> BlockHash { self.header.hash() } - fn parent_hash(&self) -> H256 { + fn parent_hash(&self) -> BlockHash { *self.header.parent_hash() } diff --git a/core/src/verification/queue/mod.rs b/core/src/verification/queue/mod.rs index 451c51c787..dc8cdccb5b 100644 --- a/core/src/verification/queue/mod.rs +++ b/core/src/verification/queue/mod.rs @@ -23,8 +23,9 @@ use std::sync::{Arc, Condvar as SCondvar, Mutex as SMutex}; use std::thread::{self, JoinHandle}; use cio::IoChannel; +use ctypes::BlockHash; use parking_lot::{Mutex, RwLock}; -use primitives::{H256, U256}; +use primitives::U256; use self::kind::{BlockLike, Kind, MemUsage}; use crate::consensus::CodeChainEngine; @@ -65,7 +66,7 @@ impl Default for Config { pub struct VerificationQueue { engine: Arc, verification: Arc>, - processing: RwLock>, // hash to score + processing: RwLock>, // hash to score deleting: Arc, ready_signal: Arc, total_score: RwLock, @@ -300,7 +301,7 @@ impl VerificationQueue { fn drain_verifying( verifying: &mut VecDeque>, verified: &mut VecDeque, - bad: &mut HashSet, + bad: &mut HashSet, sizes: &Sizes, ) { let mut removed_size = 0; @@ -324,7 +325,7 @@ impl VerificationQueue { } /// Check if the item is currently in the queue - pub fn status(&self, hash: &H256) -> Status { + pub fn status(&self, hash: &BlockHash) -> Status { if self.processing.read().contains_key(hash) { return Status::Queued } @@ -335,7 +336,7 @@ impl VerificationQueue { } /// Add a block to the queue. - pub fn import(&self, input: K::Input) -> Result { + pub fn import(&self, input: K::Input) -> Result { let h = input.hash(); { if self.processing.read().contains_key(&h) { @@ -397,7 +398,7 @@ impl VerificationQueue { /// Mark given item as processed. /// Returns true if the queue becomes empty. - pub fn mark_as_good(&self, hashes: &[H256]) -> bool { + pub fn mark_as_good(&self, hashes: &[BlockHash]) -> bool { if hashes.is_empty() { return self.processing.read().is_empty() } @@ -414,7 +415,7 @@ impl VerificationQueue { /// Mark given item and all its children as bad. pauses verification /// until complete. - pub fn mark_as_bad(&self, hashes: &[H256]) { + pub fn mark_as_bad(&self, hashes: &[BlockHash]) { if hashes.is_empty() { return } @@ -509,7 +510,7 @@ struct Verification { unverified: Mutex>, verifying: Mutex>>, verified: Mutex>, - bad: Mutex>, + bad: Mutex>, sizes: Sizes, check_seal: bool, #[allow(dead_code)] @@ -519,7 +520,7 @@ struct Verification { /// An item which is in the process of being verified. pub struct Verifying { - hash: H256, + hash: BlockHash, output: Option, } diff --git a/core/src/views/block.rs b/core/src/views/block.rs index e4f93b4950..c10ee7e188 100644 --- a/core/src/views/block.rs +++ b/core/src/views/block.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . use ccrypto::blake256; -use ctypes::Header; +use ctypes::{BlockHash, Header}; use primitives::H256; use rlp::Rlp; @@ -43,7 +43,7 @@ impl<'a> BlockView<'a> { } /// Block header hash. - pub fn hash(&self) -> H256 { + pub fn hash(&self) -> BlockHash { self.header_view().hash() } diff --git a/core/src/views/body.rs b/core/src/views/body.rs index e733f1e457..b6454cb28f 100644 --- a/core/src/views/body.rs +++ b/core/src/views/body.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . use ccrypto::blake256; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::H256; use rlp::Rlp; @@ -53,7 +53,11 @@ impl<'a> BodyView<'a> { } /// Return List of transactions with additional localization info. - pub fn localized_transactions(&self, block_hash: &H256, block_number: BlockNumber) -> Vec { + pub fn localized_transactions( + &self, + block_hash: &BlockHash, + block_number: BlockNumber, + ) -> Vec { self.transactions() .into_iter() .enumerate() @@ -90,7 +94,7 @@ impl<'a> BodyView<'a> { /// Returns localized transaction at given index. pub fn localized_transaction_at( &self, - block_hash: &H256, + block_hash: &BlockHash, block_number: BlockNumber, transaction_index: usize, ) -> Option { diff --git a/core/src/views/header.rs b/core/src/views/header.rs index 7cfb74057f..d5f23b47d2 100644 --- a/core/src/views/header.rs +++ b/core/src/views/header.rs @@ -16,7 +16,7 @@ use ccrypto::blake256; use ckey::Address; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::{Bytes, H256, U256}; use rlp::{self, Rlp}; @@ -41,8 +41,8 @@ impl<'a> HeaderView<'a> { } /// Returns header hash. - pub fn hash(&self) -> H256 { - blake256(self.rlp.as_raw()) + pub fn hash(&self) -> BlockHash { + blake256(self.rlp.as_raw()).into() } /// Returns raw rlp. @@ -51,8 +51,8 @@ impl<'a> HeaderView<'a> { } /// Returns parent hash. - pub fn parent_hash(&self) -> H256 { - self.rlp.val_at(0) + pub fn parent_hash(&self) -> BlockHash { + self.rlp.val_at::(0) } /// Returns author. diff --git a/rpc/src/v1/impls/chain.rs b/rpc/src/v1/impls/chain.rs index addac3d980..414b44bf47 100644 --- a/rpc/src/v1/impls/chain.rs +++ b/rpc/src/v1/impls/chain.rs @@ -26,7 +26,7 @@ use cjson::uint::Uint; use ckey::{public_to_address, NetworkId, PlatformAddress, Public}; use cstate::FindActionHandler; use ctypes::transaction::{Action, ShardTransaction as ShardTransactionType}; -use ctypes::{BlockNumber, ShardId}; +use ctypes::{BlockHash, BlockNumber, ShardId}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -233,7 +233,7 @@ where }) } - fn get_block_hash(&self, block_number: u64) -> Result> { + fn get_block_hash(&self, block_number: u64) -> Result> { Ok(self.client.block_hash(&BlockId::Number(block_number))) } @@ -249,7 +249,7 @@ where })) } - fn get_block_by_hash(&self, block_hash: H256) -> Result> { + fn get_block_by_hash(&self, block_hash: BlockHash) -> Result> { let id = BlockId::Hash(block_hash); Ok(self.client.block(&id).map(|block| { let block = block.decode(); @@ -262,7 +262,7 @@ where })) } - fn get_block_transaction_count_by_hash(&self, block_hash: H256) -> Result> { + fn get_block_transaction_count_by_hash(&self, block_hash: BlockHash) -> Result> { Ok(self.client.block(&BlockId::Hash(block_hash)).map(|block| block.transactions_count())) } diff --git a/rpc/src/v1/impls/miner.rs b/rpc/src/v1/impls/miner.rs index 5278593fa5..bee179060d 100644 --- a/rpc/src/v1/impls/miner.rs +++ b/rpc/src/v1/impls/miner.rs @@ -19,8 +19,8 @@ use std::sync::Arc; use ccore::block::IsBlock; use ccore::{EngineClient, EngineInfo, MinerService, MiningBlockChainClient, TermInfo}; use cjson::bytes::Bytes; +use ctypes::BlockHash; use jsonrpc_core::Result; -use primitives::H256; use super::super::errors; use super::super::traits::Miner; @@ -67,7 +67,7 @@ where .unwrap_or_else(|| Err(errors::internal("No work found.", ""))) } - fn submit_work(&self, pow_hash: H256, seal: Vec) -> Result { + fn submit_work(&self, pow_hash: BlockHash, seal: Vec) -> Result { if !self.miner.can_produce_work_package() { cwarn!(MINER, "Cannot give work package - engine seals internally."); return Err(errors::no_work_required()) diff --git a/rpc/src/v1/traits/chain.rs b/rpc/src/v1/traits/chain.rs index 268d13b193..09b45fc621 100644 --- a/rpc/src/v1/traits/chain.rs +++ b/rpc/src/v1/traits/chain.rs @@ -17,7 +17,7 @@ use cjson::scheme::Params; use cjson::uint::Uint; use ckey::{NetworkId, PlatformAddress, Public}; -use ctypes::{BlockNumber, ShardId}; +use ctypes::{BlockHash, BlockNumber, ShardId}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -137,7 +137,7 @@ pub trait Chain { /// Gets the hash of the block with given number. #[rpc(name = "chain_getBlockHash")] - fn get_block_hash(&self, block_number: u64) -> Result>; + fn get_block_hash(&self, block_number: u64) -> Result>; /// Gets block with given number. #[rpc(name = "chain_getBlockByNumber")] @@ -145,11 +145,11 @@ pub trait Chain { /// Gets block with given hash. #[rpc(name = "chain_getBlockByHash")] - fn get_block_by_hash(&self, block_hash: H256) -> Result>; + fn get_block_by_hash(&self, block_hash: BlockHash) -> Result>; ///Gets the count of transactions in a block with given hash. #[rpc(name = "chain_getBlockTransactionCountByHash")] - fn get_block_transaction_count_by_hash(&self, block_hash: H256) -> Result>; + fn get_block_transaction_count_by_hash(&self, block_hash: BlockHash) -> Result>; ///Gets the minimum transaction fee of the given name. #[rpc(name = "chain_getMinTransactionFee")] diff --git a/rpc/src/v1/traits/miner.rs b/rpc/src/v1/traits/miner.rs index 79965bd450..ea204c4549 100644 --- a/rpc/src/v1/traits/miner.rs +++ b/rpc/src/v1/traits/miner.rs @@ -15,8 +15,8 @@ // along with this program. If not, see . use cjson::bytes::Bytes; +use ctypes::BlockHash; use jsonrpc_core::Result; -use primitives::H256; use super::super::types::Work; @@ -26,5 +26,5 @@ pub trait Miner { fn get_work(&self) -> Result; #[rpc(name = "miner_submitWork")] - fn submit_work(&self, pow_hash: H256, seal: Vec) -> Result; + fn submit_work(&self, pow_hash: BlockHash, seal: Vec) -> Result; } diff --git a/rpc/src/v1/types/block.rs b/rpc/src/v1/types/block.rs index 34655e059f..8798e753c1 100644 --- a/rpc/src/v1/types/block.rs +++ b/rpc/src/v1/types/block.rs @@ -16,7 +16,7 @@ use ccore::{Block as CoreBlock, LocalizedTransaction}; use ckey::{NetworkId, PlatformAddress}; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::{H256, U256}; use super::Transaction; @@ -24,7 +24,7 @@ use super::Transaction; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Block { - parent_hash: H256, + parent_hash: BlockHash, timestamp: u64, number: u64, author: PlatformAddress, @@ -37,7 +37,7 @@ pub struct Block { score: U256, seal: Vec>, - hash: H256, + hash: BlockHash, transactions: Vec, } @@ -77,5 +77,5 @@ impl Block { #[serde(rename_all = "camelCase")] pub struct BlockNumberAndHash { pub number: BlockNumber, - pub hash: H256, + pub hash: BlockHash, } diff --git a/rpc/src/v1/types/transaction.rs b/rpc/src/v1/types/transaction.rs index 6e0c25dbba..eabd150a8f 100644 --- a/rpc/src/v1/types/transaction.rs +++ b/rpc/src/v1/types/transaction.rs @@ -17,6 +17,7 @@ use ccore::{LocalizedTransaction, PendingSignedTransactions, SignedTransaction}; use cjson::uint::Uint; use ckey::{NetworkId, Signature}; +use ctypes::BlockHash; use primitives::H256; use super::ActionWithTracker; @@ -25,7 +26,7 @@ use super::ActionWithTracker; #[serde(rename_all = "camelCase")] pub struct Transaction { pub block_number: Option, - pub block_hash: Option, + pub block_hash: Option, pub transaction_index: Option, pub result: Option, pub seq: u64, diff --git a/sync/src/block/downloader/body.rs b/sync/src/block/downloader/body.rs index e9c1885f76..96a99f6b7d 100644 --- a/sync/src/block/downloader/body.rs +++ b/sync/src/block/downloader/body.rs @@ -17,15 +17,15 @@ use std::collections::{HashMap, HashSet}; use ccore::UnverifiedTransaction; -use ctypes::Header; +use ctypes::{BlockHash, Header}; use primitives::H256; use super::super::message::RequestMessage; #[derive(Clone)] struct Target { - hash: H256, - transaction_hash: H256, + hash: BlockHash, + parent_hash: BlockHash, transactions_root: H256, transaction_root: H256, } @@ -33,8 +33,8 @@ struct Target { #[derive(Default)] pub struct BodyDownloader { targets: Vec, - downloading: HashSet, - downloaded: HashMap>, + downloading: HashSet, + downloaded: HashMap>, } impl BodyDownloader { @@ -57,7 +57,7 @@ impl BodyDownloader { } } - pub fn import_bodies(&mut self, hashes: Vec, bodies: Vec>) { + pub fn import_bodies(&mut self, hashes: Vec, bodies: Vec>) { for (hash, body) in hashes.into_iter().zip(bodies) { if self.downloading.remove(&hash) { if body.is_empty() { @@ -76,13 +76,13 @@ impl BodyDownloader { cdebug!(SYNC, "Add download target: {}", header.hash()); self.targets.push(Target { hash: header.hash(), - transaction_hash: parent.hash(), + parent_hash: parent.hash(), transactions_root: *header.transactions_root(), transaction_root: *parent.transactions_root(), }); } - pub fn remove_target(&mut self, targets: &[H256]) { + pub fn remove_target(&mut self, targets: &[BlockHash]) { if targets.is_empty() { return } @@ -99,7 +99,7 @@ impl BodyDownloader { self.downloaded.shrink_to_fit(); } - pub fn reset_downloading(&mut self, hashes: &[H256]) { + pub fn reset_downloading(&mut self, hashes: &[BlockHash]) { cdebug!(SYNC, "Remove downloading by timeout {:?}", hashes); for hash in hashes { self.downloading.remove(&hash); @@ -107,7 +107,7 @@ impl BodyDownloader { self.downloading.shrink_to_fit(); } - pub fn drain(&mut self) -> Vec<(H256, Vec)> { + pub fn drain(&mut self) -> Vec<(BlockHash, Vec)> { let mut result = Vec::new(); for t in &self.targets { if let Some(body) = self.downloaded.remove(&t.hash) { diff --git a/sync/src/block/downloader/header.rs b/sync/src/block/downloader/header.rs index f1d2193ca6..963c2135e5 100644 --- a/sync/src/block/downloader/header.rs +++ b/sync/src/block/downloader/header.rs @@ -21,7 +21,8 @@ use std::time::Instant; use ccore::encoded::Header; use ccore::{BlockChainClient, BlockId}; -use primitives::{H256, U256}; +use ctypes::BlockHash; +use primitives::U256; use super::super::message::RequestMessage; @@ -32,7 +33,7 @@ const MAX_WAIT: u64 = 15; #[derive(Clone)] struct Pivot { - hash: H256, + hash: BlockHash, total_score: U256, } @@ -42,12 +43,12 @@ pub struct HeaderDownloader { client: Arc, total_score: U256, - best_hash: H256, + best_hash: BlockHash, pivot: Pivot, request_time: Option, - downloaded: HashMap, - queued: HashMap, + downloaded: HashMap, + queued: HashMap, trial: usize, } @@ -56,7 +57,7 @@ impl HeaderDownloader { self.total_score } - pub fn new(client: Arc, total_score: U256, best_hash: H256) -> Self { + pub fn new(client: Arc, total_score: U256, best_hash: BlockHash) -> Self { let best_header_hash = client.best_block_header().hash(); let best_score = client.block_total_score(&BlockId::Latest).expect("Best block always exist"); @@ -77,7 +78,7 @@ impl HeaderDownloader { } } - pub fn update(&mut self, total_score: U256, best_hash: H256) -> bool { + pub fn update(&mut self, total_score: U256, best_hash: BlockHash) -> bool { match self.total_score.cmp(&total_score) { Ordering::Equal => true, Ordering::Less => { @@ -196,7 +197,7 @@ impl HeaderDownloader { self.downloaded.values().cloned().collect() } - pub fn mark_as_imported(&mut self, hashes: Vec) { + pub fn mark_as_imported(&mut self, hashes: Vec) { for hash in hashes { self.queued.remove(&hash); self.downloaded.remove(&hash); @@ -212,7 +213,7 @@ impl HeaderDownloader { self.downloaded.shrink_to_fit(); } - pub fn mark_as_queued(&mut self, hashes: Vec) { + pub fn mark_as_queued(&mut self, hashes: Vec) { for hash in hashes { if let Some(header) = self.downloaded.remove(&hash) { self.queued.insert(hash, header); diff --git a/sync/src/block/extension.rs b/sync/src/block/extension.rs index 32927c4fab..f089980c29 100644 --- a/sync/src/block/extension.rs +++ b/sync/src/block/extension.rs @@ -29,7 +29,7 @@ use cstate::FindActionHandler; use ctimer::TimerToken; use ctypes::header::{Header, Seal}; use ctypes::transaction::Action; -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::{H256, U256}; use rand::prelude::SliceRandom; use rand::thread_rng; @@ -374,18 +374,18 @@ impl NetworkExtension for Extension { pub enum Event { GetPeers(EventSender), NewHeaders { - imported: Vec, - enacted: Vec, - retracted: Vec, + imported: Vec, + enacted: Vec, + retracted: Vec, }, NewBlocks { - imported: Vec, - invalid: Vec, + imported: Vec, + invalid: Vec, }, } impl Extension { - fn new_headers(&mut self, imported: Vec, enacted: Vec, retracted: Vec) { + fn new_headers(&mut self, imported: Vec, enacted: Vec, retracted: Vec) { let peer_ids: Vec<_> = self.header_downloaders.keys().cloned().collect(); for id in peer_ids { if let Some(peer) = self.header_downloaders.get_mut(&id) { @@ -415,7 +415,7 @@ impl Extension { self.body_downloader.remove_target(&retracted); } - fn new_blocks(&mut self, imported: Vec, invalid: Vec) { + fn new_blocks(&mut self, imported: Vec, invalid: Vec) { self.body_downloader.remove_target(&imported); self.body_downloader.remove_target(&invalid); @@ -440,7 +440,7 @@ impl Extension { } impl Extension { - fn on_peer_status(&mut self, from: &NodeId, total_score: U256, best_hash: H256, genesis_hash: H256) { + fn on_peer_status(&mut self, from: &NodeId, total_score: U256, best_hash: BlockHash, genesis_hash: BlockHash) { // Validity check if genesis_hash != self.client.chain_info().genesis_hash { cinfo!(SYNC, "Genesis hash mismatch with peer {}", from); @@ -543,7 +543,7 @@ impl Extension { ResponseMessage::Headers(headers) } - fn create_bodies_response(&self, hashes: Vec) -> ResponseMessage { + fn create_bodies_response(&self, hashes: Vec) -> ResponseMessage { let bodies = hashes .into_iter() .map(|hash| { @@ -553,11 +553,11 @@ impl Extension { ResponseMessage::Bodies(bodies) } - fn create_state_head_response(&self, _hash: H256) -> ResponseMessage { + fn create_state_head_response(&self, _hash: BlockHash) -> ResponseMessage { unimplemented!() } - fn create_state_chunk_response(&self, _hash: H256, _tree_root: H256) -> ResponseMessage { + fn create_state_chunk_response(&self, _hash: BlockHash, _tree_root: H256) -> ResponseMessage { unimplemented!() } @@ -708,7 +708,7 @@ impl Extension { } } - fn on_body_response(&mut self, hashes: Vec, bodies: Vec>) { + fn on_body_response(&mut self, hashes: Vec, bodies: Vec>) { ctrace!(SYNC, "Received body response with lenth({}) {:?}", hashes.len(), hashes); { self.body_downloader.import_bodies(hashes, bodies); @@ -770,13 +770,13 @@ impl From> for BlockSyncSender { impl ChainNotify for BlockSyncSender { fn new_headers( &self, - imported: Vec, - _invalid: Vec, - enacted: Vec, - retracted: Vec, - _sealed: Vec, + imported: Vec, + _invalid: Vec, + enacted: Vec, + retracted: Vec, + _sealed: Vec, _duration: u64, - _new_best_proposal: Option, + _new_best_proposal: Option, ) { self.0 .send(Event::NewHeaders { @@ -789,11 +789,11 @@ impl ChainNotify for BlockSyncSender { fn new_blocks( &self, - imported: Vec, - invalid: Vec, - _enacted: Vec, - _retracted: Vec, - _sealed: Vec, + imported: Vec, + invalid: Vec, + _enacted: Vec, + _retracted: Vec, + _sealed: Vec, _duration: u64, ) { self.0 diff --git a/sync/src/block/message/mod.rs b/sync/src/block/message/mod.rs index e1abe31f5f..1abffe9b30 100644 --- a/sync/src/block/message/mod.rs +++ b/sync/src/block/message/mod.rs @@ -14,7 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use primitives::{H256, U256}; +use ctypes::BlockHash; +use primitives::U256; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; mod request; @@ -37,8 +38,8 @@ const MESSAGE_ID_STATE_CHUNK: u8 = 0x09; pub enum Message { Status { total_score: U256, - best_hash: H256, - genesis_hash: H256, + best_hash: BlockHash, + genesis_hash: BlockHash, }, Request(u64, RequestMessage), Response(u64, ResponseMessage), @@ -128,6 +129,7 @@ impl Decodable for Message { #[cfg(test)] mod tests { + use primitives::H256; use rlp::rlp_encode_and_decode_test; use super::*; @@ -136,8 +138,8 @@ mod tests { fn status_message_rlp() { rlp_encode_and_decode_test!(Message::Status { total_score: U256::default(), - best_hash: H256::default(), - genesis_hash: H256::default(), + best_hash: H256::default().into(), + genesis_hash: H256::default().into(), }); } @@ -150,6 +152,6 @@ mod tests { #[test] fn request_state_head_rlp() { let request_id = 10; - rlp_encode_and_decode_test!(Message::Request(request_id, RequestMessage::StateHead(H256::random()))); + rlp_encode_and_decode_test!(Message::Request(request_id, RequestMessage::StateHead(H256::random().into()))); } } diff --git a/sync/src/block/message/request.rs b/sync/src/block/message/request.rs index 63d1617d84..e1ad626192 100644 --- a/sync/src/block/message/request.rs +++ b/sync/src/block/message/request.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::BlockNumber; +use ctypes::{BlockHash, BlockNumber}; use primitives::H256; use rlp::{DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -24,10 +24,10 @@ pub enum RequestMessage { start_number: BlockNumber, max_count: u64, }, - Bodies(Vec), - StateHead(H256), + Bodies(Vec), + StateHead(BlockHash), StateChunk { - block_hash: H256, + block_hash: BlockHash, tree_root: H256, }, } @@ -145,20 +145,20 @@ mod tests { #[test] fn request_bodies_message_rlp() { - let message = RequestMessage::Bodies(vec![H256::default()]); + let message = RequestMessage::Bodies(vec![H256::default().into()]); assert_eq!(message, decode_bytes(message.message_id(), message.rlp_bytes().as_ref())); } #[test] fn request_state_head_message_rlp() { - let message = RequestMessage::StateHead(H256::default()); + let message = RequestMessage::StateHead(H256::default().into()); assert_eq!(message, decode_bytes(message.message_id(), message.rlp_bytes().as_ref())); } #[test] fn request_state_chunk_message_rlp() { let message = RequestMessage::StateChunk { - block_hash: H256::default(), + block_hash: H256::default().into(), tree_root: H256::default(), }; assert_eq!(message, decode_bytes(message.message_id(), message.rlp_bytes().as_ref())); diff --git a/sync/src/snapshot/service.rs b/sync/src/snapshot/service.rs index 3b708f43d0..a9cdcf4fab 100644 --- a/sync/src/snapshot/service.rs +++ b/sync/src/snapshot/service.rs @@ -20,8 +20,7 @@ use std::sync::Arc; use std::thread::spawn; use ccore::{BlockChainClient, BlockChainTrait, BlockId, ChainNotify, Client, DatabaseClient}; - -use primitives::H256; +use ctypes::BlockHash; use super::error::Error; use super::snapshot::{Snapshot, WriteSnapshot}; @@ -48,11 +47,11 @@ impl ChainNotify for Service { /// fires when chain has new blocks. fn new_blocks( &self, - _imported: Vec, - _invalid: Vec, - enacted: Vec, - _retracted: Vec, - _sealed: Vec, + _imported: Vec, + _invalid: Vec, + enacted: Vec, + _retracted: Vec, + _sealed: Vec, _duration: u64, ) { let best_number = self.client.chain_info().best_block_number; @@ -65,7 +64,7 @@ impl ChainNotify for Service { let header = self.client.block_header(&BlockId::Number(number)).expect("Snapshot target must exist"); let db = self.client.database(); - let path: PathBuf = [self.root_dir.clone(), format!("{:x}", header.hash())].iter().collect(); + let path: PathBuf = [self.root_dir.clone(), format!("{:x}", *header.hash())].iter().collect(); let root = header.state_root(); // FIXME: The db can be corrupted because the CodeChain doesn't wait child threads end on exit. spawn(move || match Snapshot::try_new(path).map(|s| s.write_snapshot(db.as_ref(), &root)) { diff --git a/types/src/block_hash.rs b/types/src/block_hash.rs new file mode 100644 index 0000000000..08d7610c3a --- /dev/null +++ b/types/src/block_hash.rs @@ -0,0 +1,109 @@ +// Copyright 2019 Kodebox, Inc. +// This file is part of CodeChain. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +use std::fmt::{self, Display, Formatter}; +use std::ops::Deref; + +use primitives::H256; +use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; + + +#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Debug, Deserialize, Serialize)] +pub struct BlockHash(H256); + +impl From for BlockHash { + fn from(h: H256) -> Self { + Self(h) + } +} + +impl Deref for BlockHash { + type Target = H256; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for BlockHash { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + +impl Encodable for BlockHash { + fn rlp_append(&self, s: &mut RlpStream) { + self.0.rlp_append(s); + } +} + +impl Decodable for BlockHash { + fn decode(rlp: &UntrustedRlp) -> Result { + Ok(H256::decode(rlp)?.into()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + use rlp::{self, rlp_encode_and_decode_test}; + + use super::*; + + #[test] + fn hash_of_block_hash_and_h256_are_the_same() { + let h256 = H256::random(); + let block_hash = BlockHash(h256); + + let mut hasher_of_h256 = DefaultHasher::new(); + let mut hasher_of_tracker = DefaultHasher::new(); + + h256.hash(&mut hasher_of_h256); + block_hash.hash(&mut hasher_of_tracker); + + assert_eq!(hasher_of_h256.finish(), hasher_of_tracker.finish()); + } + + #[test] + fn rlp_of_block_hash_can_be_decoded_to_h256() { + let h256 = H256::random(); + let block_hash = BlockHash(h256); + + let encoded = rlp::encode(&block_hash); + let decoded = rlp::decode(&*encoded); + + assert_eq!(h256, decoded); + } + + #[test] + fn rlp_of_h256_can_be_decoded_to_block_hash() { + let h256 = H256::random(); + + let encoded = rlp::encode(&h256); + let decoded = rlp::decode(&*encoded); + + let block_hash = BlockHash(h256); + assert_eq!(block_hash, decoded); + } + + #[test] + fn rlp() { + rlp_encode_and_decode_test!(BlockHash(H256::random())); + } +} diff --git a/types/src/header.rs b/types/src/header.rs index 8fb730f4bf..6c2ca453b5 100644 --- a/types/src/header.rs +++ b/types/src/header.rs @@ -23,7 +23,7 @@ use ckey::Address; use primitives::{Bytes, H256, U256}; use rlp::*; -use crate::BlockNumber; +use crate::{BlockHash, BlockNumber}; /// Semantic boolean for when a seal/signature is included. pub enum Seal { @@ -37,7 +37,7 @@ pub enum Seal { #[derive(Debug, Clone, PartialEq)] pub struct Header { /// Parent hash. - parent_hash: H256, + parent_hash: BlockHash, /// Block timestamp. timestamp: u64, /// Block number. @@ -68,7 +68,7 @@ impl Default for Header { /// Create a new, default-valued, header. fn default() -> Self { Header { - parent_hash: H256::default(), + parent_hash: H256::default().into(), timestamp: 0, number: 0, author: Default::default(), @@ -94,7 +94,7 @@ impl Header { } /// Get the parent_hash field of the header. - pub fn parent_hash(&self) -> &H256 { + pub fn parent_hash(&self) -> &BlockHash { &self.parent_hash } /// Get the timestamp field of the header. @@ -140,7 +140,7 @@ impl Header { } /// Set the number field of the header. - pub fn set_parent_hash(&mut self, a: H256) { + pub fn set_parent_hash(&mut self, a: BlockHash) { self.parent_hash = a; self.note_dirty(); } @@ -199,14 +199,14 @@ impl Header { } /// Get the hash of this header (blake of the RLP). - pub fn hash(&self) -> H256 { + pub fn hash(&self) -> BlockHash { let mut hash = self.hash.borrow_mut(); match &mut *hash { - Some(h) => *h, + Some(h) => (*h).into(), hash @ &mut None => { let h = self.rlp_blake(&Seal::With); *hash = Some(h); - h + h.into() } } } diff --git a/types/src/lib.rs b/types/src/lib.rs index c46d27d181..95d5b2ae2c 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -27,7 +27,9 @@ extern crate serde_derive; #[cfg(test)] extern crate serde_json; +mod block_hash; mod common_params; + pub mod errors; pub mod header; pub mod transaction; @@ -35,5 +37,7 @@ pub mod util; pub type BlockNumber = u64; pub type ShardId = u16; + +pub use block_hash::BlockHash; pub use common_params::CommonParams; pub use header::Header; From ccf8a14707932182f62b73d287bbee655e9ec545 Mon Sep 17 00:00:00 2001 From: Seulgi Kim Date: Sun, 27 Oct 2019 01:34:04 +0900 Subject: [PATCH 2/3] Distinguish Tracker from H256 And rename some variables that was misnamed as tx_hash. --- core/src/blockchain/blockchain.rs | 6 +- core/src/blockchain/body_db.rs | 54 +++++------ core/src/blockchain/extras.rs | 10 +-- core/src/blockchain/invoice_db.rs | 11 +-- core/src/client/client.rs | 24 +++-- core/src/client/mod.rs | 22 +++-- core/src/client/test_client.rs | 12 +-- core/src/invoice.rs | 3 +- rpc/src/v1/impls/chain.rs | 14 +-- rpc/src/v1/impls/devel.rs | 11 +-- rpc/src/v1/impls/mempool.rs | 3 +- rpc/src/v1/traits/chain.rs | 10 +-- rpc/src/v1/traits/mempool.rs | 6 +- rpc/src/v1/types/action.rs | 12 +-- rpc/src/v1/types/asset_input.rs | 6 +- spec/JSON-RPC.md | 2 +- state/src/impls/shard_level.rs | 66 +++++++------- state/src/impls/test_helper.rs | 36 ++++---- state/src/impls/top_level.rs | 101 +++++++++++---------- state/src/item/asset.rs | 16 ++-- state/src/item/asset_scheme.rs | 6 +- state/src/tests.rs | 6 +- state/src/traits.rs | 6 +- types/src/errors/runtime_error.rs | 12 +-- types/src/errors/syntax_error.rs | 6 +- types/src/lib.rs | 2 + types/src/tracker.rs | 109 +++++++++++++++++++++++ types/src/transaction/action.rs | 4 +- types/src/transaction/asset_out_point.rs | 5 +- types/src/transaction/shard.rs | 26 +++--- types/src/transaction/transaction.rs | 3 +- vm/src/executor.rs | 6 +- vm/tests/common/mod.rs | 7 +- 33 files changed, 379 insertions(+), 244 deletions(-) create mode 100644 types/src/tracker.rs diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index 9e99ff4f9f..3495d1fa2b 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -16,7 +16,7 @@ use std::sync::Arc; -use ctypes::{BlockHash, BlockNumber}; +use ctypes::{BlockHash, BlockNumber, Tracker}; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::RwLock; use primitives::H256; @@ -415,7 +415,7 @@ impl BodyProvider for BlockChain { self.body_db.transaction_address(hash) } - fn transaction_address_by_tracker(&self, tracker: &H256) -> Option { + fn transaction_address_by_tracker(&self, tracker: &Tracker) -> Option { self.body_db.transaction_address_by_tracker(tracker) } @@ -430,7 +430,7 @@ impl InvoiceProvider for BlockChain { self.invoice_db.is_known_error_hint(hash) } - fn error_hints_by_tracker(&self, tracker: &H256) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { self.invoice_db.error_hints_by_tracker(tracker) } diff --git a/core/src/blockchain/body_db.rs b/core/src/blockchain/body_db.rs index 6a016eba18..726091b9b4 100644 --- a/core/src/blockchain/body_db.rs +++ b/core/src/blockchain/body_db.rs @@ -18,7 +18,7 @@ use std::collections::{HashMap, HashSet}; use std::mem; use std::sync::Arc; -use ctypes::BlockHash; +use ctypes::{BlockHash, Tracker}; use kvdb::{DBTransaction, KeyValueDB}; use lru_cache::LruCache; use parking_lot::{Mutex, RwLock}; @@ -40,13 +40,13 @@ pub struct BodyDB { parcel_address_cache: RwLock>, pending_parcel_addresses: RwLock>>, - transaction_address_cache: Mutex>, - pending_transaction_addresses: Mutex>>, + transaction_address_cache: Mutex>, + pending_transaction_addresses: Mutex>>, db: Arc, } -type TransactionHashAndAddress = (H256, TransactionAddresses); +type TrackerAndAddress = (Tracker, TransactionAddresses); impl BodyDB { /// Create new instance of blockchain from given Genesis. @@ -185,7 +185,7 @@ impl BodyDB { fn new_transaction_address_entries( &self, best_block_changed: &BestBlockChanged, - ) -> HashMap> { + ) -> HashMap> { let block_hash = if let Some(best_block_hash) = best_block_changed.new_best_hash() { best_block_hash } else { @@ -197,8 +197,8 @@ impl BodyDB { }; let (removed, added): ( - Box>, - Box>, + Box>, + Box>, ) = match best_block_changed { BestBlockChanged::CanonChainAppended { .. @@ -229,31 +229,31 @@ impl BodyDB { BestBlockChanged::None => return Default::default(), }; - let mut added_addresses: HashMap = Default::default(); - let mut removed_addresses: HashMap = Default::default(); - let mut hashes: HashSet = Default::default(); - for (hash, address) in added { - hashes.insert(hash); - *added_addresses.entry(hash).or_insert_with(Default::default) += address; + let mut added_addresses: HashMap = Default::default(); + let mut removed_addresses: HashMap = Default::default(); + let mut trackers: HashSet = Default::default(); + for (tracker, address) in added { + trackers.insert(tracker); + *added_addresses.entry(tracker).or_insert_with(Default::default) += address; } - for (hash, address) in removed { - hashes.insert(hash); - *removed_addresses.entry(hash).or_insert_with(Default::default) += address; + for (tracker, address) in removed { + trackers.insert(tracker); + *removed_addresses.entry(tracker).or_insert_with(Default::default) += address; } - let mut inserted_address: HashMap = Default::default(); - for hash in hashes.into_iter() { - let address: TransactionAddresses = self.db.read(db::COL_EXTRA, &hash).unwrap_or_default(); - inserted_address.insert(hash, address); + let mut inserted_address: HashMap = Default::default(); + for tracker in trackers.into_iter() { + let address: TransactionAddresses = self.db.read(db::COL_EXTRA, &tracker).unwrap_or_default(); + inserted_address.insert(tracker, address); } - for (hash, removed_address) in removed_addresses.into_iter() { + for (tracker, removed_address) in removed_addresses.into_iter() { *inserted_address - .get_mut(&hash) + .get_mut(&tracker) .expect("inserted addresses are sum of added_addresses and removed_addresses") -= removed_address; } - for (hash, added_address) in added_addresses.into_iter() { + for (tracker, added_address) in added_addresses.into_iter() { *inserted_address - .get_mut(&hash) + .get_mut(&tracker) .expect("inserted addresses are sum of added_addresses and removed_addresses") += added_address; } @@ -286,7 +286,7 @@ pub trait BodyProvider { /// Get the address of parcel with given hash. fn transaction_address(&self, hash: &H256) -> Option; - fn transaction_address_by_tracker(&self, tracker: &H256) -> Option; + fn transaction_address_by_tracker(&self, tracker: &Tracker) -> Option; /// Get the block body (uncles and parcels). fn block_body(&self, hash: &BlockHash) -> Option; @@ -303,7 +303,7 @@ impl BodyProvider for BodyDB { Some(result) } - fn transaction_address_by_tracker(&self, tracker: &H256) -> Option { + fn transaction_address_by_tracker(&self, tracker: &Tracker) -> Option { let addresses = self.db.read_with_cache(db::COL_EXTRA, &mut *self.transaction_address_cache.lock(), tracker)?; addresses.into_iter().next() } @@ -348,7 +348,7 @@ fn parcel_address_entries( fn transaction_address_entries( block_hash: BlockHash, parcel_hashes: impl IntoIterator, -) -> impl Iterator { +) -> impl Iterator { parcel_hashes.into_iter().enumerate().filter_map(move |(parcel_index, parcel)| { parcel.tracker().map(|tracker| { ( diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index a48555d33b..f016b50b55 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -16,7 +16,7 @@ use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; -use ctypes::{BlockHash, BlockNumber}; +use ctypes::{BlockHash, BlockNumber, Tracker}; use primitives::{H256, H264, U256}; use crate::db::Key; @@ -31,8 +31,8 @@ enum ExtrasIndex { BlockHash = 1, /// Parcel address index ParcelAddress = 2, - /// Transaction address index - TransactionAddress = 3, + /// Transaction addresses index + TransactionAddresses = 3, // (Reserved) = 4, // (Reserved) = 5, } @@ -85,11 +85,11 @@ impl Key for H256 { } } -impl Key for H256 { +impl Key for Tracker { type Target = H264; fn key(&self) -> H264 { - with_index(self, ExtrasIndex::TransactionAddress) + with_index(self, ExtrasIndex::TransactionAddresses) } } diff --git a/core/src/blockchain/invoice_db.rs b/core/src/blockchain/invoice_db.rs index 8c14499d90..eb5b82d694 100644 --- a/core/src/blockchain/invoice_db.rs +++ b/core/src/blockchain/invoice_db.rs @@ -18,6 +18,7 @@ use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::Arc; +use ctypes::Tracker; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::RwLock; use primitives::{H256, H264}; @@ -30,7 +31,7 @@ use crate::db::{self, CacheUpdatePolicy, Key, Readable, Writable}; /// **Does not do input data verification.** pub struct InvoiceDB { // tracker -> transaction hashe + error hint - tracker_cache: RwLock>, + tracker_cache: RwLock>, // transaction hash -> error hint hash_cache: RwLock>>, @@ -55,7 +56,7 @@ impl InvoiceDB { &self, batch: &mut DBTransaction, hash: H256, - tracker: Option, + tracker: Option, error_hint: Option, ) { if self.is_known_error_hint(&hash) { @@ -82,7 +83,7 @@ pub trait InvoiceProvider { fn is_known_error_hint(&self, hash: &H256) -> bool; /// Get error hints - fn error_hints_by_tracker(&self, tracker: &H256) -> Vec<(H256, Option)>; + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)>; /// Get error hint fn error_hint(&self, hash: &H256) -> Option; @@ -93,7 +94,7 @@ impl InvoiceProvider for InvoiceDB { self.db.exists_with_cache(db::COL_ERROR_HINT, &self.hash_cache, hash) } - fn error_hints_by_tracker(&self, tracker: &H256) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { self.db .read_with_cache(db::COL_ERROR_HINT, &mut *self.tracker_cache.write(), tracker) .map(|hashes| (*hashes).clone()) @@ -175,7 +176,7 @@ impl Key> for H256 { } } -impl Key for H256 { +impl Key for Tracker { type Target = H264; fn key(&self) -> H264 { diff --git a/core/src/client/client.rs b/core/src/client/client.rs index 846a031ec4..6ea56f56b8 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -28,7 +28,7 @@ use cstate::{ }; use ctimer::{TimeoutHandler, TimerApi, TimerScheduleError, TimerToken}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker}; use cvm::{decode, execute, ChainTimeInfo, ScriptResult, VMConfig}; use hashdb::AsHashDB; use journaldb; @@ -239,7 +239,7 @@ impl Client { } } - fn transaction_addresses(&self, tracker: &H256) -> Option { + fn transaction_addresses(&self, tracker: &Tracker) -> Option { self.block_chain().transaction_address_by_tracker(tracker) } @@ -366,7 +366,13 @@ impl AssetClient for Client { } } - fn get_asset(&self, tracker: H256, index: usize, shard_id: ShardId, id: BlockId) -> TrieResult> { + fn get_asset( + &self, + tracker: Tracker, + index: usize, + shard_id: ShardId, + id: BlockId, + ) -> TrieResult> { if let Some(state) = Client::state_at(&self, id) { Ok(state.asset(shard_id, tracker, index)?) } else { @@ -379,7 +385,7 @@ impl AssetClient for Client { /// It returns None if such an asset never existed in the shard at the given block. fn is_asset_spent( &self, - tracker: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_id: BlockId, @@ -629,7 +635,7 @@ impl BlockChainTrait for Client { self.transaction_address(id).map(|addr| addr.block_hash) } - fn transaction_header(&self, tracker: &H256) -> Option<::encoded::Header> { + fn transaction_header(&self, tracker: &Tracker) -> Option<::encoded::Header> { self.transaction_addresses(tracker).map(|addr| addr.block_hash).and_then(|hash| self.block_header(&hash.into())) } } @@ -796,13 +802,13 @@ impl BlockChainClient for Client { chain.error_hint(hash) } - fn transaction_by_tracker(&self, tracker: &H256) -> Option { + fn transaction_by_tracker(&self, tracker: &Tracker) -> Option { let chain = self.block_chain(); let address = self.transaction_addresses(tracker); address.and_then(|address| chain.transaction(&address)) } - fn error_hints_by_tracker(&self, tracker: &H256) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { let chain = self.block_chain(); chain.error_hints_by_tracker(tracker) } @@ -919,11 +925,11 @@ impl MiningBlockChainClient for Client { } impl ChainTimeInfo for Client { - fn transaction_block_age(&self, tracker: &H256, parent_block_number: BlockNumber) -> Option { + fn transaction_block_age(&self, tracker: &Tracker, parent_block_number: BlockNumber) -> Option { self.transaction_block_number(tracker).map(|block_number| parent_block_number - block_number) } - fn transaction_time_age(&self, tracker: &H256, parent_timestamp: u64) -> Option { + fn transaction_time_age(&self, tracker: &Tracker, parent_timestamp: u64) -> Option { self.transaction_block_timestamp(tracker).map(|block_timestamp| parent_timestamp - block_timestamp) } } diff --git a/core/src/client/mod.rs b/core/src/client/mod.rs index bdbd712716..a9f6520a24 100644 --- a/core/src/client/mod.rs +++ b/core/src/client/mod.rs @@ -37,7 +37,7 @@ use cmerkle::Result as TrieResult; use cnetwork::NodeId; use cstate::{AssetScheme, FindActionHandler, OwnedAsset, StateResult, Text, TopLevelState, TopStateView}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; use primitives::{Bytes, H160, H256, U256}; @@ -75,13 +75,13 @@ pub trait BlockChainTrait { /// Get the hash of block that contains the transaction, if any. fn transaction_block(&self, id: &TransactionId) -> Option; - fn transaction_header(&self, tracker: &H256) -> Option<::encoded::Header>; + fn transaction_header(&self, tracker: &Tracker) -> Option<::encoded::Header>; - fn transaction_block_number(&self, tracker: &H256) -> Option { + fn transaction_block_number(&self, tracker: &Tracker) -> Option { self.transaction_header(tracker).map(|header| header.number()) } - fn transaction_block_timestamp(&self, tracker: &H256) -> Option { + fn transaction_block_timestamp(&self, tracker: &Tracker) -> Option { self.transaction_header(tracker).map(|header| header.timestamp()) } } @@ -253,9 +253,9 @@ pub trait BlockChainClient: Sync + Send + AccountData + BlockChainTrait + Import fn error_hint(&self, hash: &H256) -> Option; /// Get the transaction with given tracker. - fn transaction_by_tracker(&self, tracker: &H256) -> Option; + fn transaction_by_tracker(&self, tracker: &Tracker) -> Option; - fn error_hints_by_tracker(&self, tracker: &H256) -> Vec<(H256, Option)>; + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)>; } /// Result of import block operation. @@ -300,11 +300,17 @@ pub trait DatabaseClient { pub trait AssetClient { fn get_asset_scheme(&self, asset_type: H160, shard_id: ShardId, id: BlockId) -> TrieResult>; - fn get_asset(&self, tracker: H256, index: usize, shard_id: ShardId, id: BlockId) -> TrieResult>; + fn get_asset( + &self, + tracker: Tracker, + index: usize, + shard_id: ShardId, + id: BlockId, + ) -> TrieResult>; fn is_asset_spent( &self, - tracker: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_id: BlockId, diff --git a/core/src/client/test_client.rs b/core/src/client/test_client.rs index 2afaaba3b4..b8f5b9789d 100644 --- a/core/src/client/test_client.rs +++ b/core/src/client/test_client.rs @@ -43,7 +43,7 @@ use cstate::tests::helpers::empty_top_state; use cstate::{FindActionHandler, StateDB, TopLevelState}; use ctimer::{TimeoutHandler, TimerToken}; use ctypes::transaction::{Action, Transaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, Header as BlockHeader}; +use ctypes::{BlockHash, BlockNumber, CommonParams, Header as BlockHeader, Tracker}; use cvm::ChainTimeInfo; use journaldb; use kvdb::KeyValueDB; @@ -459,7 +459,7 @@ impl BlockChainTrait for TestBlockChainClient { None // Simple default. } - fn transaction_header(&self, _tracker: &H256) -> Option<::encoded::Header> { + fn transaction_header(&self, _tracker: &Tracker) -> Option<::encoded::Header> { None } } @@ -597,11 +597,11 @@ impl BlockChainClient for TestBlockChainClient { unimplemented!(); } - fn transaction_by_tracker(&self, _: &H256) -> Option { + fn transaction_by_tracker(&self, _: &Tracker) -> Option { unimplemented!(); } - fn error_hints_by_tracker(&self, _: &H256) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, _: &Tracker) -> Vec<(H256, Option)> { unimplemented!(); } } @@ -611,11 +611,11 @@ impl TimeoutHandler for TestBlockChainClient { } impl ChainTimeInfo for TestBlockChainClient { - fn transaction_block_age(&self, _: &H256, _parent_block_number: BlockNumber) -> Option { + fn transaction_block_age(&self, _: &Tracker, _parent_block_number: BlockNumber) -> Option { Some(0) } - fn transaction_time_age(&self, _: &H256, _parent_timestamp: u64) -> Option { + fn transaction_time_age(&self, _: &Tracker, _parent_timestamp: u64) -> Option { Some(0) } } diff --git a/core/src/invoice.rs b/core/src/invoice.rs index dcfd3d5fc1..ed3d96bc69 100644 --- a/core/src/invoice.rs +++ b/core/src/invoice.rs @@ -14,11 +14,12 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +use ctypes::Tracker; use primitives::H256; #[derive(Clone, Debug, PartialEq)] pub struct Invoice { - pub tracker: Option, + pub tracker: Option, pub hash: H256, pub error: Option, } diff --git a/rpc/src/v1/impls/chain.rs b/rpc/src/v1/impls/chain.rs index 414b44bf47..a7669a32d0 100644 --- a/rpc/src/v1/impls/chain.rs +++ b/rpc/src/v1/impls/chain.rs @@ -26,7 +26,7 @@ use cjson::uint::Uint; use ckey::{public_to_address, NetworkId, PlatformAddress, Public}; use cstate::FindActionHandler; use ctypes::transaction::{Action, ShardTransaction as ShardTransactionType}; -use ctypes::{BlockHash, BlockNumber, ShardId}; +use ctypes::{BlockHash, BlockNumber, ShardId, Tracker}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -86,17 +86,17 @@ where self.contains_transaction(transaction_hash) } - fn get_transaction_by_tracker(&self, tracker: H256) -> Result> { + fn get_transaction_by_tracker(&self, tracker: Tracker) -> Result> { Ok(self.client.transaction_by_tracker(&tracker).map(From::from)) } fn get_asset_scheme_by_tracker( &self, - tracker: H256, + tracker: Tracker, shard_id: ShardId, block_number: Option, ) -> Result> { - let asset_type = Blake::blake(tracker); + let asset_type = Blake::blake(*tracker); self.get_asset_scheme_by_type(asset_type, shard_id, block_number) } @@ -136,7 +136,7 @@ where fn get_asset( &self, - tracker: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_number: Option, @@ -148,13 +148,13 @@ where fn is_asset_spent( &self, - transaction_hash: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_number: Option, ) -> Result> { let block_id = block_number.map(BlockId::Number).unwrap_or(BlockId::Latest); - self.client.is_asset_spent(transaction_hash, index, shard_id, block_id).map_err(errors::transaction_state) + self.client.is_asset_spent(tracker, index, shard_id, block_id).map_err(errors::transaction_state) } fn get_seq(&self, address: PlatformAddress, block_number: Option) -> Result> { diff --git a/rpc/src/v1/impls/devel.rs b/rpc/src/v1/impls/devel.rs index 51e96aa71d..39843ef3ca 100644 --- a/rpc/src/v1/impls/devel.rs +++ b/rpc/src/v1/impls/devel.rs @@ -33,6 +33,7 @@ use csync::BlockSyncEvent; use ctypes::transaction::{ Action, AssetMintOutput, AssetOutPoint, AssetTransferInput, AssetTransferOutput, Transaction, }; +use ctypes::Tracker; use jsonrpc_core::Result; use kvdb::KeyValueDB; use primitives::{H160, H256}; @@ -183,10 +184,10 @@ where } macro_rules! transfer_input { - ($hash:expr, $index:expr, $asset_type:expr, $quantity:expr) => { + ($tracker:expr, $index:expr, $asset_type:expr, $quantity:expr) => { AssetTransferInput { prev_out: AssetOutPoint { - tracker: $hash, + tracker: $tracker, index: $index, asset_type: $asset_type, shard_id: 0, @@ -226,7 +227,7 @@ where } fn asset_type(tx: &Transaction) -> H160 { - Blake::blake(tx.tracker().unwrap()) + Blake::blake(*tx.tracker().unwrap()) } fn tps(count: u64, start_time: PreciseTime, end_time: PreciseTime) -> f64 { @@ -276,7 +277,7 @@ where send_tx(mint_tx, &*self.client, &genesis_keypair)?; fn create_inputs( - transaction_hash: H256, + tracker: Tracker, asset_type: H160, total_amount: u64, count: usize, @@ -284,7 +285,7 @@ where let mut inputs = Vec::new(); let amount = total_amount / (count as u64); for i in 0..(count as usize) { - let input = transfer_input!(transaction_hash, i, asset_type, amount); + let input = transfer_input!(tracker, i, asset_type, amount); inputs.push(input); } inputs diff --git a/rpc/src/v1/impls/mempool.rs b/rpc/src/v1/impls/mempool.rs index e61f9d6928..99cdc5f2af 100644 --- a/rpc/src/v1/impls/mempool.rs +++ b/rpc/src/v1/impls/mempool.rs @@ -19,6 +19,7 @@ use std::sync::Arc; use ccore::{BlockChainClient, MiningBlockChainClient, SignedTransaction}; use cjson::bytes::Bytes; use ckey::{Address, PlatformAddress}; +use ctypes::Tracker; use primitives::H256; use rlp::UntrustedRlp; @@ -59,7 +60,7 @@ where .map(Into::into) } - fn get_transaction_results_by_tracker(&self, tracker: H256) -> Result> { + fn get_transaction_results_by_tracker(&self, tracker: Tracker) -> Result> { Ok(self .client .error_hints_by_tracker(&tracker) diff --git a/rpc/src/v1/traits/chain.rs b/rpc/src/v1/traits/chain.rs index 09b45fc621..3eeb48a230 100644 --- a/rpc/src/v1/traits/chain.rs +++ b/rpc/src/v1/traits/chain.rs @@ -17,7 +17,7 @@ use cjson::scheme::Params; use cjson::uint::Uint; use ckey::{NetworkId, PlatformAddress, Public}; -use ctypes::{BlockHash, BlockNumber, ShardId}; +use ctypes::{BlockHash, BlockNumber, ShardId, Tracker}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -43,13 +43,13 @@ pub trait Chain { /// Gets transaction with given transaction tracker. #[rpc(name = "chain_getTransactionByTracker")] - fn get_transaction_by_tracker(&self, tracker: H256) -> Result>; + fn get_transaction_by_tracker(&self, tracker: Tracker) -> Result>; /// Gets asset scheme with given transaction tracker. #[rpc(name = "chain_getAssetSchemeByTracker")] fn get_asset_scheme_by_tracker( &self, - tracker: H256, + tracker: Tracker, shard_id: ShardId, block_number: Option, ) -> Result>; @@ -71,7 +71,7 @@ pub trait Chain { #[rpc(name = "chain_getAsset")] fn get_asset( &self, - tracker: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_number: Option, @@ -81,7 +81,7 @@ pub trait Chain { #[rpc(name = "chain_isAssetSpent")] fn is_asset_spent( &self, - transaction_hash: H256, + tracker: Tracker, index: usize, shard_id: ShardId, block_number: Option, diff --git a/rpc/src/v1/traits/mempool.rs b/rpc/src/v1/traits/mempool.rs index a7094210e4..dc329f3d07 100644 --- a/rpc/src/v1/traits/mempool.rs +++ b/rpc/src/v1/traits/mempool.rs @@ -15,10 +15,10 @@ // along with this program. If not, see . use cjson::bytes::Bytes; -use primitives::H256; - use ckey::PlatformAddress; +use ctypes::Tracker; use jsonrpc_core::Result; +use primitives::H256; use super::super::types::PendingTransactions; @@ -30,7 +30,7 @@ pub trait Mempool { /// Gets transaction results with given transaction tracker. #[rpc(name = "mempool_getTransactionResultsByTracker")] - fn get_transaction_results_by_tracker(&self, tracker: H256) -> Result>; + fn get_transaction_results_by_tracker(&self, tracker: Tracker) -> Result>; /// Gets a hint to find out why the transaction failed. #[rpc(name = "mempool_getErrorHint")] diff --git a/rpc/src/v1/types/action.rs b/rpc/src/v1/types/action.rs index 02160c57d5..48797bcd0c 100644 --- a/rpc/src/v1/types/action.rs +++ b/rpc/src/v1/types/action.rs @@ -19,7 +19,7 @@ use std::convert::TryFrom; use cjson::uint::Uint; use ckey::{NetworkId, PlatformAddress, Public, Signature}; use ctypes::transaction::{Action as ActionType, AssetMintOutput as AssetMintOutputType}; -use ctypes::ShardId; +use ctypes::{ShardId, Tracker}; use primitives::{Bytes, H160, H256}; use rustc_serialize::hex::{FromHex, ToHex}; @@ -142,7 +142,7 @@ pub enum ActionWithTracker { approvals: Vec, - tracker: H256, + tracker: Tracker, }, #[serde(rename_all = "camelCase")] TransferAsset { @@ -158,7 +158,7 @@ pub enum ActionWithTracker { approvals: Vec, expiration: Option, - tracker: H256, + tracker: Tracker, }, #[serde(rename_all = "camelCase")] ChangeAssetScheme { @@ -173,7 +173,7 @@ pub enum ActionWithTracker { approvals: Vec, - tracker: H256, + tracker: Tracker, }, #[serde(rename_all = "camelCase")] IncreaseAssetSupply { @@ -185,7 +185,7 @@ pub enum ActionWithTracker { approvals: Vec, - tracker: H256, + tracker: Tracker, }, #[serde(rename_all = "camelCase")] @@ -194,7 +194,7 @@ pub enum ActionWithTracker { burn: Box, receiver: PlatformAddress, - tracker: H256, + tracker: Tracker, }, Pay { receiver: PlatformAddress, diff --git a/rpc/src/v1/types/asset_input.rs b/rpc/src/v1/types/asset_input.rs index 0199173600..65fba8832c 100644 --- a/rpc/src/v1/types/asset_input.rs +++ b/rpc/src/v1/types/asset_input.rs @@ -16,13 +16,13 @@ use cjson::uint::Uint; use ctypes::transaction::{AssetOutPoint as AssetOutPointType, AssetTransferInput as AssetTransferInputType, Timelock}; -use ctypes::ShardId; -use primitives::{Bytes, H160, H256}; +use ctypes::{ShardId, Tracker}; +use primitives::{Bytes, H160}; #[derive(Debug, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct AssetOutPoint { - pub tracker: H256, + pub tracker: Tracker, pub index: usize, pub asset_type: H160, pub shard_id: ShardId, diff --git a/spec/JSON-RPC.md b/spec/JSON-RPC.md index 61e2375710..cefee266dc 100644 --- a/spec/JSON-RPC.md +++ b/spec/JSON-RPC.md @@ -994,7 +994,7 @@ Gets the text with given transaction hash. Checks whether an asset is spent or not. ### Params - 1. transaction id: `H256` + 1. tracker: `H256` 2. index: `number` 3. shard id: `number` 4. block number: `number` | `null` diff --git a/state/src/impls/shard_level.rs b/state/src/impls/shard_level.rs index 06703628bd..829c610ffb 100644 --- a/state/src/impls/shard_level.rs +++ b/state/src/impls/shard_level.rs @@ -27,7 +27,7 @@ use ctypes::transaction::{ ShardTransaction, }; use ctypes::util::unexpected::Mismatch; -use ctypes::{BlockNumber, ShardId}; +use ctypes::{BlockNumber, ShardId, Tracker}; use cvm::{decode, execute, ChainTimeInfo, ScriptResult, VMConfig}; use hashdb::AsHashDB; use primitives::{Bytes, H160, H256}; @@ -212,7 +212,7 @@ impl<'db> ShardLevelState<'db> { #[cfg_attr(feature = "cargo-clippy", allow(clippy::too_many_arguments))] fn mint_asset( &mut self, - transaction_tracker: H256, + transaction_tracker: Tracker, metadata: &str, output: &AssetMintOutput, approver: &Option
, @@ -231,7 +231,7 @@ impl<'db> ShardLevelState<'db> { } } - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); if self.asset_scheme(asset_type)?.is_some() { return Err(RuntimeError::AssetSchemeDuplicated { tracker: transaction_tracker, @@ -395,7 +395,7 @@ impl<'db> ShardLevelState<'db> { fn increase_asset_supply( &mut self, - transaction_tracker: H256, + transaction_tracker: Tracker, seq: usize, sender: &Address, approvers: &[Address], @@ -605,7 +605,7 @@ impl<'db> ShardLevelState<'db> { let mut asset_scheme = self.get_asset_scheme_mut(self.shard_id, asset_type)?; asset_scheme.increase_supply(quantity)?; - self.create_asset(*tx_hash, 0, asset_type, *lock_script_hash, parameters.to_vec(), quantity)?; + self.create_asset((*tx_hash).into(), 0, asset_type, *lock_script_hash, parameters.to_vec(), quantity)?; ctrace!(TX, "Created Wrapped CCC on {}:{}:{}", self.shard_id, tx_hash, 0); Ok(()) } @@ -647,7 +647,7 @@ impl<'db> ShardLevelState<'db> { Ok(()) } - fn kill_asset(&mut self, tracker: H256, index: usize) { + fn kill_asset(&mut self, tracker: Tracker, index: usize) { self.cache.remove_asset(&OwnedAssetAddress::new(tracker, index, self.shard_id)); } @@ -675,7 +675,7 @@ impl<'db> ShardLevelState<'db> { pub fn create_asset( &self, - tracker: H256, + tracker: Tracker, index: usize, asset_type: H160, lock_script_hash: H160, @@ -700,7 +700,7 @@ impl<'db> ShardStateView for ShardLevelState<'db> { self.cache.asset_scheme(&AssetSchemeAddress::new(asset_type, self.shard_id), &trie) } - fn asset(&self, tracker: H256, index: usize) -> Result, TrieError> { + fn asset(&self, tracker: Tracker, index: usize) -> Result, TrieError> { let db = self.db.borrow(); let trie = TrieFactory::readonly(db.as_hashdb(), &self.root)?; self.cache.asset(&OwnedAssetAddress::new(tracker, index, self.shard_id), &trie) @@ -783,7 +783,7 @@ impl<'db> ShardStateView for ReadOnlyShardLevelState<'db> { self.cache.asset_scheme(&AssetSchemeAddress::new(asset_type, self.shard_id), &trie) } - fn asset(&self, tracker: H256, index: usize) -> Result, TrieError> { + fn asset(&self, tracker: Tracker, index: usize) -> Result, TrieError> { let db = self.db.borrow(); let trie = TrieFactory::readonly(db.as_hashdb(), &self.root)?; self.cache.asset(&OwnedAssetAddress::new(tracker, index, self.shard_id), &trie) @@ -825,7 +825,7 @@ mod tests { asset_mint!(asset_mint_output!(lock_script_hash, parameters, amount), metadata.clone(), approver: approver); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!(Ok(()), state.apply(&transaction, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ @@ -851,7 +851,7 @@ mod tests { approver: approver ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!(Ok(()), state.apply(&transaction, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -879,7 +879,7 @@ mod tests { ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!(Ok(()), state.apply(&transaction, &sender, &[sender], &[], &get_test_client(), 0, 0)); assert_eq!( @@ -910,7 +910,7 @@ mod tests { let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone(), approver: approver); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -949,7 +949,7 @@ mod tests { let amount = 30; let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone()); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -999,7 +999,7 @@ mod tests { allowed_script_hashes: allowed_script_hashes.clone() ); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1047,7 +1047,7 @@ mod tests { allowed_script_hashes: allowed_script_hashes.clone() ); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1087,7 +1087,7 @@ mod tests { let amount = 30; let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone()); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1124,7 +1124,7 @@ mod tests { let amount = 30; let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone()); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1188,7 +1188,7 @@ mod tests { let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone(), registrar: registrar); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1235,7 +1235,7 @@ mod tests { let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone(), registrar: registrar); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1269,7 +1269,7 @@ mod tests { let amount = 30; let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone()); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1316,12 +1316,12 @@ mod tests { let metadata1 = "metadata".to_string(); let mint1 = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata1.clone()); let mint_tracker1 = mint1.tracker(); - let asset_type1 = Blake::blake(mint_tracker1); + let asset_type1 = Blake::blake(*mint_tracker1); let metadata2 = "metadata2".to_string(); let mint2 = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata2.clone()); let mint_tracker2 = mint2.tracker(); - let asset_type2 = Blake::blake(mint_tracker2); + let asset_type2 = Blake::blake(*mint_tracker2); assert_eq!(Ok(()), state.apply(&mint1, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1381,7 +1381,7 @@ mod tests { let wrap_ccc_tracker = wrap_ccc.tracker(); let asset_type = H160::zero(); - assert_eq!(wrap_ccc_tracker, tx_hash); + assert_eq!(*wrap_ccc_tracker, tx_hash); assert_eq!(Ok(()), state.apply(&wrap_ccc, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ @@ -1417,7 +1417,7 @@ mod tests { let wrap_ccc = asset_wrap_ccc!(tx_hash, asset_wrap_ccc_output!(lock_script_hash, amount)); let wrap_ccc_tracker = wrap_ccc.tracker(); - assert_eq!(wrap_ccc_tracker, tx_hash); + assert_eq!(*wrap_ccc_tracker, tx_hash); assert_eq!(Ok(()), state.apply(&wrap_ccc, &sender, &[sender], &[], &get_test_client(), 0, 0)); let asset_type = H160::zero(); @@ -1478,7 +1478,7 @@ mod tests { let amount = 30; let mint = asset_mint!(asset_mint_output!(lock_script_hash, supply: amount), metadata.clone()); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1550,7 +1550,7 @@ mod tests { approver: approver ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!(Ok(()), state.apply(&transaction, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1578,7 +1578,7 @@ mod tests { asset_mint!(asset_mint_output!(lock_script_hash, parameters: parameters), metadata, approver: approver); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!( Err(StateError::Runtime(RuntimeError::InsufficientPermission)), @@ -1612,7 +1612,7 @@ mod tests { ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); check_shard_level_state!(state, [ (scheme: (asset_type)), @@ -1648,7 +1648,7 @@ mod tests { ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); check_shard_level_state!(state, [ (scheme: (asset_type)), @@ -1681,7 +1681,7 @@ mod tests { ); let transaction_tracker = transaction.tracker(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); assert_eq!(Ok(()), state.apply(&transaction, &sender, &[], &[], &get_test_client(), 0, 0)); @@ -1710,7 +1710,7 @@ mod tests { ); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); @@ -1757,7 +1757,7 @@ mod tests { ); let mint_tracker = mint.tracker(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint, &sender, &[sender], &[], &get_test_client(), 0, 0)); diff --git a/state/src/impls/test_helper.rs b/state/src/impls/test_helper.rs index 78544c9b71..a05729e7c2 100644 --- a/state/src/impls/test_helper.rs +++ b/state/src/impls/test_helper.rs @@ -641,45 +641,45 @@ macro_rules! check_shard_level_state { check_shard_level_state!($state, [$($x),*]); }; - ($state:expr, [(asset: ($tx_hash:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { - let asset = $state.asset($tx_hash, $index) - .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tx_hash, $index)) - .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tx_hash, $index)); + ($state:expr, [(asset: ($tracker:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { + let asset = $state.asset($tracker, $index) + .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tracker, $index)) + .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tracker, $index)); assert_eq!(&$asset_type, asset.asset_type()); assert_eq!($quantity, asset.quantity()); check_shard_level_state!($state, [$($x),*]); }; - ($state:expr, [(asset: ($tx_hash:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { - let asset = $state.asset($tx_hash, $index) - .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tx_hash, $index)) - .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tx_hash, $index)); + ($state:expr, [(asset: ($tracker:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { + let asset = $state.asset($tracker, $index) + .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tracker, $index)) + .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tracker, $index)); assert_eq!(&$asset_type, asset.asset_type()); assert_eq!($quantity, asset.quantity()); check_shard_level_state!($state, [$($x),*]); }; - ($state:expr, [(asset: ($tx_hash:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { - let asset = $state.asset($tx_hash, $index) - .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tx_hash, $index)) - .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tx_hash, $index)); + ($state:expr, [(asset: ($tracker:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr }) $(,$x:tt)*]) => { + let asset = $state.asset($tracker, $index) + .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tracker, $index)) + .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tracker, $index)); assert_eq!(&$asset_type, asset.asset_type()); assert_eq!($quantity, asset.quantity()); check_shard_level_state!($state, [$($x),*]); }; - ($state:expr, [(asset: ($tx_hash:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr, lock_script_hash: $lock_script_hash:expr }) $(,$x:tt)*]) => { - let asset = $state.asset($tx_hash, $index) - .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tx_hash, $index)) - .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tx_hash, $index)); + ($state:expr, [(asset: ($tracker:expr, $index:expr) => { asset_type: $asset_type:expr, quantity: $quantity:expr, lock_script_hash: $lock_script_hash:expr }) $(,$x:tt)*]) => { + let asset = $state.asset($tracker, $index) + .expect(&format!("Cannot read Asset from {}:{}:{}", $state.shard_id(), $tracker, $index)) + .expect(&format!("Asset for {}:{}:{} not exist", $state.shard_id(), $tracker, $index)); assert_eq!(&$asset_type, asset.asset_type()); assert_eq!($quantity, asset.quantity()); assert_eq!(&$lock_script_hash, asset.lock_script_hash()); check_shard_level_state!($state, [$($x),*]); }; - ($state:expr, [(asset: ($tx_hash:expr, $index:expr)) $(,$x:tt)*]) => { - assert_eq!(Ok(None), $state.asset($tx_hash, $index)); + ($state:expr, [(asset: ($tracker:expr, $index:expr)) $(,$x:tt)*]) => { + assert_eq!(Ok(None), $state.asset($tracker, $index)); check_shard_level_state!($state, [$($x),*]); }; diff --git a/state/src/impls/top_level.rs b/state/src/impls/top_level.rs index 954c9ec527..50bdc9befc 100644 --- a/state/src/impls/top_level.rs +++ b/state/src/impls/top_level.rs @@ -46,6 +46,8 @@ use ctypes::transaction::{ Action, AssetOutPoint, AssetTransferInput, AssetWrapCCCOutput, ShardTransaction, Transaction, }; use ctypes::util::unexpected::Mismatch; +#[cfg(test)] +use ctypes::Tracker; use ctypes::{BlockNumber, CommonParams, ShardId}; use cvm::ChainTimeInfo; use hashdb::AsHashDB; @@ -745,7 +747,7 @@ impl TopLevelState { fn create_asset( &mut self, shard_id: ShardId, - tx_hash: H256, + tracker: Tracker, index: usize, asset_type: H160, lock_script_hash: H160, @@ -756,7 +758,7 @@ impl TopLevelState { Some(shard_root) => { let mut shard_cache = self.shard_caches.entry(shard_id).or_default(); let state = ShardLevelState::from_existing(shard_id, &mut self.db, shard_root, &mut shard_cache)?; - state.create_asset(tx_hash, index, asset_type, lock_script_hash, parameters, amount)?; + state.create_asset(tracker, index, asset_type, lock_script_hash, parameters, amount)?; Ok(true) } None => Ok(false), @@ -1477,7 +1479,7 @@ mod tests_tx { let (master_account, master_public, _) = address(); let (regular_account, regular_public, _) = address(); let type_of_wccc = H160::zero(); - let tracker = H256::random(); + let tracker = H256::random().into(); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let shard_id = 0; set_top_level_state!(state, [ @@ -1617,13 +1619,13 @@ mod tests_tx { let (_, regular_public, _) = address(); let shard_id = 0x0; - let mint_tracker = H256::random(); + let mint_tracker = Tracker::from(H256::random()); let mut state = get_temp_state(); let metadata = "metadata".to_string(); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let amount = 30; - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); set_top_level_state!(state, [ (account: sender => balance: 25), @@ -1653,13 +1655,13 @@ mod tests_tx { let (_, regular_public, regular_private) = address(); let shard_id = 0x0; - let mint_tracker = H256::random(); + let mint_tracker = Tracker::from(H256::random()); let mut state = get_temp_state(); let metadata = "metadata".to_string(); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let amount = 30; - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); set_top_level_state!(state, [ (account: sender => balance: 25), @@ -1813,7 +1815,7 @@ mod tests_tx { approver: approver ); let transaction_tracker = transaction.tracker().unwrap(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 11, transaction); assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); @@ -1849,7 +1851,7 @@ mod tests_tx { approver: approver ); let transaction_tracker = transaction.tracker().unwrap(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 5, transaction); assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); @@ -1880,7 +1882,7 @@ mod tests_tx { let mint = mint_asset!(Box::new(asset_mint_output!(lock_script_hash, supply: amount)), metadata.clone()); let mint_tracker = mint.tracker().unwrap(); let mint_tx = transaction!(fee: 20, mint); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); assert_eq!(Ok(()), state.apply(&mint_tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); @@ -1991,11 +1993,13 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (tx_hash, 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); - let unwrap_ccc_tx = - unwrap_ccc!(asset_transfer_input!(asset_out_point!(tx_hash, 0, asset_type, 30), vec![0x01]), receiver); + let unwrap_ccc_tx = unwrap_ccc!( + asset_transfer_input!(asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), vec![0x01]), + receiver + ); let tx = transaction!(seq: 1, fee: 11, unwrap_ccc_tx); assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); @@ -2003,7 +2007,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 100 - 11 - 30 - 11)), (account: receiver => (seq: 0, balance: 30)), - (asset: (tx_hash, 0, 0)) + (asset: (Tracker::from(tx_hash), 0, 0)) ]); } @@ -2033,12 +2037,15 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (tx_hash, 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); let failed_lock_script = vec![0x02]; let unwrap_ccc_tx = unwrap_ccc!( - asset_transfer_input!(asset_out_point!(tx_hash, 0, asset_type, 30), failed_lock_script.clone()), + asset_transfer_input!( + asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), + failed_lock_script.clone() + ), receiver ); let tx = transaction!(seq: 1, fee: 11, unwrap_ccc_tx); @@ -2055,7 +2062,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (tx_hash, 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); } @@ -2116,13 +2123,13 @@ mod tests_tx { let asset_type = H160::zero(); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 30 - 11)), - (asset: (tx_hash, 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); let lock_script_hash_burn = H160::from("ca5d3fa0a6887285ef6aa85cb12960a2b6706e00"); let random_lock_script_hash = H160::random(); let transfer_tx = transfer_asset!( - inputs: asset_transfer_inputs![(asset_out_point!(tx_hash, 0, asset_type, 30), vec![0x30, 0x01])], + inputs: asset_transfer_inputs![(asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), vec![0x30, 0x01])], asset_transfer_outputs![ (lock_script_hash, vec![vec![1]], asset_type, 10), (lock_script_hash_burn, asset_type, 5), @@ -2137,7 +2144,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 100 - 30 - 11 - 11)), - (asset: (tx_hash, 0, 0)), + (asset: (Tracker::from(tx_hash), 0, 0)), (asset: (transfer_tx_tracker, 0, 0) => { asset_type: asset_type, quantity: 10 }), (asset: (transfer_tx_tracker, 1, 0) => { asset_type: asset_type, quantity: 5 }), (asset: (transfer_tx_tracker, 2, 0) => { asset_type: asset_type, quantity: 15 }) @@ -2279,7 +2286,7 @@ mod tests_tx { let shard_id = 3; check_top_level_state!(state, [ - (asset: (H256::random(), 0, shard_id)) + (asset: (Tracker::from(H256::random()), 0, shard_id)) ]); } @@ -2413,7 +2420,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 20 - 5)), (shard: 0 => owners: vec![sender], users: vec![]), - (asset: (H256::random(), 0, invalid_shard_id)) + (asset: (Tracker::from(H256::random()), 0, invalid_shard_id)) ]); } @@ -2435,7 +2442,7 @@ mod tests_tx { check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 20 - 5)), (shard: 0 => owners: vec![sender], users: users), - (asset: (H256::random(), 0, invalid_shard_id)) + (asset: (Tracker::from(H256::random()), 0, invalid_shard_id)) ]); } @@ -2484,7 +2491,7 @@ mod tests_tx { let asset_type = H160::zero(); let transfer = transfer_asset!( inputs: - asset_transfer_inputs![(asset_out_point!(H256::random(), 0, asset_type, shard_id, 30), vec![ + asset_transfer_inputs![(asset_out_point!(Tracker::from(H256::random()), 0, asset_type, shard_id, 30), vec![ 0x30, 0x01 ])], asset_transfer_outputs![ @@ -2664,7 +2671,7 @@ mod tests_tx { let mint = mint_asset!(Box::new(asset_mint_output!(lock_script_hash, parameters, amount)), metadata.clone()); let mint_tracker = mint.tracker().unwrap(); - let asset_type = Blake::blake(mint_tracker); + let asset_type = Blake::blake(*mint_tracker); let tx = transaction!(fee: 20, mint); @@ -2742,10 +2749,10 @@ mod tests_tx { fn transfer_failed_if_the_input_amount_is_not_valid() { let shard_id = 0; - let mint_tracker1 = H256::random(); - let mint_tracker2 = H256::random(); - let asset_type1 = Blake::blake(mint_tracker1); - let asset_type2 = Blake::blake(mint_tracker2); + let mint_tracker1 = Tracker::from(H256::random()); + let mint_tracker2 = Tracker::from(H256::random()); + let asset_type1 = Blake::blake(*mint_tracker1); + let asset_type2 = Blake::blake(*mint_tracker2); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); @@ -2806,10 +2813,10 @@ mod tests_tx { let shard3 = 3; let shard4 = 4; - let mint_tracker3 = H256::random(); - let mint_tracker4 = H256::random(); - let asset_type3 = Blake::blake(mint_tracker3); - let asset_type4 = Blake::blake(mint_tracker4); + let mint_tracker3 = Tracker::from(H256::random()); + let mint_tracker4 = Tracker::from(H256::random()); + let asset_type3 = Blake::blake(*mint_tracker3); + let asset_type4 = Blake::blake(*mint_tracker4); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let (sender, signer_public, _) = address(); @@ -2873,10 +2880,10 @@ mod tests_tx { let shard3 = 3; let shard4 = 4; - let mint_tracker3 = H256::random(); - let mint_tracker4 = H256::random(); - let asset_type3 = Blake::blake(mint_tracker3); - let asset_type4 = Blake::blake(mint_tracker4); + let mint_tracker3 = Tracker::from(H256::random()); + let mint_tracker4 = Tracker::from(H256::random()); + let asset_type3 = Blake::blake(*mint_tracker3); + let asset_type4 = Blake::blake(*mint_tracker4); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let (sender, signer_public, _) = address(); @@ -2940,10 +2947,10 @@ mod tests_tx { let shard3 = 3; let shard4 = 4; - let mint_tracker3 = H256::random(); - let mint_tracker4 = H256::random(); - let asset_type3 = Blake::blake(mint_tracker3); - let asset_type4 = Blake::blake(mint_tracker4); + let mint_tracker3 = Tracker::from(H256::random()); + let mint_tracker4 = Tracker::from(H256::random()); + let asset_type3 = Blake::blake(*mint_tracker3); + let asset_type4 = Blake::blake(*mint_tracker4); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let (sender, signer_public, _) = address(); @@ -3014,10 +3021,10 @@ mod tests_tx { let shard3 = 3; let shard4 = 4; - let mint_tracker3 = H256::random(); - let mint_tracker4 = H256::random(); - let asset_type3 = Blake::blake(mint_tracker3); - let asset_type4 = Blake::blake(mint_tracker4); + let mint_tracker3 = Tracker::from(H256::random()); + let mint_tracker4 = Tracker::from(H256::random()); + let asset_type3 = Blake::blake(*mint_tracker3); + let asset_type4 = Blake::blake(*mint_tracker4); let lock_script_hash = H160::from("0xb042ad154a3359d276835c903587ebafefea22af"); let (sender, signer_public, _) = address(); @@ -3193,7 +3200,7 @@ mod tests_tx { approver: regular_account ); let transaction_tracker = transaction.tracker().unwrap(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 11, transaction); assert_eq!( @@ -3236,7 +3243,7 @@ mod tests_tx { registrar: regular_account ); let transaction_tracker = transaction.tracker().unwrap(); - let asset_type = Blake::blake(transaction_tracker); + let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 11, transaction); assert_eq!( diff --git a/state/src/item/asset.rs b/state/src/item/asset.rs index 3b7aabf824..1f1cbd8954 100644 --- a/state/src/item/asset.rs +++ b/state/src/item/asset.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::ShardId; +use ctypes::{ShardId, Tracker}; use primitives::{Bytes, H160, H256}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -152,11 +152,11 @@ pub struct OwnedAssetAddress(H256); impl_address!(SHARD, OwnedAssetAddress, PREFIX); impl OwnedAssetAddress { - pub fn new(transaction_tracker: H256, index: usize, shard_id: ShardId) -> Self { + pub fn new(tracker: Tracker, index: usize, shard_id: ShardId) -> Self { debug_assert_eq!(::std::mem::size_of::(), ::std::mem::size_of::()); let index = index as u64; - Self::from_hash_with_shard_id(transaction_tracker, index, shard_id) + Self::from_hash_with_shard_id(*tracker, index, shard_id) } } @@ -168,7 +168,7 @@ mod tests { #[test] fn asset_from_address() { - let tx_id = { + let tracker = { let mut address; 'address: loop { address = H256::random(); @@ -182,11 +182,11 @@ mod tests { } break } - address + address.into() }; let shard_id = 0xBEEF; - let address1 = OwnedAssetAddress::new(tx_id, 0, shard_id); - let address2 = OwnedAssetAddress::new(tx_id, 1, shard_id); + let address1 = OwnedAssetAddress::new(tracker, 0, shard_id); + let address2 = OwnedAssetAddress::new(tracker, 1, shard_id); assert_ne!(address1, address2); assert_eq!(address1[0..2], [PREFIX, 0]); assert_eq!(address1[2..4], [0xBE, 0xEF]); // shard id @@ -229,7 +229,7 @@ mod tests { #[test] fn shard_id() { - let origin = H256::random(); + let origin = H256::random().into(); let shard_id = 0xCAA; let asset_address = OwnedAssetAddress::new(origin, 2, shard_id); assert_eq!(shard_id, asset_address.shard_id()); diff --git a/state/src/item/asset_scheme.rs b/state/src/item/asset_scheme.rs index 80fdb7972d..d1194f4a38 100644 --- a/state/src/item/asset_scheme.rs +++ b/state/src/item/asset_scheme.rs @@ -17,7 +17,7 @@ use ccrypto::Blake; use ckey::Address; use ctypes::errors::RuntimeError; -use ctypes::ShardId; +use ctypes::{ShardId, Tracker}; use primitives::{H160, H256}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -219,8 +219,8 @@ impl AssetSchemeAddress { Self::from_hash_with_shard_id(asset_type, index, shard_id) } - pub fn new_from_tracker(tracker: H256, shard_id: ShardId) -> Self { - let asset_type = Blake::blake(tracker); + pub fn new_from_tracker(tracker: Tracker, shard_id: ShardId) -> Self { + let asset_type = Blake::blake(*tracker); Self::new(asset_type, shard_id) } } diff --git a/state/src/tests.rs b/state/src/tests.rs index 3de024e8e2..a911ab9248 100644 --- a/state/src/tests.rs +++ b/state/src/tests.rs @@ -18,7 +18,7 @@ pub mod helpers { use std::sync::Arc; use cmerkle::TrieFactory; - use ctypes::BlockNumber; + use ctypes::{BlockNumber, Tracker}; use cvm::ChainTimeInfo; use hashdb::AsHashDB; use kvdb::KeyValueDB; @@ -33,11 +33,11 @@ pub mod helpers { pub struct TestClient {} impl ChainTimeInfo for TestClient { - fn transaction_block_age(&self, _: &H256, _parent_block_number: BlockNumber) -> Option { + fn transaction_block_age(&self, _: &Tracker, _parent_block_number: BlockNumber) -> Option { Some(0) } - fn transaction_time_age(&self, _: &H256, _parent_block_timestamp: u64) -> Option { + fn transaction_time_age(&self, _: &Tracker, _parent_block_timestamp: u64) -> Option { Some(0) } } diff --git a/state/src/traits.rs b/state/src/traits.rs index 164e2e53fa..f54448e4c1 100644 --- a/state/src/traits.rs +++ b/state/src/traits.rs @@ -17,7 +17,7 @@ use ckey::{public_to_address, Address, Public, Signature}; use cmerkle::Result as TrieResult; use ctypes::transaction::ShardTransaction; -use ctypes::{BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockNumber, CommonParams, ShardId, Tracker}; use cvm::ChainTimeInfo; use primitives::{Bytes, H160, H256}; @@ -116,7 +116,7 @@ pub trait TopStateView { } /// Get the asset. - fn asset(&self, shard_id: ShardId, tracker: H256, index: usize) -> TrieResult> { + fn asset(&self, shard_id: ShardId, tracker: Tracker, index: usize) -> TrieResult> { match self.shard_state(shard_id)? { None => Ok(None), Some(state) => state.asset(tracker, index), @@ -132,7 +132,7 @@ pub trait ShardStateView { /// Get the asset scheme. fn asset_scheme(&self, asset_type: H160) -> TrieResult>; /// Get the asset. - fn asset(&self, tracker: H256, index: usize) -> TrieResult>; + fn asset(&self, tracker: Tracker, index: usize) -> TrieResult>; } pub trait ShardState { diff --git a/types/src/errors/runtime_error.rs b/types/src/errors/runtime_error.rs index 63d0fc34de..2368a95fa0 100644 --- a/types/src/errors/runtime_error.rs +++ b/types/src/errors/runtime_error.rs @@ -17,12 +17,12 @@ use std::fmt::{Display, Formatter, Result as FormatResult}; use ckey::Address; -use primitives::{H160, H256}; +use primitives::H160; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use super::TaggedRlp; use crate::util::unexpected::Mismatch; -use crate::ShardId; +use crate::{ShardId, Tracker}; #[derive(Debug, PartialEq, Clone, Eq, Serialize)] #[serde(tag = "type", content = "content")] @@ -30,11 +30,11 @@ pub enum Error { /// Desired input asset not found AssetNotFound { shard_id: ShardId, - tracker: H256, + tracker: Tracker, index: usize, }, AssetSchemeDuplicated { - tracker: H256, + tracker: Tracker, shard_id: ShardId, }, /// Desired input asset scheme not found @@ -54,7 +54,7 @@ pub enum Error { /// Script execution result is `Fail` FailedToUnlock { shard_id: ShardId, - tracker: H256, + tracker: Tracker, index: usize, reason: UnlockFailureReason, }, @@ -69,7 +69,7 @@ pub enum Error { InsufficientPermission, InvalidAssetQuantity { shard_id: ShardId, - tracker: H256, + tracker: Tracker, index: usize, expected: u64, got: u64, diff --git a/types/src/errors/syntax_error.rs b/types/src/errors/syntax_error.rs index 6f8c246f00..c9924737f7 100644 --- a/types/src/errors/syntax_error.rs +++ b/types/src/errors/syntax_error.rs @@ -17,18 +17,18 @@ use std::fmt::{Display, Formatter, Result as FormatResult}; use ckey::NetworkId; -use primitives::{H160, H256}; +use primitives::H160; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use super::TaggedRlp; -use crate::ShardId; +use crate::{ShardId, Tracker}; #[derive(Debug, PartialEq, Clone, Eq, Serialize)] #[serde(tag = "type", content = "content")] pub enum Error { /// There are burn/inputs that shares same previous output DuplicatedPreviousOutput { - tracker: H256, + tracker: Tracker, index: usize, }, EmptyShardOwners(ShardId), diff --git a/types/src/lib.rs b/types/src/lib.rs index 95d5b2ae2c..cb3229e222 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -29,6 +29,7 @@ extern crate serde_json; mod block_hash; mod common_params; +mod tracker; pub mod errors; pub mod header; @@ -41,3 +42,4 @@ pub type ShardId = u16; pub use block_hash::BlockHash; pub use common_params::CommonParams; pub use header::Header; +pub use tracker::Tracker; diff --git a/types/src/tracker.rs b/types/src/tracker.rs new file mode 100644 index 0000000000..ac59019a67 --- /dev/null +++ b/types/src/tracker.rs @@ -0,0 +1,109 @@ +// Copyright 2019 Kodebox, Inc. +// This file is part of CodeChain. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +use std::fmt::{self, Display, Formatter}; +use std::ops::Deref; + +use primitives::H256; +use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; + + +#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Debug, Deserialize, Serialize)] +pub struct Tracker(H256); + +impl From for Tracker { + fn from(h: H256) -> Self { + Self(h) + } +} + +impl Deref for Tracker { + type Target = H256; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Tracker { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + +impl Encodable for Tracker { + fn rlp_append(&self, s: &mut RlpStream) { + self.0.rlp_append(s); + } +} + +impl Decodable for Tracker { + fn decode(rlp: &UntrustedRlp) -> Result { + Ok(H256::decode(rlp)?.into()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + use rlp::{self, rlp_encode_and_decode_test}; + + use super::*; + + #[test] + fn hash_of_tracker_and_h256_are_the_same() { + let h256 = H256::random(); + let tracker = Tracker(h256); + + let mut hasher_of_h256 = DefaultHasher::new(); + let mut hasher_of_tracker = DefaultHasher::new(); + + h256.hash(&mut hasher_of_h256); + tracker.hash(&mut hasher_of_tracker); + + assert_eq!(hasher_of_h256.finish(), hasher_of_tracker.finish()); + } + + #[test] + fn rlp_of_tracker_can_be_decoded_to_h256() { + let h256 = H256::random(); + let tracker = Tracker(h256); + + let encoded = rlp::encode(&tracker); + let decoded = rlp::decode(&*encoded); + + assert_eq!(h256, decoded); + } + + #[test] + fn rlp_of_h256_can_be_decoded_to_tracker() { + let h256 = H256::random(); + + let encoded = rlp::encode(&h256); + let decoded = rlp::decode(&*encoded); + + let tracker = Tracker(h256); + assert_eq!(tracker, decoded); + } + + #[test] + fn rlp() { + rlp_encode_and_decode_test!(Tracker(H256::random())); + } +} diff --git a/types/src/transaction/action.rs b/types/src/transaction/action.rs index 22e321af63..66884afdc2 100644 --- a/types/src/transaction/action.rs +++ b/types/src/transaction/action.rs @@ -23,7 +23,7 @@ use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use crate::errors::SyntaxError; use crate::transaction::{AssetMintOutput, AssetTransferInput, AssetTransferOutput, ShardTransaction}; -use crate::{CommonParams, ShardId}; +use crate::{CommonParams, ShardId, Tracker}; const PAY: u8 = 0x02; const SET_REGULAR_KEY: u8 = 0x03; @@ -158,7 +158,7 @@ impl Action { } } - pub fn tracker(&self) -> Option { + pub fn tracker(&self) -> Option { self.asset_transaction().map(|tx| tx.tracker()) } diff --git a/types/src/transaction/asset_out_point.rs b/types/src/transaction/asset_out_point.rs index b11c6d2244..be72d0ce14 100644 --- a/types/src/transaction/asset_out_point.rs +++ b/types/src/transaction/asset_out_point.rs @@ -14,13 +14,14 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use primitives::{H160, H256}; +use primitives::H160; use crate::ShardId; +use crate::Tracker; #[derive(Debug, Clone, Eq, PartialEq, RlpDecodable, RlpEncodable)] pub struct AssetOutPoint { - pub tracker: H256, + pub tracker: Tracker, pub index: usize, pub asset_type: H160, pub shard_id: ShardId, diff --git a/types/src/transaction/shard.rs b/types/src/transaction/shard.rs index b417d49fe4..f10032c9a0 100644 --- a/types/src/transaction/shard.rs +++ b/types/src/transaction/shard.rs @@ -21,7 +21,7 @@ use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use super::{AssetMintOutput, AssetTransferInput, AssetTransferOutput, HashingError, PartialHashing}; use crate::util::tag::Tag; -use crate::ShardId; +use crate::{ShardId, Tracker}; /// Shard Transaction type. #[derive(Debug, Clone, PartialEq, Eq)] @@ -79,15 +79,15 @@ pub struct AssetWrapCCCOutput { } impl ShardTransaction { - pub fn tracker(&self) -> H256 { + pub fn tracker(&self) -> Tracker { if let ShardTransaction::WrapCCC { tx_hash, .. } = self { - return *tx_hash + return (*tx_hash).into() } - blake256(&*self.rlp_bytes()) + blake256(&*self.rlp_bytes()).into() } pub fn network_id(&self) -> NetworkId { @@ -561,7 +561,7 @@ mod tests { assert!(is_input_and_output_consistent( &[AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type, shard_id: 0, @@ -598,7 +598,7 @@ mod tests { &[ AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type: asset_type1, shard_id: 0, @@ -610,7 +610,7 @@ mod tests { }, AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type: asset_type2, shard_id: 0, @@ -657,7 +657,7 @@ mod tests { &[ AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type: asset_type1, shard_id: 0, @@ -669,7 +669,7 @@ mod tests { }, AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type: asset_type2, shard_id: 0, @@ -725,7 +725,7 @@ mod tests { assert!(!is_input_and_output_consistent( &[AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type, shard_id: 0, @@ -748,7 +748,7 @@ mod tests { assert!(!is_input_and_output_consistent( &[AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type, shard_id: 0, @@ -777,7 +777,7 @@ mod tests { assert!(!is_input_and_output_consistent( &[AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type, shard_id: 0, @@ -825,7 +825,7 @@ mod tests { burns: vec![], inputs: vec![AssetTransferInput { prev_out: AssetOutPoint { - tracker: H256::random(), + tracker: H256::random().into(), index: 0, asset_type: H160::random(), shard_id: 0, diff --git a/types/src/transaction/transaction.rs b/types/src/transaction/transaction.rs index c3cc26e3ba..c5a9c54aab 100644 --- a/types/src/transaction/transaction.rs +++ b/types/src/transaction/transaction.rs @@ -21,6 +21,7 @@ use rlp::RlpStream; use super::Action; use super::{AssetWrapCCCOutput, ShardTransaction}; +use crate::Tracker; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Transaction { @@ -51,7 +52,7 @@ impl Transaction { blake256(stream.as_raw()) } - pub fn tracker(&self) -> Option { + pub fn tracker(&self) -> Option { let shard_tx = match self.action.clone() { Action::WrapCCC { shard_id, diff --git a/vm/src/executor.rs b/vm/src/executor.rs index ab03140cd7..22a192fdfe 100644 --- a/vm/src/executor.rs +++ b/vm/src/executor.rs @@ -18,7 +18,7 @@ use ccrypto::{blake256, keccak256, ripemd160, sha256, Blake}; use ckey::{verify, Public, Signature, SIGNATURE_LENGTH}; use ctypes::transaction::{AssetTransferInput, HashingError, PartialHashing}; use ctypes::util::tag::Tag; -use ctypes::BlockNumber; +use ctypes::{BlockNumber, Tracker}; use primitives::{H160, H256}; @@ -371,10 +371,10 @@ fn check_multi_sig(tx_hash: &H256, mut pubkey: Vec, mut signatures: Vec< pub trait ChainTimeInfo { /// Get the block height of the transaction. - fn transaction_block_age(&self, tracker: &H256, parent_block_number: BlockNumber) -> Option; + fn transaction_block_age(&self, tracker: &Tracker, parent_block_number: BlockNumber) -> Option; /// Get the how many seconds elapsed since transaction is confirmed, according to block timestamp. - fn transaction_time_age(&self, tracker: &H256, parent_timestamp: u64) -> Option; + fn transaction_time_age(&self, tracker: &Tracker, parent_timestamp: u64) -> Option; } #[cfg(test)] diff --git a/vm/tests/common/mod.rs b/vm/tests/common/mod.rs index 400480733a..2ddc5dc9be 100644 --- a/vm/tests/common/mod.rs +++ b/vm/tests/common/mod.rs @@ -14,9 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::BlockNumber; +use ctypes::{BlockNumber, Tracker}; use cvm::ChainTimeInfo; -use primitives::H256; pub struct TestClient { block_age: Option, @@ -39,11 +38,11 @@ impl Default for TestClient { } impl ChainTimeInfo for TestClient { - fn transaction_block_age(&self, _: &H256, _parent_block_number: BlockNumber) -> Option { + fn transaction_block_age(&self, _: &Tracker, _parent_block_number: BlockNumber) -> Option { self.block_age } - fn transaction_time_age(&self, _: &H256, _parent_timestamp: u64) -> Option { + fn transaction_time_age(&self, _: &Tracker, _parent_timestamp: u64) -> Option { self.time_age } } From f9afdd7a85c5416fa9a1d3bdf4d99798c62d0ef8 Mon Sep 17 00:00:00 2001 From: Seulgi Kim Date: Sun, 27 Oct 2019 02:20:03 +0900 Subject: [PATCH 3/3] Distinguish TxHash from H256 --- core/src/block.rs | 6 +- core/src/blockchain/blockchain.rs | 10 +- core/src/blockchain/body_db.rs | 22 +-- core/src/blockchain/extras.rs | 10 +- core/src/blockchain/invoice_db.rs | 28 ++-- core/src/client/chain_notify.rs | 5 +- core/src/client/client.rs | 12 +- core/src/client/mod.rs | 10 +- core/src/client/test_client.rs | 8 +- core/src/consensus/tendermint/worker.rs | 2 +- core/src/encoded.rs | 6 +- core/src/invoice.rs | 5 +- core/src/miner/mem_pool.rs | 13 +- core/src/miner/mem_pool_types.rs | 7 +- core/src/miner/miner.rs | 8 +- core/src/miner/mod.rs | 6 +- core/src/transaction.rs | 21 ++- core/src/types/ids.rs | 9 +- core/src/views/block.rs | 7 +- core/src/views/body.rs | 7 +- rpc/src/v1/impls/chain.rs | 14 +- rpc/src/v1/impls/devel.rs | 4 +- rpc/src/v1/impls/mempool.rs | 7 +- rpc/src/v1/traits/chain.rs | 14 +- rpc/src/v1/traits/mempool.rs | 7 +- rpc/src/v1/types/action.rs | 8 +- rpc/src/v1/types/mod.rs | 5 +- rpc/src/v1/types/transaction.rs | 5 +- state/src/impls/shard_level.rs | 10 +- state/src/impls/top_level.rs | 191 +++++++++++++----------- state/src/item/metadata.rs | 8 +- state/src/traits.rs | 10 +- sync/src/transaction/extension.rs | 10 +- types/src/lib.rs | 2 + types/src/transaction/action.rs | 6 +- types/src/transaction/shard.rs | 6 +- types/src/transaction/transaction.rs | 9 +- types/src/tx_hash.rs | 109 ++++++++++++++ 38 files changed, 374 insertions(+), 253 deletions(-) create mode 100644 types/src/tx_hash.rs diff --git a/core/src/block.rs b/core/src/block.rs index 6b9e218aa5..9498ef9337 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -23,7 +23,7 @@ use cstate::{FindActionHandler, StateDB, StateError, StateWithCache, TopLevelSta use ctypes::errors::HistoryError; use ctypes::header::{Header, Seal}; use ctypes::util::unexpected::Mismatch; -use ctypes::{BlockNumber, CommonParams}; +use ctypes::{BlockNumber, CommonParams, TxHash}; use cvm::ChainTimeInfo; use primitives::{Bytes, H256}; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -90,7 +90,7 @@ pub struct ExecutedBlock { state: TopLevelState, transactions: Vec, invoices: Vec, - transactions_set: HashSet, + transactions_set: HashSet, } impl ExecutedBlock { @@ -153,7 +153,7 @@ impl<'x> OpenBlock<'x> { pub fn push_transaction( &mut self, tx: SignedTransaction, - h: Option, + h: Option, client: &C, parent_block_number: BlockNumber, parent_block_timestamp: u64, diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index 3495d1fa2b..4d7ee18845 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -16,7 +16,7 @@ use std::sync::Arc; -use ctypes::{BlockHash, BlockNumber, Tracker}; +use ctypes::{BlockHash, BlockNumber, Tracker, TxHash}; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::RwLock; use primitives::H256; @@ -411,7 +411,7 @@ impl BodyProvider for BlockChain { self.body_db.is_known_body(hash) } - fn transaction_address(&self, hash: &H256) -> Option { + fn transaction_address(&self, hash: &TxHash) -> Option { self.body_db.transaction_address(hash) } @@ -426,15 +426,15 @@ impl BodyProvider for BlockChain { impl InvoiceProvider for BlockChain { /// Returns true if invoices for given hash is known - fn is_known_error_hint(&self, hash: &H256) -> bool { + fn is_known_error_hint(&self, hash: &TxHash) -> bool { self.invoice_db.is_known_error_hint(hash) } - fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(TxHash, Option)> { self.invoice_db.error_hints_by_tracker(tracker) } - fn error_hint(&self, hash: &H256) -> Option { + fn error_hint(&self, hash: &TxHash) -> Option { self.invoice_db.error_hint(hash) } } diff --git a/core/src/blockchain/body_db.rs b/core/src/blockchain/body_db.rs index 726091b9b4..997cc6b035 100644 --- a/core/src/blockchain/body_db.rs +++ b/core/src/blockchain/body_db.rs @@ -18,11 +18,11 @@ use std::collections::{HashMap, HashSet}; use std::mem; use std::sync::Arc; -use ctypes::{BlockHash, Tracker}; +use ctypes::{BlockHash, Tracker, TxHash}; use kvdb::{DBTransaction, KeyValueDB}; use lru_cache::LruCache; use parking_lot::{Mutex, RwLock}; -use primitives::{Bytes, H256}; +use primitives::Bytes; use rlp::RlpStream; use rlp_compress::{blocks_swapper, compress, decompress}; @@ -37,8 +37,8 @@ const BODY_CACHE_SIZE: usize = 1000; pub struct BodyDB { // block cache body_cache: Mutex>, - parcel_address_cache: RwLock>, - pending_parcel_addresses: RwLock>>, + parcel_address_cache: RwLock>, + pending_parcel_addresses: RwLock>>, transaction_address_cache: Mutex>, pending_transaction_addresses: Mutex>>, @@ -141,7 +141,7 @@ impl BodyDB { fn new_parcel_address_entries( &self, best_block_changed: &BestBlockChanged, - ) -> HashMap> { + ) -> HashMap> { let block_hash = if let Some(best_block_hash) = best_block_changed.new_best_hash() { best_block_hash } else { @@ -284,7 +284,7 @@ pub trait BodyProvider { fn is_known_body(&self, hash: &BlockHash) -> bool; /// Get the address of parcel with given hash. - fn transaction_address(&self, hash: &H256) -> Option; + fn transaction_address(&self, hash: &TxHash) -> Option; fn transaction_address_by_tracker(&self, tracker: &Tracker) -> Option; @@ -298,7 +298,7 @@ impl BodyProvider for BodyDB { } /// Get the address of parcel with given hash. - fn transaction_address(&self, hash: &H256) -> Option { + fn transaction_address(&self, hash: &TxHash) -> Option { let result = self.db.read_with_cache(db::COL_EXTRA, &mut *self.parcel_address_cache.write(), hash)?; Some(result) } @@ -332,11 +332,11 @@ impl BodyProvider for BodyDB { fn parcel_address_entries( block_hash: BlockHash, - parcel_hashes: impl IntoIterator, -) -> impl Iterator)> { - parcel_hashes.into_iter().enumerate().map(move |(index, parcel_hash)| { + tx_hashes: impl IntoIterator, +) -> impl Iterator)> { + tx_hashes.into_iter().enumerate().map(move |(index, tx_hash)| { ( - parcel_hash, + tx_hash, Some(TransactionAddress { block_hash, index, diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index f016b50b55..4a62ac5a1d 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -16,7 +16,7 @@ use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; -use ctypes::{BlockHash, BlockNumber, Tracker}; +use ctypes::{BlockHash, BlockNumber, Tracker, TxHash}; use primitives::{H256, H264, U256}; use crate::db::Key; @@ -29,8 +29,8 @@ enum ExtrasIndex { BlockDetails = 0, /// Block hash index BlockHash = 1, - /// Parcel address index - ParcelAddress = 2, + /// Transaction address index + TransactionAddress = 2, /// Transaction addresses index TransactionAddresses = 3, // (Reserved) = 4, @@ -77,11 +77,11 @@ impl Key for BlockHash { } } -impl Key for H256 { +impl Key for TxHash { type Target = H264; fn key(&self) -> H264 { - with_index(self, ExtrasIndex::ParcelAddress) + with_index(self, ExtrasIndex::TransactionAddress) } } diff --git a/core/src/blockchain/invoice_db.rs b/core/src/blockchain/invoice_db.rs index eb5b82d694..b5fb9e3993 100644 --- a/core/src/blockchain/invoice_db.rs +++ b/core/src/blockchain/invoice_db.rs @@ -18,7 +18,7 @@ use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::Arc; -use ctypes::Tracker; +use ctypes::{Tracker, TxHash}; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::RwLock; use primitives::{H256, H264}; @@ -33,7 +33,7 @@ pub struct InvoiceDB { // tracker -> transaction hashe + error hint tracker_cache: RwLock>, // transaction hash -> error hint - hash_cache: RwLock>>, + hash_cache: RwLock>>, db: Arc, } @@ -55,7 +55,7 @@ impl InvoiceDB { pub fn insert_invoice( &self, batch: &mut DBTransaction, - hash: H256, + hash: TxHash, tracker: Option, error_hint: Option, ) { @@ -80,34 +80,34 @@ impl InvoiceDB { /// Interface for querying invoices. pub trait InvoiceProvider { /// Returns true if invoices for given hash is known - fn is_known_error_hint(&self, hash: &H256) -> bool; + fn is_known_error_hint(&self, hash: &TxHash) -> bool; /// Get error hints - fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)>; + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(TxHash, Option)>; /// Get error hint - fn error_hint(&self, hash: &H256) -> Option; + fn error_hint(&self, hash: &TxHash) -> Option; } impl InvoiceProvider for InvoiceDB { - fn is_known_error_hint(&self, hash: &H256) -> bool { + fn is_known_error_hint(&self, hash: &TxHash) -> bool { self.db.exists_with_cache(db::COL_ERROR_HINT, &self.hash_cache, hash) } - fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(TxHash, Option)> { self.db .read_with_cache(db::COL_ERROR_HINT, &mut *self.tracker_cache.write(), tracker) .map(|hashes| (*hashes).clone()) .unwrap_or_default() } - fn error_hint(&self, hash: &H256) -> Option { + fn error_hint(&self, hash: &TxHash) -> Option { self.db.read_with_cache(db::COL_ERROR_HINT, &mut *self.hash_cache.write(), hash)? } } #[derive(Clone, Default)] -pub struct TrackerInvoices(Vec<(H256, Option)>); +pub struct TrackerInvoices(Vec<(TxHash, Option)>); impl Encodable for TrackerInvoices { fn rlp_append(&self, s: &mut RlpStream) { @@ -137,14 +137,14 @@ impl Decodable for TrackerInvoices { } } -impl From)>> for TrackerInvoices { - fn from(f: Vec<(H256, Option)>) -> Self { +impl From)>> for TrackerInvoices { + fn from(f: Vec<(TxHash, Option)>) -> Self { TrackerInvoices(f) } } impl Deref for TrackerInvoices { - type Target = Vec<(H256, Option)>; + type Target = Vec<(TxHash, Option)>; fn deref(&self) -> &Self::Target { &self.0 @@ -168,7 +168,7 @@ impl From for u8 { } } -impl Key> for H256 { +impl Key> for TxHash { type Target = H264; fn key(&self) -> H264 { diff --git a/core/src/client/chain_notify.rs b/core/src/client/chain_notify.rs index dfbdba5d56..ffe0c4f547 100644 --- a/core/src/client/chain_notify.rs +++ b/core/src/client/chain_notify.rs @@ -15,8 +15,7 @@ // along with this program. If not, see . use cnetwork::NodeId; -use ctypes::BlockHash; -use primitives::H256; +use ctypes::{BlockHash, TxHash}; /// Represents what has to be handled by actor listening to chain events pub trait ChainNotify: Send + Sync { @@ -48,7 +47,7 @@ pub trait ChainNotify: Send + Sync { } /// fires when new transactions are received from a peer - fn transactions_received(&self, _hashes: Vec, _peer_id: NodeId) { + fn transactions_received(&self, _hashes: Vec, _peer_id: NodeId) { // does nothing by default } } diff --git a/core/src/client/client.rs b/core/src/client/client.rs index 6ea56f56b8..add839f9fb 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -28,7 +28,7 @@ use cstate::{ }; use ctimer::{TimeoutHandler, TimerApi, TimerScheduleError, TimerToken}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker, TxHash}; use cvm::{decode, execute, ChainTimeInfo, ScriptResult, VMConfig}; use hashdb::AsHashDB; use journaldb; @@ -142,7 +142,7 @@ impl Client { self.notify.write().push(target); } - pub fn transactions_received(&self, hashes: &[H256], peer_id: NodeId) { + pub fn transactions_received(&self, hashes: &[TxHash], peer_id: NodeId) { self.notify(|notify| { notify.transactions_received(hashes.to_vec(), peer_id); }); @@ -422,7 +422,7 @@ impl AssetClient for Client { } impl TextClient for Client { - fn get_text(&self, tx_hash: H256, id: BlockId) -> TrieResult> { + fn get_text(&self, tx_hash: TxHash, id: BlockId) -> TrieResult> { if let Some(state) = Client::state_at(&self, id) { Ok(state.text(&tx_hash)?) } else { @@ -797,7 +797,7 @@ impl BlockChainClient for Client { self.transaction_address(id).and_then(|address| chain.transaction(&address)) } - fn error_hint(&self, hash: &H256) -> Option { + fn error_hint(&self, hash: &TxHash) -> Option { let chain = self.block_chain(); chain.error_hint(hash) } @@ -808,7 +808,7 @@ impl BlockChainClient for Client { address.and_then(|address| chain.transaction(&address)) } - fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(TxHash, Option)> { let chain = self.block_chain(); chain.error_hints_by_tracker(tracker) } @@ -855,7 +855,7 @@ impl Shard for Client { state.number_of_shards().ok() } - fn shard_id_by_hash(&self, create_shard_tx_hash: &H256, state: StateOrBlock) -> Option { + fn shard_id_by_hash(&self, create_shard_tx_hash: &TxHash, state: StateOrBlock) -> Option { let state = self.state_info(state)?; state.shard_id_by_hash(&create_shard_tx_hash).ok()? } diff --git a/core/src/client/mod.rs b/core/src/client/mod.rs index a9f6520a24..6b565e903a 100644 --- a/core/src/client/mod.rs +++ b/core/src/client/mod.rs @@ -37,7 +37,7 @@ use cmerkle::Result as TrieResult; use cnetwork::NodeId; use cstate::{AssetScheme, FindActionHandler, OwnedAsset, StateResult, Text, TopLevelState, TopStateView}; use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker}; +use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker, TxHash}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; use primitives::{Bytes, H160, H256, U256}; @@ -185,7 +185,7 @@ impl From for StateOrBlock { pub trait Shard { fn number_of_shards(&self, state: StateOrBlock) -> Option; - fn shard_id_by_hash(&self, create_shard_tx_hash: &H256, state: StateOrBlock) -> Option; + fn shard_id_by_hash(&self, create_shard_tx_hash: &TxHash, state: StateOrBlock) -> Option; fn shard_root(&self, shard_id: ShardId, state: StateOrBlock) -> Option; fn shard_owners(&self, shard_id: ShardId, state: StateOrBlock) -> Option>; @@ -250,12 +250,12 @@ pub trait BlockChainClient: Sync + Send + AccountData + BlockChainTrait + Import fn transaction(&self, id: &TransactionId) -> Option; /// Get invoice with given hash. - fn error_hint(&self, hash: &H256) -> Option; + fn error_hint(&self, hash: &TxHash) -> Option; /// Get the transaction with given tracker. fn transaction_by_tracker(&self, tracker: &Tracker) -> Option; - fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(H256, Option)>; + fn error_hints_by_tracker(&self, tracker: &Tracker) -> Vec<(TxHash, Option)>; } /// Result of import block operation. @@ -319,7 +319,7 @@ pub trait AssetClient { /// Provides methods to texts pub trait TextClient { - fn get_text(&self, tx_hash: H256, id: BlockId) -> TrieResult>; + fn get_text(&self, tx_hash: TxHash, id: BlockId) -> TrieResult>; } pub trait ExecuteClient: ChainTimeInfo { diff --git a/core/src/client/test_client.rs b/core/src/client/test_client.rs index b8f5b9789d..8b61a8f443 100644 --- a/core/src/client/test_client.rs +++ b/core/src/client/test_client.rs @@ -43,7 +43,7 @@ use cstate::tests::helpers::empty_top_state; use cstate::{FindActionHandler, StateDB, TopLevelState}; use ctimer::{TimeoutHandler, TimerToken}; use ctypes::transaction::{Action, Transaction}; -use ctypes::{BlockHash, BlockNumber, CommonParams, Header as BlockHeader, Tracker}; +use ctypes::{BlockHash, BlockNumber, CommonParams, Header as BlockHeader, Tracker, TxHash}; use cvm::ChainTimeInfo; use journaldb; use kvdb::KeyValueDB; @@ -291,7 +291,7 @@ impl TestBlockChainClient { } /// Inserts a transaction to miners mem pool. - pub fn insert_transaction_to_pool(&self) -> H256 { + pub fn insert_transaction_to_pool(&self) -> TxHash { let keypair = Random.generate().unwrap(); let tx = Transaction { seq: 0, @@ -593,7 +593,7 @@ impl BlockChainClient for TestBlockChainClient { unimplemented!(); } - fn error_hint(&self, _hash: &H256) -> Option { + fn error_hint(&self, _hash: &TxHash) -> Option { unimplemented!(); } @@ -601,7 +601,7 @@ impl BlockChainClient for TestBlockChainClient { unimplemented!(); } - fn error_hints_by_tracker(&self, _: &Tracker) -> Vec<(H256, Option)> { + fn error_hints_by_tracker(&self, _: &Tracker) -> Vec<(TxHash, Option)> { unimplemented!(); } } diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index d2b7da7ef2..93386a0df5 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -1457,7 +1457,7 @@ impl Worker { bytes: double.to_action().rlp_bytes().into_vec(), }, }; - let signature = match self.signer.sign_ecdsa(tx.hash()) { + let signature = match self.signer.sign_ecdsa(*tx.hash()) { Ok(signature) => signature, Err(e) => { cerror!(ENGINE, "Found double vote, but could not sign the message: {}", e); diff --git a/core/src/encoded.rs b/core/src/encoded.rs index 375a6505fd..0e77876b5b 100644 --- a/core/src/encoded.rs +++ b/core/src/encoded.rs @@ -25,7 +25,7 @@ use ccrypto::blake256; use ckey::Address; -use ctypes::{BlockHash, BlockNumber, Header as FullHeader}; +use ctypes::{BlockHash, BlockNumber, Header as FullHeader, TxHash}; use primitives::{H256, U256}; use rlp::Rlp; @@ -173,7 +173,7 @@ impl Body { } /// The hash of each transaction in the block. - pub fn transaction_hashes(&self) -> Vec { + pub fn transaction_hashes(&self) -> Vec { self.view().transaction_hashes() } } @@ -298,7 +298,7 @@ impl Block { } /// The hash of each transaction in the block. - pub fn transaction_hashes(&self) -> Vec { + pub fn transaction_hashes(&self) -> Vec { self.view().transaction_hashes() } } diff --git a/core/src/invoice.rs b/core/src/invoice.rs index ed3d96bc69..c36e1303ae 100644 --- a/core/src/invoice.rs +++ b/core/src/invoice.rs @@ -14,12 +14,11 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::Tracker; -use primitives::H256; +use ctypes::{Tracker, TxHash}; #[derive(Clone, Debug, PartialEq)] pub struct Invoice { pub tracker: Option, - pub hash: H256, + pub hash: TxHash, pub error: Option, } diff --git a/core/src/miner/mem_pool.rs b/core/src/miner/mem_pool.rs index d513085a34..8729639c0e 100644 --- a/core/src/miner/mem_pool.rs +++ b/core/src/miner/mem_pool.rs @@ -20,9 +20,8 @@ use std::sync::Arc; use ckey::{public_to_address, Public}; use ctypes::errors::{HistoryError, RuntimeError, SyntaxError}; -use ctypes::BlockNumber; +use ctypes::{BlockNumber, TxHash}; use kvdb::{DBTransaction, KeyValueDB}; -use primitives::H256; use rlp; use table::Table; @@ -96,7 +95,7 @@ pub struct MemPool { /// The memory limit of each queue queue_memory_limit: usize, /// All transactions managed by pool indexed by hash - by_hash: HashMap, + by_hash: HashMap, /// Current seq of each public key (fee payer) first_seqs: HashMap, /// Next seq of transaction in current (to quickly check next expected transaction) @@ -279,7 +278,7 @@ impl MemPool { let order = TransactionOrder::for_transaction(&item, client_account.seq); let order_with_tag = TransactionOrderWithTag::new(order, QueueTag::New); - backup::backup_item(&mut batch, hash, &item); + backup::backup_item(&mut batch, *hash, &item); self.by_hash.insert(hash, item); if let Some(old_order_with_tag) = self.by_signer_public.insert(signer_public, seq, order_with_tag) { @@ -458,7 +457,7 @@ impl MemPool { let order = TransactionOrder::for_transaction(&item, client_account.seq); let order_with_tag = TransactionOrderWithTag::new(order, QueueTag::New); - self.by_hash.insert(*hash, item.clone()); + self.by_hash.insert((*hash).into(), item.clone()); self.by_signer_public.insert(signer_public, seq, order_with_tag); if item.origin == TxOrigin::Local { @@ -508,7 +507,7 @@ impl MemPool { /// If gap is introduced marks subsequent transactions as future pub fn remove( &mut self, - transaction_hashes: &[H256], + transaction_hashes: &[TxHash], fetch_seq: &F, current_block_number: PoolingInstant, current_timestamp: u64, @@ -959,7 +958,7 @@ impl MemPool { } /// Returns Some(true) if the given transaction is local and None for not found. - pub fn is_local_transaction(&self, tx_hash: H256) -> Option { + pub fn is_local_transaction(&self, tx_hash: TxHash) -> Option { self.by_hash.get(&tx_hash).map(|found_item| found_item.origin.is_local()) } diff --git a/core/src/miner/mem_pool_types.rs b/core/src/miner/mem_pool_types.rs index 3b9709b041..d69433c24c 100644 --- a/core/src/miner/mem_pool_types.rs +++ b/core/src/miner/mem_pool_types.rs @@ -19,8 +19,7 @@ use std::collections::{BTreeMap, BTreeSet}; use ckey::Public; use ctypes::transaction::Action; -use ctypes::BlockNumber; -use primitives::H256; +use ctypes::{BlockNumber, TxHash}; use rlp; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -122,7 +121,7 @@ pub struct TransactionOrder { /// Currently using the RLP byte length of the transaction as the mem usage. pub mem_usage: usize, /// Hash to identify associated transaction - pub hash: H256, + pub hash: TxHash, /// Incremental id assigned when transaction is inserted to the pool. pub insertion_id: u64, /// Origin of the transaction @@ -238,7 +237,7 @@ impl MemPoolItem { } } - pub fn hash(&self) -> H256 { + pub fn hash(&self) -> TxHash { self.tx.hash() } diff --git a/core/src/miner/miner.rs b/core/src/miner/miner.rs index f4795b50ff..0278715cff 100644 --- a/core/src/miner/miner.rs +++ b/core/src/miner/miner.rs @@ -26,7 +26,7 @@ use ckey::{public_to_address, Address, Password, PlatformAddress, Public}; use cstate::{FindActionHandler, TopLevelState}; use ctypes::errors::{HistoryError, RuntimeError}; use ctypes::transaction::{Action, IncompleteTransaction, Timelock}; -use ctypes::{BlockHash, BlockNumber, Header}; +use ctypes::{BlockHash, BlockNumber, Header, TxHash}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; use parking_lot::{Mutex, RwLock}; @@ -111,7 +111,7 @@ struct SealingWork { enabled: bool, } -type TransactionListener = Box; +type TransactionListener = Box; pub struct Miner { mem_pool: Arc>, @@ -197,7 +197,7 @@ impl Miner { } /// Set a callback to be notified about imported transactions' hashes. - pub fn add_transactions_listener(&self, f: Box) { + pub fn add_transactions_listener(&self, f: Box) { self.transaction_listener.write().push(f); } @@ -1055,7 +1055,7 @@ impl MinerService for Miner { platform_address: PlatformAddress, passphrase: Option, seq: Option, - ) -> Result<(H256, u64), Error> { + ) -> Result<(TxHash, u64), Error> { let address = platform_address.try_into_address()?; let seq = match seq { Some(seq) => seq, diff --git a/core/src/miner/mod.rs b/core/src/miner/mod.rs index 867ec2a4eb..0eea957edf 100644 --- a/core/src/miner/mod.rs +++ b/core/src/miner/mod.rs @@ -28,9 +28,9 @@ use std::ops::Range; use ckey::{Address, Password, PlatformAddress}; use cstate::{FindActionHandler, TopStateView}; use ctypes::transaction::IncompleteTransaction; -use ctypes::BlockHash; +use ctypes::{BlockHash, TxHash}; use cvm::ChainTimeInfo; -use primitives::{Bytes, H256}; +use primitives::Bytes; pub use self::miner::{AuthoringParams, Miner, MinerOptions}; pub use self::stratum::{Config as StratumConfig, Error as StratumError, Stratum}; @@ -141,7 +141,7 @@ pub trait MinerService: Send + Sync { platform_address: PlatformAddress, passphrase: Option, seq: Option, - ) -> Result<(H256, u64), Error>; + ) -> Result<(TxHash, u64), Error>; /// Get a list of all pending transactions in the mem pool. fn ready_transactions(&self, range: Range) -> PendingSignedTransactions; diff --git a/core/src/transaction.rs b/core/src/transaction.rs index 2749e12955..118564ed3e 100644 --- a/core/src/transaction.rs +++ b/core/src/transaction.rs @@ -20,8 +20,7 @@ use ccrypto::blake256; use ckey::{self, public_to_address, recover, sign, Private, Public, Signature}; use ctypes::errors::SyntaxError; use ctypes::transaction::Transaction; -use ctypes::{BlockHash, BlockNumber, CommonParams}; -use primitives::H256; +use ctypes::{BlockHash, BlockNumber, CommonParams, TxHash}; use rlp::{self, DecoderError, Encodable, RlpStream, UntrustedRlp}; use crate::error::Error; @@ -34,7 +33,7 @@ pub struct UnverifiedTransaction { /// Signature. sig: Signature, /// Hash of the transaction - hash: H256, + hash: TxHash, } impl Deref for UnverifiedTransaction { @@ -60,7 +59,7 @@ impl rlp::Decodable for UnverifiedTransaction { got: item_count, }) } - let hash = blake256(d.as_raw()); + let hash = blake256(d.as_raw()).into(); Ok(UnverifiedTransaction { unsigned: Transaction { seq: d.val_at(0)?, @@ -85,14 +84,14 @@ impl UnverifiedTransaction { UnverifiedTransaction { unsigned, sig, - hash: 0.into(), + hash: Default::default(), } .compute_hash() } /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { - let hash = blake256(&*self.rlp_bytes()); + let hash = blake256(&*self.rlp_bytes()).into(); self.hash = hash; self } @@ -108,7 +107,7 @@ impl UnverifiedTransaction { } /// Get the hash of this header (blake256 of the RLP). - pub fn hash(&self) -> H256 { + pub fn hash(&self) -> TxHash { self.hash } @@ -287,7 +286,7 @@ mod tests { network_id: "tc".into(), }, sig: Signature::default(), - hash: H256::default(), + hash: H256::default().into(), } .compute_hash()); } @@ -305,7 +304,7 @@ mod tests { }, }, sig: Signature::default(), - hash: H256::default(), + hash: H256::default().into(), } .compute_hash()); } @@ -322,7 +321,7 @@ mod tests { }, }, sig: Signature::default(), - hash: H256::default(), + hash: H256::default().into(), } .compute_hash()); } @@ -339,7 +338,7 @@ mod tests { }, }, sig: Signature::default(), - hash: H256::default(), + hash: H256::default().into(), } .compute_hash()); } diff --git a/core/src/types/ids.rs b/core/src/types/ids.rs index 1aa6ca8f5d..aeb0934e27 100644 --- a/core/src/types/ids.rs +++ b/core/src/types/ids.rs @@ -14,8 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::{BlockHash, BlockNumber}; -use primitives::H256; +use ctypes::{BlockHash, BlockNumber, TxHash}; /// Uniquely identifies block. #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] @@ -48,14 +47,14 @@ impl From for BlockId { #[derive(Debug, PartialEq, Clone, Hash, Eq)] pub enum TransactionId { /// Transaction's blake256. - Hash(H256), + Hash(TxHash), /// Block id and transaction index within this block. /// Querying by block position is always faster. Location(BlockId, usize), } -impl From for TransactionId { - fn from(hash: H256) -> Self { +impl From for TransactionId { + fn from(hash: TxHash) -> Self { TransactionId::Hash(hash) } } diff --git a/core/src/views/block.rs b/core/src/views/block.rs index c10ee7e188..be58df491c 100644 --- a/core/src/views/block.rs +++ b/core/src/views/block.rs @@ -15,8 +15,7 @@ // along with this program. If not, see . use ccrypto::blake256; -use ctypes::{BlockHash, Header}; -use primitives::H256; +use ctypes::{BlockHash, Header, TxHash}; use rlp::Rlp; use super::{HeaderView, TransactionView}; @@ -101,8 +100,8 @@ impl<'a> BlockView<'a> { } /// Return transaction hashes. - pub fn transaction_hashes(&self) -> Vec { - self.rlp.at(1).iter().map(|rlp| blake256(rlp.as_raw())).collect() + pub fn transaction_hashes(&self) -> Vec { + self.rlp.at(1).iter().map(|rlp| blake256(rlp.as_raw()).into()).collect() } /// Returns transaction at given index without deserializing unnecessary data. diff --git a/core/src/views/body.rs b/core/src/views/body.rs index b6454cb28f..e9b6681b76 100644 --- a/core/src/views/body.rs +++ b/core/src/views/body.rs @@ -15,8 +15,7 @@ // along with this program. If not, see . use ccrypto::blake256; -use ctypes::{BlockHash, BlockNumber}; -use primitives::H256; +use ctypes::{BlockHash, BlockNumber, TxHash}; use rlp::Rlp; use super::TransactionView; @@ -82,8 +81,8 @@ impl<'a> BodyView<'a> { } /// Return transaction hashes. - pub fn transaction_hashes(&self) -> Vec { - self.rlp.at(0).iter().map(|rlp| blake256(rlp.as_raw())).collect() + pub fn transaction_hashes(&self) -> Vec { + self.rlp.at(0).iter().map(|rlp| blake256(rlp.as_raw()).into()).collect() } /// Returns transaction at given index without deserializing unnecessary data. diff --git a/rpc/src/v1/impls/chain.rs b/rpc/src/v1/impls/chain.rs index a7669a32d0..576e571d00 100644 --- a/rpc/src/v1/impls/chain.rs +++ b/rpc/src/v1/impls/chain.rs @@ -26,7 +26,7 @@ use cjson::uint::Uint; use ckey::{public_to_address, NetworkId, PlatformAddress, Public}; use cstate::FindActionHandler; use ctypes::transaction::{Action, ShardTransaction as ShardTransactionType}; -use ctypes::{BlockHash, BlockNumber, ShardId, Tracker}; +use ctypes::{BlockHash, BlockNumber, ShardId, Tracker, TxHash}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -65,12 +65,12 @@ where + TermInfo + 'static, { - fn get_transaction(&self, transaction_hash: H256) -> Result> { + fn get_transaction(&self, transaction_hash: TxHash) -> Result> { let id = transaction_hash.into(); Ok(self.client.transaction(&id).map(From::from)) } - fn get_transaction_signer(&self, transaction_hash: H256) -> Result> { + fn get_transaction_signer(&self, transaction_hash: TxHash) -> Result> { let id = transaction_hash.into(); Ok(self.client.transaction(&id).map(|mut tx| { let address = public_to_address(&tx.signer()); @@ -78,11 +78,11 @@ where })) } - fn contains_transaction(&self, transaction_hash: H256) -> Result { + fn contains_transaction(&self, transaction_hash: TxHash) -> Result { Ok(self.client.transaction_block(&transaction_hash.into()).is_some()) } - fn contain_transaction(&self, transaction_hash: H256) -> Result { + fn contain_transaction(&self, transaction_hash: TxHash) -> Result { self.contains_transaction(transaction_hash) } @@ -123,7 +123,7 @@ where } } - fn get_text(&self, transaction_hash: H256, block_number: Option) -> Result> { + fn get_text(&self, transaction_hash: TxHash, block_number: Option) -> Result> { if block_number == Some(0) { return Ok(None) } @@ -193,7 +193,7 @@ where Ok(self.client.number_of_shards(block_id.into())) } - fn get_shard_id_by_hash(&self, create_shard_tx_hash: H256, block_number: Option) -> Result> { + fn get_shard_id_by_hash(&self, create_shard_tx_hash: TxHash, block_number: Option) -> Result> { let block_id = block_number.map(BlockId::Number).unwrap_or(BlockId::Latest); Ok(self.client.shard_id_by_hash(&create_shard_tx_hash, block_id.into())) } diff --git a/rpc/src/v1/impls/devel.rs b/rpc/src/v1/impls/devel.rs index 39843ef3ca..0fa2e47a05 100644 --- a/rpc/src/v1/impls/devel.rs +++ b/rpc/src/v1/impls/devel.rs @@ -33,7 +33,7 @@ use csync::BlockSyncEvent; use ctypes::transaction::{ Action, AssetMintOutput, AssetOutPoint, AssetTransferInput, AssetTransferOutput, Transaction, }; -use ctypes::Tracker; +use ctypes::{Tracker, TxHash}; use jsonrpc_core::Result; use kvdb::KeyValueDB; use primitives::{H160, H256}; @@ -217,7 +217,7 @@ where SignedTransaction::new_with_sign(tx, key_pair.private()) } - fn send_tx(tx: Transaction, client: &C, key_pair: &KeyPair) -> Result + fn send_tx(tx: Transaction, client: &C, key_pair: &KeyPair) -> Result where C: MiningBlockChainClient + EngineInfo + TermInfo, { let signed = SignedTransaction::new_with_sign(tx, key_pair.private()); diff --git a/rpc/src/v1/impls/mempool.rs b/rpc/src/v1/impls/mempool.rs index 99cdc5f2af..efa92bdb38 100644 --- a/rpc/src/v1/impls/mempool.rs +++ b/rpc/src/v1/impls/mempool.rs @@ -19,8 +19,7 @@ use std::sync::Arc; use ccore::{BlockChainClient, MiningBlockChainClient, SignedTransaction}; use cjson::bytes::Bytes; use ckey::{Address, PlatformAddress}; -use ctypes::Tracker; -use primitives::H256; +use ctypes::{Tracker, TxHash}; use rlp::UntrustedRlp; use jsonrpc_core::Result; @@ -45,7 +44,7 @@ impl Mempool for MempoolClient where C: BlockChainClient + MiningBlockChainClient + 'static, { - fn send_signed_transaction(&self, raw: Bytes) -> Result { + fn send_signed_transaction(&self, raw: Bytes) -> Result { UntrustedRlp::new(&raw.into_vec()) .as_val() .map_err(|e| errors::rlp(&e)) @@ -69,7 +68,7 @@ where .collect()) } - fn get_error_hint(&self, transaction_hash: H256) -> Result> { + fn get_error_hint(&self, transaction_hash: TxHash) -> Result> { Ok(self.client.error_hint(&transaction_hash)) } diff --git a/rpc/src/v1/traits/chain.rs b/rpc/src/v1/traits/chain.rs index 3eeb48a230..d9dc27b3d8 100644 --- a/rpc/src/v1/traits/chain.rs +++ b/rpc/src/v1/traits/chain.rs @@ -17,7 +17,7 @@ use cjson::scheme::Params; use cjson::uint::Uint; use ckey::{NetworkId, PlatformAddress, Public}; -use ctypes::{BlockHash, BlockNumber, ShardId, Tracker}; +use ctypes::{BlockHash, BlockNumber, ShardId, Tracker, TxHash}; use primitives::{Bytes as BytesArray, H160, H256}; use jsonrpc_core::Result; @@ -28,18 +28,18 @@ use super::super::types::{AssetScheme, Block, BlockNumberAndHash, OwnedAsset, Te pub trait Chain { /// Gets transaction with given hash. #[rpc(name = "chain_getTransaction")] - fn get_transaction(&self, transaction_hash: H256) -> Result>; + fn get_transaction(&self, transaction_hash: TxHash) -> Result>; /// Gets the signer of transaction with given hash. #[rpc(name = "chain_getTransactionSigner")] - fn get_transaction_signer(&self, transaction_hash: H256) -> Result>; + fn get_transaction_signer(&self, transaction_hash: TxHash) -> Result>; /// Query whether the chain has the transaction with given transaction hash. #[rpc(name = "chain_containsTransaction")] - fn contains_transaction(&self, transaction_hash: H256) -> Result; + fn contains_transaction(&self, transaction_hash: TxHash) -> Result; #[rpc(name = "chain_containTransaction")] - fn contain_transaction(&self, transaction_hash: H256) -> Result; + fn contain_transaction(&self, transaction_hash: TxHash) -> Result; /// Gets transaction with given transaction tracker. #[rpc(name = "chain_getTransactionByTracker")] @@ -65,7 +65,7 @@ pub trait Chain { /// Gets text with given transaction hash. #[rpc(name = "chain_getText")] - fn get_text(&self, transaction_hash: H256, block_number: Option) -> Result>; + fn get_text(&self, transaction_hash: TxHash, block_number: Option) -> Result>; /// Gets asset with given asset type. #[rpc(name = "chain_getAsset")] @@ -113,7 +113,7 @@ pub trait Chain { /// Gets shard id #[rpc(name = "chain_getShardIdByHash")] - fn get_shard_id_by_hash(&self, create_shard_tx_hash: H256, block_number: Option) -> Result>; + fn get_shard_id_by_hash(&self, create_shard_tx_hash: TxHash, block_number: Option) -> Result>; /// Gets shard root #[rpc(name = "chain_getShardRoot")] diff --git a/rpc/src/v1/traits/mempool.rs b/rpc/src/v1/traits/mempool.rs index dc329f3d07..b7726306b0 100644 --- a/rpc/src/v1/traits/mempool.rs +++ b/rpc/src/v1/traits/mempool.rs @@ -16,9 +16,8 @@ use cjson::bytes::Bytes; use ckey::PlatformAddress; -use ctypes::Tracker; +use ctypes::{Tracker, TxHash}; use jsonrpc_core::Result; -use primitives::H256; use super::super::types::PendingTransactions; @@ -26,7 +25,7 @@ use super::super::types::PendingTransactions; pub trait Mempool { /// Sends signed transaction, returning its hash. #[rpc(name = "mempool_sendSignedTransaction")] - fn send_signed_transaction(&self, raw: Bytes) -> Result; + fn send_signed_transaction(&self, raw: Bytes) -> Result; /// Gets transaction results with given transaction tracker. #[rpc(name = "mempool_getTransactionResultsByTracker")] @@ -34,7 +33,7 @@ pub trait Mempool { /// Gets a hint to find out why the transaction failed. #[rpc(name = "mempool_getErrorHint")] - fn get_error_hint(&self, transaction_hash: H256) -> Result>; + fn get_error_hint(&self, transaction_hash: TxHash) -> Result>; /// Gets transactions in the current mem pool. #[rpc(name = "mempool_getPendingTransactions")] diff --git a/rpc/src/v1/types/action.rs b/rpc/src/v1/types/action.rs index 48797bcd0c..25343e937a 100644 --- a/rpc/src/v1/types/action.rs +++ b/rpc/src/v1/types/action.rs @@ -19,8 +19,8 @@ use std::convert::TryFrom; use cjson::uint::Uint; use ckey::{NetworkId, PlatformAddress, Public, Signature}; use ctypes::transaction::{Action as ActionType, AssetMintOutput as AssetMintOutputType}; -use ctypes::{ShardId, Tracker}; -use primitives::{Bytes, H160, H256}; +use ctypes::{ShardId, Tracker, TxHash}; +use primitives::{Bytes, H160}; use rustc_serialize::hex::{FromHex, ToHex}; use super::super::errors::ConversionError; @@ -116,7 +116,7 @@ pub enum Action { signature: Signature, }, Remove { - hash: H256, + hash: TxHash, signature: Signature, }, #[serde(rename_all = "camelCase")] @@ -230,7 +230,7 @@ pub enum ActionWithTracker { signature: Signature, }, Remove { - hash: H256, + hash: TxHash, signature: Signature, }, #[serde(rename_all = "camelCase")] diff --git a/rpc/src/v1/types/mod.rs b/rpc/src/v1/types/mod.rs index db0e1ceeb8..66d9b30ba5 100644 --- a/rpc/src/v1/types/mod.rs +++ b/rpc/src/v1/types/mod.rs @@ -25,8 +25,6 @@ mod transaction; mod unsigned_transaction; mod work; -use primitives::H256; - use self::asset::Asset; use self::asset_input::AssetTransferInput; use self::asset_output::{AssetMintOutput, AssetTransferOutput}; @@ -41,6 +39,7 @@ pub use self::transaction::{PendingTransactions, Transaction}; pub use self::unsigned_transaction::UnsignedTransaction; pub use self::work::Work; +use ctypes::TxHash; use serde::de::{self, Deserialize, Deserializer}; #[derive(Debug, Serialize, Deserialize)] @@ -51,7 +50,7 @@ pub struct FilterStatus { #[derive(Debug, Serialize, Deserialize)] pub struct SendTransactionResult { - pub hash: H256, + pub hash: TxHash, pub seq: u64, } diff --git a/rpc/src/v1/types/transaction.rs b/rpc/src/v1/types/transaction.rs index eabd150a8f..1586d256f9 100644 --- a/rpc/src/v1/types/transaction.rs +++ b/rpc/src/v1/types/transaction.rs @@ -17,8 +17,7 @@ use ccore::{LocalizedTransaction, PendingSignedTransactions, SignedTransaction}; use cjson::uint::Uint; use ckey::{NetworkId, Signature}; -use ctypes::BlockHash; -use primitives::H256; +use ctypes::{BlockHash, TxHash}; use super::ActionWithTracker; @@ -33,7 +32,7 @@ pub struct Transaction { pub fee: Uint, pub network_id: NetworkId, pub action: ActionWithTracker, - pub hash: H256, + pub hash: TxHash, pub sig: Signature, } diff --git a/state/src/impls/shard_level.rs b/state/src/impls/shard_level.rs index 829c610ffb..261b861f7a 100644 --- a/state/src/impls/shard_level.rs +++ b/state/src/impls/shard_level.rs @@ -792,6 +792,8 @@ impl<'db> ShardStateView for ReadOnlyShardLevelState<'db> { #[cfg(test)] mod tests { + use ctypes::TxHash; + use super::super::super::StateError; use super::super::test_helper::SHARD_ID; use super::*; @@ -1374,14 +1376,14 @@ mod tests { let mut state = get_temp_shard_state(&mut state_db, SHARD_ID, &mut shard_cache); let lock_script_hash = H160::from("ca5d3fa0a6887285ef6aa85cb12960a2b6706e00"); - let tx_hash = H256::random(); + let tx_hash = TxHash::from(H256::random()); let amount = 30; let wrap_ccc = asset_wrap_ccc!(tx_hash, asset_wrap_ccc_output!(lock_script_hash, amount)); let wrap_ccc_tracker = wrap_ccc.tracker(); let asset_type = H160::zero(); - assert_eq!(*wrap_ccc_tracker, tx_hash); + assert_eq!(*wrap_ccc_tracker, *tx_hash); assert_eq!(Ok(()), state.apply(&wrap_ccc, &sender, &[sender], &[], &get_test_client(), 0, 0)); check_shard_level_state!(state, [ @@ -1411,13 +1413,13 @@ mod tests { let mut state = get_temp_shard_state(&mut state_db, SHARD_ID, &mut shard_cache); let lock_script_hash = H160::from("b042ad154a3359d276835c903587ebafefea22af"); - let tx_hash = H256::random(); + let tx_hash = TxHash::from(H256::random()); let amount = 30; let wrap_ccc = asset_wrap_ccc!(tx_hash, asset_wrap_ccc_output!(lock_script_hash, amount)); let wrap_ccc_tracker = wrap_ccc.tracker(); - assert_eq!(*wrap_ccc_tracker, tx_hash); + assert_eq!(*wrap_ccc_tracker, *tx_hash); assert_eq!(Ok(()), state.apply(&wrap_ccc, &sender, &[sender], &[], &get_test_client(), 0, 0)); let asset_type = H160::zero(); diff --git a/state/src/impls/top_level.rs b/state/src/impls/top_level.rs index 50bdc9befc..b871efaa58 100644 --- a/state/src/impls/top_level.rs +++ b/state/src/impls/top_level.rs @@ -48,7 +48,7 @@ use ctypes::transaction::{ use ctypes::util::unexpected::Mismatch; #[cfg(test)] use ctypes::Tracker; -use ctypes::{BlockNumber, CommonParams, ShardId}; +use ctypes::{BlockNumber, CommonParams, ShardId, TxHash}; use cvm::ChainTimeInfo; use hashdb::AsHashDB; use kvdb::DBTransaction; @@ -256,7 +256,7 @@ impl TopLevelState { pub fn apply( &mut self, tx: &Transaction, - signed_hash: &H256, + signed_hash: &TxHash, signer_public: &Public, client: &C, parent_block_number: BlockNumber, @@ -297,7 +297,7 @@ impl TopLevelState { fn apply_internal( &mut self, tx: &Transaction, - signed_hash: &H256, + signed_hash: &TxHash, signer_public: &Public, client: &C, parent_block_number: BlockNumber, @@ -363,8 +363,8 @@ impl TopLevelState { &mut self, action: &Action, network_id: NetworkId, - tx_hash: H256, - signed_hash: &H256, + tx_hash: TxHash, + signed_hash: &TxHash, fee_payer: &Address, signer_public: &Public, client: &C, @@ -660,13 +660,13 @@ impl TopLevelState { self.top_cache.shard_mut(&shard_address, &trie) } - fn get_text(&self, key: &H256) -> TrieResult> { + fn get_text(&self, key: &TxHash) -> TrieResult> { let db = self.db.borrow(); let trie = TrieFactory::readonly(db.as_hashdb(), &self.root)?; self.top_cache.text(key, &trie) } - fn get_text_mut(&self, key: &H256) -> TrieResult> { + fn get_text_mut(&self, key: &TxHash) -> TrieResult> { let db = self.db.borrow(); let trie = TrieFactory::readonly(db.as_hashdb(), &self.root)?; self.top_cache.text_mut(key, &trie) @@ -876,7 +876,7 @@ impl TopState for TopLevelState { Ok(()) } - fn create_shard(&mut self, fee_payer: &Address, tx_hash: H256, users: Vec
) -> StateResult<()> { + fn create_shard(&mut self, fee_payer: &Address, tx_hash: TxHash, users: Vec
) -> StateResult<()> { let shard_id = { let mut metadata = self.get_metadata_mut()?; metadata.add_shard(tx_hash) @@ -943,7 +943,7 @@ impl TopState for TopLevelState { Ok(()) } - fn store_text(&mut self, key: &H256, text: Text, sig: &Signature) -> StateResult<()> { + fn store_text(&mut self, key: &TxHash, text: Text, sig: &Signature) -> StateResult<()> { match verify_address(text.certifier(), sig, &text.content_hash()) { Ok(false) => { return Err(RuntimeError::TextVerificationFail("Certifier and signer are different".to_string()).into()) @@ -956,7 +956,7 @@ impl TopState for TopLevelState { Ok(()) } - fn remove_text(&mut self, key: &H256, sig: &Signature) -> StateResult<()> { + fn remove_text(&mut self, key: &TxHash, sig: &Signature) -> StateResult<()> { let text = self.get_text(key)?.ok_or_else(|| RuntimeError::TextNotExist)?; match verify_address(text.certifier(), sig, key) { Ok(false) => { @@ -1382,7 +1382,7 @@ mod tests_tx { expected: 0, found: 2 }))), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1405,7 +1405,7 @@ mod tests_tx { cost: 5, } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1422,7 +1422,7 @@ mod tests_tx { let receiver = 1u64.into(); let tx = transaction!(fee: 5, pay!(receiver, 10)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 5)), @@ -1439,7 +1439,7 @@ mod tests_tx { set_top_level_state!(state, [(account: sender => balance: 5)]); let tx = transaction!(fee: 5, set_regular_key!(key)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 0, key: key)) @@ -1462,7 +1462,7 @@ mod tests_tx { let tx = transaction!(fee: 5, pay!(regular_account, 10)); assert_eq!( Err(RuntimeError::InvalidTransferDestination.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1498,7 +1498,7 @@ mod tests_tx { let tx = transaction!(seq: 0, fee: 11, unwrap_ccc_tx); assert_eq!( Err(RuntimeError::InvalidTransferDestination.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1518,7 +1518,7 @@ mod tests_tx { let key = regular_keypair.public(); let tx = transaction!(fee: 5, set_regular_key!(*key)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 10, key: *key)) @@ -1526,7 +1526,10 @@ mod tests_tx { let tx = transaction!(seq: 1, fee: 5, Action::CreateShard { users: vec![] }); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), regular_keypair.public(), &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&tx, &H256::random().into(), regular_keypair.public(), &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 15 - 5 - 5)), @@ -1549,7 +1552,7 @@ mod tests_tx { let key = regular_keypair.public(); let tx = transaction!(fee: 5, set_regular_key!(*key)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 10, key: *key)), @@ -1559,7 +1562,7 @@ mod tests_tx { let tx = transaction!(fee: 5, set_regular_key!(*key)); assert_eq!( Err(RuntimeError::RegularKeyAlreadyInUse.into()), - state.apply(&tx, &H256::random(), &sender_public2, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public2, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1582,7 +1585,7 @@ mod tests_tx { let tx = transaction! (fee: 5, set_regular_key!(sender_public2)); assert_eq!( Err(RuntimeError::RegularKeyAlreadyInUseAsPlatformAccount.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1605,7 +1608,7 @@ mod tests_tx { let (_, regular_public2, _) = address(); let tx = transaction! (fee: 5, set_regular_key!(regular_public2)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0)); assert_eq!(Ok(false), state.regular_account_exists_and_not_null(®ular_public)); check_top_level_state!(state, [ @@ -1642,7 +1645,10 @@ mod tests_tx { ); let transfer_tx = transaction!(seq: 0, fee: 11, transfer); - assert_eq!(Ok(()), state.apply(&transfer_tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&transfer_tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 25 - 11)) ]); @@ -1684,7 +1690,10 @@ mod tests_tx { ); let transfer_tx = transaction!(seq: 0, fee: 11, transfer); - assert_eq!(Ok(()), state.apply(&transfer_tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&transfer_tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 25 - 11)) ]); @@ -1707,7 +1716,7 @@ mod tests_tx { assert_eq!(Ok(false), state.regular_account_exists_and_not_null(®ular_public)); let tx = transaction!(fee: 5, Action::CreateShard { users: vec![] }); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 20)), (account: regular_address => (seq: 1, balance: 20 - 5)), @@ -1730,7 +1739,7 @@ mod tests_tx { let tx = transaction!(fee: 5, pay!(regular_address, 5)); assert_eq!( Err(RuntimeError::InvalidTransferDestination.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1754,7 +1763,7 @@ mod tests_tx { let tx = transaction!(fee: 5, pay!(receiver_address, 5)); assert_eq!( Err(RuntimeError::CannotUseMasterKey.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1781,7 +1790,7 @@ mod tests_tx { cost: 30, } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1818,7 +1827,7 @@ mod tests_tx { let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 11, transaction); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11)), @@ -1854,7 +1863,7 @@ mod tests_tx { let asset_type = Blake::blake(*transaction_tracker); let tx = transaction!(fee: 5, transaction); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 5)), @@ -1884,7 +1893,7 @@ mod tests_tx { let mint_tx = transaction!(fee: 20, mint); let asset_type = Blake::blake(*mint_tracker); - assert_eq!(Ok(()), state.apply(&mint_tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&mint_tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 120 - 20)), @@ -1907,7 +1916,10 @@ mod tests_tx { let transfer_tx = transaction!(seq: 1, fee: 30, transfer); - assert_eq!(Ok(()), state.apply(&transfer_tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&transfer_tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 120 - 20 - 30)), @@ -1945,7 +1957,7 @@ mod tests_tx { ); let tx = transaction!(fee: 11, transaction.clone()); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11)) @@ -1959,7 +1971,7 @@ mod tests_tx { shard_id } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -1987,27 +1999,27 @@ mod tests_tx { let tx = transaction!(fee: 11, wrap_ccc!(lock_script_hash, quantity)); let tx_hash = tx.hash(); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); let asset_type = H160::zero(); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(*tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); let unwrap_ccc_tx = unwrap_ccc!( - asset_transfer_input!(asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), vec![0x01]), + asset_transfer_input!(asset_out_point!(Tracker::from(*tx_hash), 0, asset_type, 30), vec![0x01]), receiver ); let tx = transaction!(seq: 1, fee: 11, unwrap_ccc_tx); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 100 - 11 - 30 - 11)), (account: receiver => (seq: 0, balance: 30)), - (asset: (Tracker::from(tx_hash), 0, 0)) + (asset: (Tracker::from(*tx_hash), 0, 0)) ]); } @@ -2031,19 +2043,19 @@ mod tests_tx { let tx = transaction!(fee: 11, wrap_ccc!(lock_script_hash, quantity)); let tx_hash = tx.hash(); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); let asset_type = H160::zero(); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(*tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); let failed_lock_script = vec![0x02]; let unwrap_ccc_tx = unwrap_ccc!( asset_transfer_input!( - asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), + asset_out_point!(Tracker::from(*tx_hash), 0, asset_type, 30), failed_lock_script.clone() ), receiver @@ -2056,13 +2068,13 @@ mod tests_tx { found: Blake::blake(&failed_lock_script), }) .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 11 - 30)), (account: receiver), - (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(*tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); } @@ -2090,7 +2102,7 @@ mod tests_tx { cost: 30, } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2118,18 +2130,18 @@ mod tests_tx { let tx = transaction!(fee: 11, wrap_ccc!(lock_script_hash, quantity)); let tx_hash = tx.hash(); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); let asset_type = H160::zero(); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 30 - 11)), - (asset: (Tracker::from(tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) + (asset: (Tracker::from(*tx_hash), 0, 0) => { asset_type: asset_type, quantity: quantity }) ]); let lock_script_hash_burn = H160::from("ca5d3fa0a6887285ef6aa85cb12960a2b6706e00"); let random_lock_script_hash = H160::random(); let transfer_tx = transfer_asset!( - inputs: asset_transfer_inputs![(asset_out_point!(Tracker::from(tx_hash), 0, asset_type, 30), vec![0x30, 0x01])], + inputs: asset_transfer_inputs![(asset_out_point!(Tracker::from(*tx_hash), 0, asset_type, 30), vec![0x30, 0x01])], asset_transfer_outputs![ (lock_script_hash, vec![vec![1]], asset_type, 10), (lock_script_hash_burn, asset_type, 5), @@ -2140,11 +2152,11 @@ mod tests_tx { let tx = transaction!(seq: 1, fee: 11, transfer_tx); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 100 - 30 - 11 - 11)), - (asset: (Tracker::from(tx_hash), 0, 0)), + (asset: (Tracker::from(*tx_hash), 0, 0)), (asset: (transfer_tx_tracker, 0, 0) => { asset_type: asset_type, quantity: 10 }), (asset: (transfer_tx_tracker, 1, 0) => { asset_type: asset_type, quantity: 5 }), (asset: (transfer_tx_tracker, 2, 0) => { asset_type: asset_type, quantity: 15 }) @@ -2156,7 +2168,7 @@ mod tests_tx { ); let tx = transaction!(seq: 2, fee: 11, unwrap_ccc_tx); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 3, balance: 100 - 30 - 11 - 11 - 11 + 5)), @@ -2183,7 +2195,7 @@ mod tests_tx { let signature = sign(&sender_private, &content_hash).unwrap(); let store_tx = transaction!(fee: 10, store!(content.clone(), sender, signature)); - let dummy_signed_hash = H256::random(); + let dummy_signed_hash = TxHash::from(H256::random()); assert_eq!(Ok(()), state.apply(&store_tx, &dummy_signed_hash, &sender_public, &get_test_client(), 0, 0, 0)); @@ -2195,7 +2207,10 @@ mod tests_tx { let signature = sign(&sender_private, &dummy_signed_hash).unwrap(); let remove_tx = transaction!(seq: 1, fee: 10, remove!(dummy_signed_hash, signature)); - assert_eq!(Ok(()), state.apply(&remove_tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&remove_tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 2, balance: 0)), @@ -2221,7 +2236,7 @@ mod tests_tx { let tx = transaction!(fee: 10, store!(content.clone(), sender, signature)); - match state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) { + match state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) { Err(StateError::Runtime(RuntimeError::TextVerificationFail(_))) => {} err => panic!("The transaction must fail with text verification failure, but {:?}", err), } @@ -2237,7 +2252,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::TextVerificationFail("Certifier and signer are different".to_string()).into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2258,13 +2273,13 @@ mod tests_tx { (metadata: shards: 1) ]); - let hash = H256::random(); + let hash = TxHash::from(H256::random()); let signature = sign(&sender_private, &hash).unwrap(); let remove_tx = transaction!(fee: 10, remove!(hash, signature)); assert_eq!( Err(RuntimeError::TextNotExist.into()), - state.apply(&remove_tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&remove_tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2314,9 +2329,9 @@ mod tests_tx { let tx1 = transaction!(fee: 5, Action::CreateShard { users: vec![] }); let tx2 = transaction!(seq: 1, fee: 5, Action::CreateShard { users: users.clone() }); - let invalid_hash = H256::random(); - let signed_hash1 = H256::random(); - let signed_hash2 = H256::random(); + let invalid_hash = TxHash::from(H256::random()); + let signed_hash1 = TxHash::from(H256::random()); + let signed_hash2 = TxHash::from(H256::random()); assert_eq!(Ok(None), state.shard_id_by_hash(&invalid_hash)); assert_eq!(Ok(None), state.shard_id_by_hash(&signed_hash1)); @@ -2367,9 +2382,9 @@ mod tests_tx { ]); let tx1 = transaction!(fee: 5, Action::CreateShard { users: vec![shard_user] }); - let invalid_hash = H256::random(); - let signed_hash1 = H256::random(); - let signed_hash2 = H256::random(); + let invalid_hash = TxHash::from(H256::random()); + let signed_hash1 = TxHash::from(H256::random()); + let signed_hash2 = TxHash::from(H256::random()); assert_eq!(Ok(None), state.shard_id_by_hash(&invalid_hash)); assert_eq!(Ok(None), state.shard_id_by_hash(&signed_hash1)); @@ -2414,7 +2429,7 @@ mod tests_tx { ]); let tx = transaction!(fee: 5, Action::CreateShard { users: vec![] }); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); let invalid_shard_id = 3; check_top_level_state!(state, [ @@ -2436,7 +2451,7 @@ mod tests_tx { ]); let tx = transaction!(fee: 5, Action::CreateShard { users: users.clone() }); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); let invalid_shard_id = 3; check_top_level_state!(state, [ @@ -2469,7 +2484,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::InvalidShardId(0).into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2505,7 +2520,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::InvalidShardId(100).into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 120)) @@ -2529,7 +2544,7 @@ mod tests_tx { ]); let tx = transaction!(fee: 5, set_shard_owners!(owners.clone())); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 5)), @@ -2556,7 +2571,7 @@ mod tests_tx { let tx = transaction!(fee: 5, set_shard_owners!(owners)); assert_eq!( Err(RuntimeError::NewOwnersMustContainSender.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 100)), @@ -2584,7 +2599,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::InsufficientPermission.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2611,7 +2626,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::InvalidShardId(invalid_shard_id).into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2640,7 +2655,7 @@ mod tests_tx { let tx = transaction!(fee: 5, set_shard_owners!(owners)); assert_eq!( Err(StateError::Runtime(RuntimeError::InsufficientPermission)), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -2675,7 +2690,7 @@ mod tests_tx { let tx = transaction!(fee: 20, mint); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 20)), @@ -2705,7 +2720,7 @@ mod tests_tx { let tx = transaction!(fee: 5, set_shard_users!(new_users)); - assert_eq!(Ok(()), state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0)); + assert_eq!(Ok(()), state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0)); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 100 - 5)) ]); @@ -2737,7 +2752,7 @@ mod tests_tx { assert_eq!( Err(RuntimeError::InsufficientPermission.into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 100)), @@ -2794,7 +2809,7 @@ mod tests_tx { got: 10, } .into()), - state.apply(&transfer_tx, &H256::random(), &signer_public, &get_test_client(), 0, 0, 0) + state.apply(&transfer_tx, &H256::random().into(), &signer_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)), @@ -2860,7 +2875,10 @@ mod tests_tx { let transfer_tracker = transfer.tracker().unwrap(); let transfer_tx = transaction!(seq: 0, fee: 11, transfer); - assert_eq!(Ok(()), state.apply(&transfer_tx, &H256::random(), &signer_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&transfer_tx, &H256::random().into(), &signer_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 25 - 11)), (scheme: (shard3, asset_type3) => { supply: 10 }), @@ -2927,7 +2945,10 @@ mod tests_tx { let transfer_tracker = transfer.tracker().unwrap(); let transfer_tx = transaction!(seq: 0, fee: 11, transfer); - assert_eq!(Ok(()), state.apply(&transfer_tx, &H256::random(), &signer_public, &get_test_client(), 0, 0, 0)); + assert_eq!( + Ok(()), + state.apply(&transfer_tx, &H256::random().into(), &signer_public, &get_test_client(), 0, 0, 0) + ); check_top_level_state!(state, [ (account: sender => (seq: 1, balance: 25 - 11)), (scheme: (shard3, asset_type3) => { supply: 10 }), @@ -3000,7 +3021,7 @@ mod tests_tx { shard_id: shard3, } .into()), - state.apply(&transfer_tx, &H256::random(), &signer_public, &get_test_client(), 0, 0, 0) + state.apply(&transfer_tx, &H256::random().into(), &signer_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)), @@ -3077,7 +3098,7 @@ mod tests_tx { got: 10, } .into()), - state.apply(&transfer_tx, &H256::random(), &signer_public, &get_test_client(), 0, 0, 0) + state.apply(&transfer_tx, &H256::random().into(), &signer_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)), @@ -3112,7 +3133,7 @@ mod tests_tx { name: "shard user".to_string(), } .into()), - state.apply(&tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)) @@ -3141,7 +3162,7 @@ mod tests_tx { name: "shard user".to_string(), } .into()), - state.apply(&tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)) @@ -3170,7 +3191,7 @@ mod tests_tx { name: "shard owner".to_string(), } .into()), - state.apply(&tx, &H256::random(), ®ular_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), ®ular_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ (account: sender => (seq: 0, balance: 25)) @@ -3209,7 +3230,7 @@ mod tests_tx { name: "approver of asset".to_string(), } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ @@ -3252,7 +3273,7 @@ mod tests_tx { name: "registrar of asset".to_string(), } .into()), - state.apply(&tx, &H256::random(), &sender_public, &get_test_client(), 0, 0, 0) + state.apply(&tx, &H256::random().into(), &sender_public, &get_test_client(), 0, 0, 0) ); check_top_level_state!(state, [ diff --git a/state/src/item/metadata.rs b/state/src/item/metadata.rs index 25fa163cab..8b9f5a766e 100644 --- a/state/src/item/metadata.rs +++ b/state/src/item/metadata.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::{CommonParams, ShardId}; +use ctypes::{CommonParams, ShardId, TxHash}; use primitives::H256; use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -30,7 +30,7 @@ struct TermMetadata { pub struct Metadata { number_of_shards: ShardId, number_of_initial_shards: ShardId, - hashes: Vec, + hashes: Vec, term: TermMetadata, seq: u64, params: Option, @@ -52,7 +52,7 @@ impl Metadata { &self.number_of_shards } - pub fn add_shard(&mut self, tx_hash: H256) -> ShardId { + pub fn add_shard(&mut self, tx_hash: TxHash) -> ShardId { let r = self.number_of_shards; self.number_of_shards += 1; self.hashes.push(tx_hash); @@ -67,7 +67,7 @@ impl Metadata { self.number_of_initial_shards = number_of_shards; } - pub fn shard_id_by_hash(&self, tx_hash: &H256) -> Option { + pub fn shard_id_by_hash(&self, tx_hash: &TxHash) -> Option { debug_assert_eq!(::std::mem::size_of::(), ::std::mem::size_of::<::ctypes::ShardId>()); assert!(self.hashes.len() < ::std::u16::MAX as usize); self.hashes.iter().enumerate().find(|(_index, hash)| tx_hash == *hash).map(|(index, _)| { diff --git a/state/src/traits.rs b/state/src/traits.rs index f54448e4c1..40d94688f7 100644 --- a/state/src/traits.rs +++ b/state/src/traits.rs @@ -17,7 +17,7 @@ use ckey::{public_to_address, Address, Public, Signature}; use cmerkle::Result as TrieResult; use ctypes::transaction::ShardTransaction; -use ctypes::{BlockNumber, CommonParams, ShardId, Tracker}; +use ctypes::{BlockNumber, CommonParams, ShardId, Tracker, TxHash}; use cvm::ChainTimeInfo; use primitives::{Bytes, H160, H256}; @@ -88,7 +88,7 @@ pub trait TopStateView { Ok(*self.metadata()?.expect("Metadata must exist").number_of_shards()) } - fn shard_id_by_hash(&self, tx_hash: &H256) -> TrieResult> { + fn shard_id_by_hash(&self, tx_hash: &TxHash) -> TrieResult> { Ok(self.metadata()?.and_then(|metadata| metadata.shard_id_by_hash(tx_hash))) } @@ -166,7 +166,7 @@ pub trait TopState { /// Set the regular key of account `owner_public` fn set_regular_key(&mut self, owner_public: &Public, key: &Public) -> StateResult<()>; - fn create_shard(&mut self, fee_payer: &Address, tx_hash: H256, users: Vec
) -> StateResult<()>; + fn create_shard(&mut self, fee_payer: &Address, tx_hash: TxHash, users: Vec
) -> StateResult<()>; fn change_shard_owners(&mut self, shard_id: ShardId, owners: &[Address], sender: &Address) -> StateResult<()>; fn change_shard_users(&mut self, shard_id: ShardId, users: &[Address], sender: &Address) -> StateResult<()>; @@ -174,8 +174,8 @@ pub trait TopState { fn set_shard_owners(&mut self, shard_id: ShardId, new_owners: Vec
) -> StateResult<()>; fn set_shard_users(&mut self, shard_id: ShardId, new_users: Vec
) -> StateResult<()>; - fn store_text(&mut self, key: &H256, text: Text, sig: &Signature) -> StateResult<()>; - fn remove_text(&mut self, key: &H256, sig: &Signature) -> StateResult<()>; + fn store_text(&mut self, key: &TxHash, text: Text, sig: &Signature) -> StateResult<()>; + fn remove_text(&mut self, key: &TxHash, sig: &Signature) -> StateResult<()>; fn increase_term_id(&mut self, last_term_finished_block_num: u64) -> StateResult<()>; diff --git a/sync/src/transaction/extension.rs b/sync/src/transaction/extension.rs index 4eb1aa912c..892f8f390b 100644 --- a/sync/src/transaction/extension.rs +++ b/sync/src/transaction/extension.rs @@ -21,8 +21,8 @@ use std::time::Duration; use ccore::{BlockChainClient, UnverifiedTransaction}; use cnetwork::{Api, NetworkExtension, NodeId}; use ctimer::TimerToken; +use ctypes::TxHash; use never_type::Never; -use primitives::H256; use rlp::{Encodable, UntrustedRlp}; use super::message::Message; @@ -33,12 +33,12 @@ const MAX_HISTORY_SIZE: usize = 100_000; #[derive(Default)] struct KnownTxs { - history_set: HashSet, - history_queue: VecDeque, + history_set: HashSet, + history_queue: VecDeque, } impl KnownTxs { - fn push(&mut self, hash: H256) { + fn push(&mut self, hash: TxHash) { debug_assert!(!self.history_set.contains(&hash)); self.history_set.insert(hash); self.history_queue.push_back(hash); @@ -47,7 +47,7 @@ impl KnownTxs { } } - fn contains(&mut self, hash: &H256) -> bool { + fn contains(&mut self, hash: &TxHash) -> bool { self.history_set.contains(hash) } } diff --git a/types/src/lib.rs b/types/src/lib.rs index cb3229e222..05e9fbf1c4 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -30,6 +30,7 @@ extern crate serde_json; mod block_hash; mod common_params; mod tracker; +mod tx_hash; pub mod errors; pub mod header; @@ -43,3 +44,4 @@ pub use block_hash::BlockHash; pub use common_params::CommonParams; pub use header::Header; pub use tracker::Tracker; +pub use tx_hash::TxHash; diff --git a/types/src/transaction/action.rs b/types/src/transaction/action.rs index 66884afdc2..cfe40405ee 100644 --- a/types/src/transaction/action.rs +++ b/types/src/transaction/action.rs @@ -23,7 +23,7 @@ use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use crate::errors::SyntaxError; use crate::transaction::{AssetMintOutput, AssetTransferInput, AssetTransferOutput, ShardTransaction}; -use crate::{CommonParams, ShardId, Tracker}; +use crate::{CommonParams, ShardId, Tracker, TxHash}; const PAY: u8 = 0x02; const SET_REGULAR_KEY: u8 = 0x03; @@ -126,7 +126,7 @@ pub enum Action { signature: Signature, }, Remove { - hash: H256, + hash: TxHash, signature: Signature, }, } @@ -1037,7 +1037,7 @@ mod tests { #[test] fn encode_and_decode_remove() { rlp_encode_and_decode_test!(Action::Remove { - hash: H256::random(), + hash: H256::random().into(), signature: Signature::random(), }); } diff --git a/types/src/transaction/shard.rs b/types/src/transaction/shard.rs index f10032c9a0..f6cd0d4f88 100644 --- a/types/src/transaction/shard.rs +++ b/types/src/transaction/shard.rs @@ -21,7 +21,7 @@ use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; use super::{AssetMintOutput, AssetTransferInput, AssetTransferOutput, HashingError, PartialHashing}; use crate::util::tag::Tag; -use crate::{ShardId, Tracker}; +use crate::{ShardId, Tracker, TxHash}; /// Shard Transaction type. #[derive(Debug, Clone, PartialEq, Eq)] @@ -66,7 +66,7 @@ pub enum ShardTransaction { WrapCCC { network_id: NetworkId, shard_id: ShardId, - tx_hash: H256, + tx_hash: TxHash, output: AssetWrapCCCOutput, }, } @@ -85,7 +85,7 @@ impl ShardTransaction { .. } = self { - return (*tx_hash).into() + return (**tx_hash).into() } blake256(&*self.rlp_bytes()).into() } diff --git a/types/src/transaction/transaction.rs b/types/src/transaction/transaction.rs index c5a9c54aab..57f57275d3 100644 --- a/types/src/transaction/transaction.rs +++ b/types/src/transaction/transaction.rs @@ -16,12 +16,11 @@ use ccrypto::blake256; use ckey::NetworkId; -use primitives::H256; use rlp::RlpStream; use super::Action; use super::{AssetWrapCCCOutput, ShardTransaction}; -use crate::Tracker; +use crate::{Tracker, TxHash}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Transaction { @@ -45,11 +44,11 @@ impl Transaction { s.append(&self.action); } - /// The message hash of the tranasction. - pub fn hash(&self) -> H256 { + /// The message hash of the transaction. + pub fn hash(&self) -> TxHash { let mut stream = RlpStream::new(); self.rlp_append_unsigned(&mut stream); - blake256(stream.as_raw()) + blake256(stream.as_raw()).into() } pub fn tracker(&self) -> Option { diff --git a/types/src/tx_hash.rs b/types/src/tx_hash.rs new file mode 100644 index 0000000000..b674265f2b --- /dev/null +++ b/types/src/tx_hash.rs @@ -0,0 +1,109 @@ +// Copyright 2019 Kodebox, Inc. +// This file is part of CodeChain. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +use std::fmt::{self, Display, Formatter}; +use std::ops::Deref; + +use primitives::H256; +use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; + + +#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, Debug, Deserialize, Serialize)] +pub struct TxHash(H256); + +impl From for TxHash { + fn from(h: H256) -> Self { + Self(h) + } +} + +impl Deref for TxHash { + type Target = H256; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for TxHash { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + +impl Encodable for TxHash { + fn rlp_append(&self, s: &mut RlpStream) { + self.0.rlp_append(s); + } +} + +impl Decodable for TxHash { + fn decode(rlp: &UntrustedRlp) -> Result { + Ok(H256::decode(rlp)?.into()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + use rlp::{self, rlp_encode_and_decode_test}; + + use super::*; + + #[test] + fn hash_of_tx_hash_and_h256_are_the_same() { + let h256 = H256::random(); + let tx_hash = TxHash(h256); + + let mut hasher_of_h256 = DefaultHasher::new(); + let mut hasher_of_tracker = DefaultHasher::new(); + + h256.hash(&mut hasher_of_h256); + tx_hash.hash(&mut hasher_of_tracker); + + assert_eq!(hasher_of_h256.finish(), hasher_of_tracker.finish()); + } + + #[test] + fn rlp_of_tx_hash_can_be_decoded_to_h256() { + let h256 = H256::random(); + let tx_hash = TxHash(h256); + + let encoded = rlp::encode(&tx_hash); + let decoded = rlp::decode(&*encoded); + + assert_eq!(h256, decoded); + } + + #[test] + fn rlp_of_h256_can_be_decoded_to_tx_hash() { + let h256 = H256::random(); + + let encoded = rlp::encode(&h256); + let decoded = rlp::decode(&*encoded); + + let tx_hash = TxHash(h256); + assert_eq!(tx_hash, decoded); + } + + #[test] + fn rlp() { + rlp_encode_and_decode_test!(TxHash(H256::random())); + } +}