Merge branch 'master' of https://github.com/gavofyork/ethcore into evm

This commit is contained in:
debris 2016-01-09 18:41:12 +01:00
commit 9cc88e2cb1
28 changed files with 372 additions and 465 deletions

File diff suppressed because one or more lines are too long

34
res/null_morden.json Normal file
View File

@ -0,0 +1,34 @@
{
"engineName": "NullEngine",
"params": {
"accountStartNonce": "0x0100000",
"frontierCompatibilityModeLimit": "0xfffa2990",
"maximumExtraDataSize": "0x20",
"tieBreakingGas": false,
"minGasLimit": "0x1388",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar": "",
"networkID" : "0x2"
},
"genesis": {
"nonce": "0x00006d6f7264656e",
"difficulty": "0x20000",
"mixHash": "0x00000000000000000000000000000000000000647572616c65787365646c6578",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x",
"gasLimit": "0x2fefd8"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376", "nonce": "1048576" }
}
}

View File

@ -1,12 +1,4 @@
use std::collections::HashMap; use util::*;
use util::hash::*;
use util::sha3::*;
use util::hashdb::*;
use util::bytes::*;
use util::trie::*;
use util::rlp::*;
use util::uint::*;
use std::cell::*;
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] ); pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );
@ -66,7 +58,7 @@ impl Account {
} }
/// Create a new contract account. /// Create a new contract account.
/// NOTE: make sure you use `set_code` on this before `commit`ing. /// NOTE: make sure you use `init_code` on this before `commit`ing.
pub fn new_contract(balance: U256) -> Account { pub fn new_contract(balance: U256) -> Account {
Account { Account {
balance: balance, balance: balance,
@ -78,9 +70,16 @@ impl Account {
} }
} }
/// Reset this account to the status of a not-yet-initialised contract.
/// NOTE: Account should have `init_code()` called on it later.
pub fn reset_code(&mut self) {
self.code_hash = None;
self.code_cache = vec![];
}
/// Set this account's code to the given code. /// Set this account's code to the given code.
/// NOTE: Account should have been created with `new_contract`. /// NOTE: Account should have been created with `new_contract()` or have `reset_code()` called on it.
pub fn set_code(&mut self, code: Bytes) { pub fn init_code(&mut self, code: Bytes) {
assert!(self.code_hash.is_none()); assert!(self.code_hash.is_none());
self.code_cache = code; self.code_cache = code;
} }
@ -224,7 +223,7 @@ fn storage_at() {
let mut a = Account::new_contract(U256::from(69u8)); let mut a = Account::new_contract(U256::from(69u8));
a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64))); a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64)));
a.commit_storage(&mut db); a.commit_storage(&mut db);
a.set_code(vec![]); a.init_code(vec![]);
a.commit_code(&mut db); a.commit_code(&mut db);
a.rlp() a.rlp()
}; };
@ -241,7 +240,7 @@ fn note_code() {
let rlp = { let rlp = {
let mut a = Account::new_contract(U256::from(69u8)); let mut a = Account::new_contract(U256::from(69u8));
a.set_code(vec![0x55, 0x44, 0xffu8]); a.init_code(vec![0x55, 0x44, 0xffu8]);
a.commit_code(&mut db); a.commit_code(&mut db);
a.rlp() a.rlp()
}; };
@ -267,7 +266,7 @@ fn commit_storage() {
fn commit_code() { fn commit_code() {
let mut a = Account::new_contract(U256::from(69u8)); let mut a = Account::new_contract(U256::from(69u8));
let mut db = OverlayDB::new_temp(); let mut db = OverlayDB::new_temp();
a.set_code(vec![0x55, 0x44, 0xffu8]); a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_hash(), SHA3_EMPTY); assert_eq!(a.code_hash(), SHA3_EMPTY);
a.commit_code(&mut db); a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb"); assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");

View File

@ -1,12 +1,6 @@
use std::collections::hash_set::*; use util::*;
use util::hash::*;
use util::bytes::*;
use util::uint::*;
use util::error::*;
use util::overlaydb::*;
use transaction::*; use transaction::*;
use receipt::*; use receipt::*;
use blockchain::*;
use engine::*; use engine::*;
use header::*; use header::*;
use env_info::*; use env_info::*;
@ -130,7 +124,7 @@ impl<'engine> OpenBlock<'engine> {
} }
/// Turn this into a `ClosedBlock`. A BlockChain must be provided in order to figure ou the uncles. /// Turn this into a `ClosedBlock`. A BlockChain must be provided in order to figure ou the uncles.
pub fn close(self, _bc: &BlockChain) -> ClosedBlock { unimplemented!(); } pub fn close(self, _uncles: Vec<Header>) -> ClosedBlock<'engine> { unimplemented!(); }
} }
impl<'engine> IsBlock for OpenBlock<'engine> { impl<'engine> IsBlock for OpenBlock<'engine> {
@ -158,3 +152,14 @@ impl SealedBlock {
impl IsBlock for SealedBlock { impl IsBlock for SealedBlock {
fn block(&self) -> &Block { &self.block } fn block(&self) -> &Block { &self.block }
} }
#[test]
fn open_block() {
use super::*;
use spec::*;
let engine = Spec::new_test().to_engine().unwrap();
let genesis_header = engine.spec().genesis_header();
let mut db = OverlayDB::new_temp();
engine.spec().ensure_db_good(&mut db);
let b = OpenBlock::new(engine.deref(), db, &genesis_header, vec![genesis_header.hash()]);
}

View File

@ -1,18 +1,7 @@
//! Fast access to blockchain data. //! Fast access to blockchain data.
use std::collections::HashMap; use util::*;
use std::cell::RefCell;
use std::path::Path;
use std::hash::Hash;
use rocksdb::{DB, WriteBatch, Writable}; use rocksdb::{DB, WriteBatch, Writable};
use heapsize::HeapSizeOf;
use util::hash::*;
use util::uint::*;
use util::rlp::*;
use util::hashdb::*;
use util::sha3::*;
use util::bytes::*;
use util::squeeze::*;
use header::*; use header::*;
use extras::*; use extras::*;
use transaction::*; use transaction::*;
@ -86,18 +75,19 @@ impl BlockChain {
/// extern crate ethcore; /// extern crate ethcore;
/// use std::env; /// use std::env;
/// use std::str::FromStr; /// use std::str::FromStr;
/// use ethcore::genesis::*; /// use ethcore::spec::*;
/// use ethcore::blockchain::*; /// use ethcore::blockchain::*;
/// use ethcore::ethereum;
/// use util::hash::*; /// use util::hash::*;
/// use util::uint::*; /// use util::uint::*;
/// ///
/// fn main() { /// fn main() {
/// let genesis = Genesis::new_frontier(); /// let spec = ethereum::new_frontier();
/// ///
/// let mut dir = env::temp_dir(); /// let mut dir = env::temp_dir();
/// dir.push(H32::random().hex()); /// dir.push(H32::random().hex());
/// ///
/// let bc = BlockChain::new(genesis.block(), &dir); /// let bc = BlockChain::new(&spec.genesis_block(), &dir);
/// ///
/// let genesis_hash = "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"; /// let genesis_hash = "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3";
/// assert_eq!(bc.genesis_hash(), H256::from_str(genesis_hash).unwrap()); /// assert_eq!(bc.genesis_hash(), H256::from_str(genesis_hash).unwrap());

View File

@ -1,12 +1,4 @@
use std::cmp::min; use util::*;
use std::fmt;
use util::uint::*;
use util::hash::*;
use util::sha3::*;
use util::bytes::*;
use rustc_serialize::json::Json;
use std::io::Write;
use util::crypto::*;
use crypto::sha2::Sha256; use crypto::sha2::Sha256;
use crypto::ripemd160::Ripemd160; use crypto::ripemd160::Ripemd160;
use crypto::digest::Digest; use crypto::digest::Digest;
@ -95,8 +87,8 @@ pub fn new_builtin_exec(name: &str) -> Option<Box<Fn(&[u8], &mut [u8])>> {
it.copy_raw(input); it.copy_raw(input);
if it.v == H256::from(&U256::from(27)) || it.v == H256::from(&U256::from(28)) { if it.v == H256::from(&U256::from(27)) || it.v == H256::from(&U256::from(28)) {
let s = Signature::from_rsv(&it.r, &it.s, it.v[31] - 27); let s = Signature::from_rsv(&it.r, &it.s, it.v[31] - 27);
if is_valid(&s) { if ec::is_valid(&s) {
match recover(&s, &it.hash) { match ec::recover(&s, &it.hash) {
Ok(p) => { Ok(p) => {
let r = p.as_slice().sha3(); let r = p.as_slice().sha3();
// NICE: optimise and separate out into populate-like function // NICE: optimise and separate out into populate-like function

8
src/common.rs Normal file
View File

@ -0,0 +1,8 @@
pub use util::*;
pub use env_info::*;
pub use evm_schedule::*;
pub use views::*;
pub use builtin::*;
pub use header::*;
pub use account::*;
pub use transaction::*;

View File

@ -1,16 +1,6 @@
use std::collections::hash_map::*; use common::*;
use util::bytes::*;
use util::hash::*;
use util::uint::*;
use util::rlp::*;
use util::semantic_version::*;
use util::error::*;
use header::Header;
use transaction::Transaction;
use block::Block; use block::Block;
use spec::Spec; use spec::Spec;
use evm_schedule::EvmSchedule;
use env_info::EnvInfo;
/// A consensus mechanism for the chain. Generally either proof-of-work or proof-of-stake-based. /// A consensus mechanism for the chain. Generally either proof-of-work or proof-of-stake-based.
/// Provides hooks into each of the major parts of block import. /// Provides hooks into each of the major parts of block import.
@ -35,8 +25,8 @@ pub trait Engine {
fn evm_schedule(&self, env_info: &EnvInfo) -> EvmSchedule; fn evm_schedule(&self, env_info: &EnvInfo) -> EvmSchedule;
/// Some intrinsic operation parameters; by default they take their value from the `spec()`'s `engine_params`. /// Some intrinsic operation parameters; by default they take their value from the `spec()`'s `engine_params`.
fn maximum_extra_data_size(&self, _env_info: &EnvInfo) -> usize { decode(&self.spec().engine_params.get("maximum_extra_data_size").unwrap()) } fn maximum_extra_data_size(&self, _env_info: &EnvInfo) -> usize { decode(&self.spec().engine_params.get("maximumExtraDataSize").unwrap()) }
fn account_start_nonce(&self) -> U256 { decode(&self.spec().engine_params.get("account_start_nonce").unwrap()) } fn account_start_nonce(&self) -> U256 { decode(&self.spec().engine_params.get("accountStartNonce").unwrap()) }
/// Block transformation functions, before and after the transactions. /// Block transformation functions, before and after the transactions.
fn on_new_block(&self, _block: &mut Block) {} fn on_new_block(&self, _block: &mut Block) {}

View File

@ -1,5 +1,4 @@
use util::uint::*; use util::*;
use util::hash::*;
/// Simple vector of hashes, should be at most 256 items large, can be smaller if being used /// Simple vector of hashes, should be at most 256 items large, can be smaller if being used
/// for a block whose number is less than 257. /// for a block whose number is less than 257.

View File

@ -1,4 +1,4 @@
use util::uint::*; use util::*;
#[inline] #[inline]
pub fn ether() -> U256 { U256::exp10(18) } pub fn ether() -> U256 { U256::exp10(18) }

View File

@ -1,10 +1,7 @@
//use util::error::*; use common::*;
use util::rlp::decode;
use engine::Engine;
use spec::Spec;
use block::*; use block::*;
use evm_schedule::EvmSchedule; use spec::*;
use env_info::EnvInfo; use engine::*;
/// Engine using Ethash proof-of-work consensus algorithm, suitable for Ethereum /// Engine using Ethash proof-of-work consensus algorithm, suitable for Ethereum
/// mainnet chains in the Olympic, Frontier and Homestead eras. /// mainnet chains in the Olympic, Frontier and Homestead eras.
@ -31,3 +28,19 @@ impl Engine for Ethash {
} }
// TODO: test for on_close_block. // TODO: test for on_close_block.
#[test]
fn playpen() {
use super::*;
use state::*;
let engine = new_morden().to_engine().unwrap();
let genesis_header = engine.spec().genesis_header();
let mut db = OverlayDB::new_temp();
engine.spec().ensure_db_good(&mut db);
assert!(SecTrieDB::new(&db, &genesis_header.state_root).contains(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")));
{
let s = State::from_existing(db.clone(), genesis_header.state_root.clone(), engine.account_start_nonce());
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64));
}
let b = OpenBlock::new(engine.deref(), db, &genesis_header, vec![genesis_header.hash()]);
// let c = b.close();
}

72
src/ethereum/mod.rs Normal file
View File

@ -0,0 +1,72 @@
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
pub mod ethash;
pub mod denominations;
pub use self::ethash::*;
pub use self::denominations::*;
use super::spec::*;
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec { Spec::from_json_utf8(include_bytes!("res/olympic.json")) }
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec { Spec::from_json_utf8(include_bytes!("res/frontier.json")) }
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec { Spec::from_json_utf8(include_bytes!("res/frontier_test.json")) }
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec { Spec::from_json_utf8(include_bytes!("res/homestead_test.json")) }
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec { Spec::from_json_utf8(include_bytes!("res/morden.json")) }
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
#[test]
fn ensure_db_good() {
let engine = new_morden().to_engine().unwrap();
let genesis_header = engine.spec().genesis_header();
let mut db = OverlayDB::new_temp();
engine.spec().ensure_db_good(&mut db);
let s = State::from_existing(db.clone(), genesis_header.state_root.clone(), engine.account_start_nonce());
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000002")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000003")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000004")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")), U256::from(1u64) << 200);
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000000")), U256::from(0u64));
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(*morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
morden.to_engine();
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(*frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
frontier.to_engine();
}
}

View File

@ -0,0 +1,33 @@
{
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
"frontierCompatibilityModeLimit": "0xffffffffffffffff",
"maximumExtraDataSize": "0x20",
"tieBreakingGas": false,
"minGasLimit": "0x1388",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b",
"networkID" : "0x1"
},
"genesis": {
"nonce": "0x0000000000000042",
"difficulty": "0x400000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
}
}

View File

@ -0,0 +1,33 @@
{
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
"frontierCompatibilityModeLimit": "0xffffffff",
"maximumExtraDataSize": "0x20",
"minGasLimit": "0x1388",
"tieBreakingGas": false,
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b",
"networkID" : "0x1"
},
"genesis": {
"nonce": "0x0000000000000042",
"difficulty": "0x400000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
}
}

View File

@ -0,0 +1,41 @@
{
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
"frontierCompatibilityModeLimit": "0xffffffff",
"maximumExtraDataSize": "0x0400",
"tieBreakingGas": false,
"minGasLimit": "125000",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x08",
"blockReward": "0x14D1120D7B160000",
"registrar": "5e70c0bbcd5636e0f9f9316e9f8633feb64d4050",
"networkID" : "0x0"
},
"genesis": {
"nonce": "0x000000000000002a",
"difficulty": "0x20000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x",
"gasLimit": "0x2fefd8"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"e6716f9544a56c530d868e4bfbacb172315bdead": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"b9c015918bdaba24b4ff057a92a3873d6eb201be": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"2ef47100e0787b915105fd5e3f4ff6752079d5cb": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"cd2a3d9f938e13cd947ec05abc7fe734df8dd826": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"6c386a4b26f73c802f34673f7248bb118f97424a": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"e4157b34ea9615cfbde6b4fda419828124b70c78": { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
}
}

View File

@ -1,4 +1,3 @@
use std::mem;
use util::hash::*; use util::hash::*;
use util::uint::*; use util::uint::*;
use util::rlp::*; use util::rlp::*;
@ -89,7 +88,7 @@ impl<'a> Executive<'a> {
} }
} }
fn call(e: &mut Executive<'a>, p: &EvmParams) -> ExecutiveResult { fn call(_e: &mut Executive<'a>, _p: &EvmParams) -> ExecutiveResult {
//let _ext = Externalities::from_executive(e, &p); //let _ext = Externalities::from_executive(e, &p);
ExecutiveResult::Ok ExecutiveResult::Ok
} }
@ -97,6 +96,7 @@ impl<'a> Executive<'a> {
fn create(e: &mut Executive<'a>, params: &EvmParams) -> ExecutiveResult { fn create(e: &mut Executive<'a>, params: &EvmParams) -> ExecutiveResult {
//self.state.require_or_from(&self.params.address, false, ||Account::new_contract(U256::from(0))); //self.state.require_or_from(&self.params.address, false, ||Account::new_contract(U256::from(0)));
//TODO: ensure that account at given address is created //TODO: ensure that account at given address is created
e.state.new_contract(&params.address);
e.state.transfer_balance(&params.sender, &params.address, &params.value); e.state.transfer_balance(&params.sender, &params.address, &params.value);
let code = { let code = {
@ -110,13 +110,13 @@ impl<'a> Executive<'a> {
ExecutiveResult::Ok ExecutiveResult::Ok
}, },
EvmResult::Return(output) => { EvmResult::Return(output) => {
//e.state.set_code(&params.address, output); e.state.init_code(&params.address, output);
ExecutiveResult::Ok ExecutiveResult::Ok
}, },
EvmResult::OutOfGas => { EvmResult::OutOfGas => {
ExecutiveResult::OutOfGas ExecutiveResult::OutOfGas
}, },
err => { _err => {
ExecutiveResult::InternalError ExecutiveResult::InternalError
} }
} }
@ -255,21 +255,17 @@ mod tests {
use evm_schedule::*; use evm_schedule::*;
use super::contract_address; use super::contract_address;
struct TestEngine { struct TestEngine;
spec: Spec
}
impl TestEngine { impl TestEngine {
fn new() -> Self { fn new() -> Self {
TestEngine { TestEngine
spec: Spec::new_like_frontier()
}
} }
} }
impl Engine for TestEngine { impl Engine for TestEngine {
fn name(&self) -> &str { "TestEngine" } fn name(&self) -> &str { "TestEngine" }
fn spec(&self) -> &Spec { &self.spec } fn spec(&self) -> &Spec { unimplemented!() }
fn evm_schedule(&self, _env_info: &EnvInfo) -> EvmSchedule { EvmSchedule::new_frontier() } fn evm_schedule(&self, _env_info: &EnvInfo) -> EvmSchedule { EvmSchedule::new_frontier() }
} }
@ -311,8 +307,6 @@ mod tests {
let sender = Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(); let sender = Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap();
let address = contract_address(&sender, &U256::zero()); let address = contract_address(&sender, &U256::zero());
let next_address = contract_address(&address, &U256::zero()); let next_address = contract_address(&address, &U256::zero());
println!("address: {:?}", address);
println!("next address: {:?}", next_address);
let mut params = EvmParams::new(); let mut params = EvmParams::new();
params.address = address.clone(); params.address = address.clone();
params.sender = sender.clone(); params.sender = sender.clone();
@ -330,7 +324,6 @@ mod tests {
} }
assert_eq!(state.storage_at(&address, &H256::new()), H256::from(next_address.clone())); assert_eq!(state.storage_at(&address, &H256::new()), H256::from(next_address.clone()));
//assert_eq!(state.code(&next_address).unwrap(), "601080600c6000396000f3006000355415600957005b602035600035".from_hex().unwrap()); assert_eq!(state.code(&next_address).unwrap(), "6000355415600957005b602035600035".from_hex().unwrap());
//assert!(false);
} }
} }

View File

@ -336,21 +336,15 @@ mod tests {
use evm_schedule::*; use evm_schedule::*;
use spec::*; use spec::*;
struct TestEngine { struct TestEngine;
spec: Spec
}
impl TestEngine { impl TestEngine {
fn new() -> Self { fn new() -> Self { TestEngine }
TestEngine {
spec: Spec::new_like_frontier()
}
}
} }
impl Engine for TestEngine { impl Engine for TestEngine {
fn name(&self) -> &str { "TestEngine" } fn name(&self) -> &str { "TestEngine" }
fn spec(&self) -> &Spec { &self.spec } fn spec(&self) -> &Spec { unimplemented!() }
fn evm_schedule(&self, _env_info: &EnvInfo) -> EvmSchedule { EvmSchedule::new_frontier() } fn evm_schedule(&self, _env_info: &EnvInfo) -> EvmSchedule { EvmSchedule::new_frontier() }
} }
@ -520,8 +514,8 @@ mod tests {
params.code = address_code.clone(); params.code = address_code.clone();
let mut state = State::new_temp(); let mut state = State::new_temp();
state.set_code(&address, address_code); state.init_code(&address, address_code);
state.set_code(&sender, sender_code); state.init_code(&sender, sender_code);
let info = EnvInfo::new(); let info = EnvInfo::new();
let engine = TestEngine::new(); let engine = TestEngine::new();

View File

@ -1,8 +1,5 @@
use heapsize::HeapSizeOf; use util::*;
use rocksdb::{DB, Writable}; use rocksdb::{DB, Writable};
use util::uint::*;
use util::hash::*;
use util::rlp::*;
/// Represents index of extra data in database /// Represents index of extra data in database
#[derive(Copy, Clone)] #[derive(Copy, Clone)]

View File

@ -1,123 +0,0 @@
use std::io::Read;
use std::str::FromStr;
use std::collections::HashMap;
use rustc_serialize::base64::FromBase64;
use rustc_serialize::json::Json;
use rustc_serialize::hex::FromHex;
use flate2::read::GzDecoder;
use util::rlp::*;
use util::hash::*;
use util::uint::*;
use util::sha3::*;
use account::*;
use header::*;
/// Converts file from base64 gzipped bytes to json
fn base_to_json(source: &[u8]) -> Json {
// there is probably no need to store genesis in based64 gzip,
// but that's what go does, and it was easy to load it this way
let data = source.from_base64().expect("Genesis block is malformed!");
let data_ref: &[u8] = &data;
let mut decoder = GzDecoder::new(data_ref).expect("Gzip is invalid");
let mut s: String = "".to_string();
decoder.read_to_string(&mut s).expect("Gzip is invalid");
Json::from_str(&s).expect("Json is invalid")
}
pub struct Genesis {
block: Vec<u8>,
state: HashMap<Address, Account>
}
impl Genesis {
/// Creates genesis block for frontier network
pub fn new_frontier() -> Genesis {
let root = H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap();
let json = base_to_json(include_bytes!("../res/genesis_frontier"));
let (header, state) = Self::load_genesis_json(json, root);
Self::new_from_header_and_state(header, state)
}
/// Creates genesis block from header and state hashmap
pub fn new_from_header_and_state(header: Header, state: HashMap<Address, Account>) -> Genesis {
let empty_list = RlpStream::new_list(0).out();
let mut stream = RlpStream::new_list(3);
stream.append(&header);
stream.append_raw(&empty_list, 1);
stream.append_raw(&empty_list, 1);
Genesis {
block: stream.out(),
state: state
}
}
/// Loads genesis block from json file
fn load_genesis_json(json: Json, state_root: H256) -> (Header, HashMap<Address, Account>) {
// once we commit ourselves to some json parsing library (serde?)
// move it to proper data structure
let empty_list = RlpStream::new_list(0).out();
let empty_list_sha3 = empty_list.sha3();
let empty_data = encode(&"");
let empty_data_sha3 = empty_data.sha3();
let mut state = HashMap::new();
let accounts = json["alloc"].as_object().expect("Missing genesis state");
for (address, acc) in accounts.iter() {
let addr = Address::from_str(address).unwrap();
let o = acc.as_object().unwrap();
let balance = U256::from_dec_str(o["balance"].as_string().unwrap()).unwrap();
state.insert(addr, Account::new_basic(balance, U256::from(0)));
}
let header = Header {
parent_hash: H256::from_str(&json["parentHash"].as_string().unwrap()[2..]).unwrap(),
uncles_hash: empty_list_sha3.clone(),
author: Address::from_str(&json["coinbase"].as_string().unwrap()[2..]).unwrap(),
state_root: state_root,
transactions_root: empty_data_sha3.clone(),
receipts_root: empty_data_sha3.clone(),
log_bloom: H2048::new(),
difficulty: U256::from_str(&json["difficulty"].as_string().unwrap()[2..]).unwrap(),
number: U256::from(0u8),
gas_limit: U256::from_str(&json["gasLimit"].as_string().unwrap()[2..]).unwrap(),
gas_used: U256::from(0u8),
timestamp: U256::from_str(&json["timestamp"].as_string().unwrap()[2..]).unwrap(),
extra_data: json["extraData"].as_string().unwrap()[2..].from_hex().unwrap(),
seal: {
// ethash specific fields
let mixhash = H256::from_str(&json["mixhash"].as_string().unwrap()[2..]).unwrap();
let nonce = H64::from_str(&json["nonce"].as_string().unwrap()[2..]).unwrap();
vec![encode(&mixhash), encode(&nonce)]
}
};
(header, state)
}
/// Returns genesis block
pub fn block(&self) -> &[u8] {
&self.block
}
/// Returns genesis block state
pub fn state(&self) -> &HashMap<Address, Account> {
&self.state
}
// not sure if this one is needed
pub fn drain(self) -> (Vec<u8>, HashMap<Address, Account>) {
(self.block, self.state)
}
}
#[test]
fn test_genesis() {
use views::*;
let g = Genesis::new_frontier();
let view = BlockView::new(&g.block).header_view();
let genesis_hash = H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap();
assert_eq!(view.sha3(), genesis_hash);
}

View File

@ -1,7 +1,4 @@
use util::hash::*; use util::*;
use util::bytes::*;
use util::uint::*;
use util::rlp::*;
/// Type for a 2048-bit log-bloom, as used by our blocks. /// Type for a 2048-bit log-bloom, as used by our blocks.
pub type LogBloom = H2048; pub type LogBloom = H2048;
@ -38,6 +35,8 @@ pub struct Header {
pub difficulty: U256, pub difficulty: U256,
pub seal: Vec<Bytes>, pub seal: Vec<Bytes>,
pub hash: RefCell<Option<H256>>, //TODO: make this private
} }
impl Header { impl Header {
@ -61,6 +60,21 @@ impl Header {
difficulty: ZERO_U256.clone(), difficulty: ZERO_U256.clone(),
seal: vec![], seal: vec![],
hash: RefCell::new(None),
}
}
pub fn hash(&self) -> H256 {
let mut hash = self.hash.borrow_mut();
match &mut *hash {
&mut Some(ref h) => h.clone(),
hash @ &mut None => {
let mut stream = RlpStream::new();
stream.append(self);
let h = stream.as_raw().sha3();
*hash = Some(h.clone());
h.clone()
}
} }
} }
} }
@ -84,6 +98,7 @@ impl Decodable for Header {
timestamp: try!(Decodable::decode(&d[11])), timestamp: try!(Decodable::decode(&d[11])),
extra_data: try!(Decodable::decode(&d[12])), extra_data: try!(Decodable::decode(&d[12])),
seal: vec![], seal: vec![],
hash: RefCell::new(None),
}; };
for i in 13..d.len() { for i in 13..d.len() {

View File

@ -85,11 +85,7 @@ extern crate evmjit;
extern crate ethcore_util as util; extern crate ethcore_util as util;
//use util::error::*; pub mod common;
pub use util::hash::*;
pub use util::uint::*;
pub use util::bytes::*;
pub mod env_info; pub mod env_info;
pub mod engine; pub mod engine;
pub mod state; pub mod state;
@ -97,15 +93,14 @@ pub mod account;
pub mod header; pub mod header;
pub mod transaction; pub mod transaction;
pub mod receipt; pub mod receipt;
pub mod denominations;
pub mod null_engine; pub mod null_engine;
pub mod evm_schedule; pub mod evm_schedule;
pub mod builtin; pub mod builtin;
pub mod spec; pub mod spec;
pub mod genesis;
pub mod views; pub mod views;
pub mod blockchain; pub mod blockchain;
pub mod extras; pub mod extras;
pub mod evm; pub mod evm;
pub mod ethash;
pub mod block; pub mod block;
pub mod ethereum;

View File

@ -1,5 +1,4 @@
use util::hash::*; use util::*;
use util::uint::*;
/// Information describing execution of a transaction. /// Information describing execution of a transaction.
pub struct Receipt { pub struct Receipt {

View File

@ -1,25 +1,7 @@
use std::io::Read; use common::*;
use std::collections::HashMap;
use std::cell::*;
use std::str::FromStr;
use rustc_serialize::base64::FromBase64;
use rustc_serialize::json::Json;
use rustc_serialize::hex::FromHex;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use util::uint::*; use engine::*;
use util::hash::*; use null_engine::*;
use util::bytes::*;
use util::triehash::*;
use util::error::*;
use util::rlp::*;
use util::sha3::*;
use account::*;
use engine::Engine;
use builtin::Builtin;
use null_engine::NullEngine;
use ethash::Ethash;
use denominations::*;
use header::*;
/// Converts file from base64 gzipped bytes to json /// Converts file from base64 gzipped bytes to json
pub fn gzip64res_to_json(source: &[u8]) -> Json { pub fn gzip64res_to_json(source: &[u8]) -> Json {
@ -94,7 +76,7 @@ impl Spec {
pub fn to_engine(self) -> Result<Box<Engine>, EthcoreError> { pub fn to_engine(self) -> Result<Box<Engine>, EthcoreError> {
match self.engine_name.as_ref() { match self.engine_name.as_ref() {
"NullEngine" => Ok(NullEngine::new_boxed(self)), "NullEngine" => Ok(NullEngine::new_boxed(self)),
"Ethash" => Ok(Ethash::new_boxed(self)), "Ethash" => Ok(super::ethereum::Ethash::new_boxed(self)),
_ => Err(EthcoreError::UnknownName) _ => Err(EthcoreError::UnknownName)
} }
} }
@ -107,7 +89,7 @@ impl Spec {
Ref::map(self.state_root_memo.borrow(), |x|x.as_ref().unwrap()) Ref::map(self.state_root_memo.borrow(), |x|x.as_ref().unwrap())
} }
fn genesis_header(&self) -> Header { pub fn genesis_header(&self) -> Header {
Header { Header {
parent_hash: self.parent_hash.clone(), parent_hash: self.parent_hash.clone(),
timestamp: self.timestamp.clone(), timestamp: self.timestamp.clone(),
@ -129,8 +111,9 @@ impl Spec {
s.out() s.out()
}; };
let r = Rlp::new(&seal); let r = Rlp::new(&seal);
(0..self.seal_fields).map(|i| r.at(i).raw().to_vec()).collect() (0..self.seal_fields).map(|i| r.at(i).as_raw().to_vec()).collect()
}, },
hash: RefCell::new(None),
} }
} }
@ -207,138 +190,14 @@ impl Spec {
} }
} }
/// Returns the builtins map for the standard network of Ethereum Olympic, Frontier and Homestead. /// Ensure that the given state DB has the trie nodes in for the genesis state.
fn standard_builtins() -> HashMap<Address, Builtin> { pub fn ensure_db_good(&self, db: &mut HashDB) {
let mut ret = HashMap::new(); if !db.contains(&self.state_root()) {
ret.insert(Address::from_str("0000000000000000000000000000000000000001").unwrap(), Builtin::from_named_linear("ecrecover", 3000, 0).unwrap()); let mut root = H256::new();
ret.insert(Address::from_str("0000000000000000000000000000000000000002").unwrap(), Builtin::from_named_linear("sha256", 60, 12).unwrap()); let mut t = SecTrieDBMut::new(db, &mut root);
ret.insert(Address::from_str("0000000000000000000000000000000000000003").unwrap(), Builtin::from_named_linear("ripemd160", 600, 120).unwrap()); for (address, account) in self.genesis_state.iter() {
ret.insert(Address::from_str("0000000000000000000000000000000000000004").unwrap(), Builtin::from_named_linear("identity", 15, 3).unwrap()); t.insert(address.as_slice(), &account.rlp());
ret }
}
/// Creates the Olympic network chain spec.
pub fn new_like_olympic() -> Spec {
Spec {
engine_name: "Ethash".to_string(),
engine_params: vec![
("block_reward", encode(&(finney() * U256::from(1500u64)))),
("maximum_extra_data_size", encode(&U256::from(1024u64))),
("account_start_nonce", encode(&U256::from(0u64))),
("gas_limit_bounds_divisor", encode(&1024u64)),
("minimum_difficulty", encode(&131_072u64)),
("difficulty_bound_divisor", encode(&2048u64)),
("duration_limit", encode(&8u64)),
("min_gas_limit", encode(&125_000u64)),
("gas_floor_target", encode(&3_141_592u64)),
].into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0.to_string(), vec.1);
acc
}),
builtins: Self::standard_builtins(),
parent_hash: H256::new(),
author: Address::new(),
difficulty: U256::from(131_072u64),
gas_limit: U256::from(0u64),
gas_used: U256::from(0u64),
timestamp: U256::from(0u64),
extra_data: vec![],
genesis_state: vec![ // TODO: make correct
(Address::new(), Account::new_basic(U256::from(1) << 200, U256::from(0)))
].into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0, vec.1);
acc
}),
seal_fields: 2,
seal_rlp: { let mut r = RlpStream::new_list(2); r.append(&H256::new()); r.append(&0x2au64); r.out() }, // TODO: make correct
state_root_memo: RefCell::new(None),
}
}
/// Creates the Frontier network chain spec, except for the genesis state, which is blank.
pub fn new_like_frontier() -> Spec {
Spec {
engine_name: "Ethash".to_string(),
engine_params: vec![
("block_reward", encode(&(ether() * U256::from(5u64)))),
("maximum_extra_data_size", encode(&U256::from(32u64))),
("account_start_nonce", encode(&U256::from(0u64))),
("gas_limit_bounds_divisor", encode(&1024u64)),
("minimum_difficulty", encode(&131_072u64)),
("difficulty_bound_divisor", encode(&2048u64)),
("duration_limit", encode(&13u64)),
("min_gas_limit", encode(&5000u64)),
("gas_floor_target", encode(&3_141_592u64)),
].into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0.to_string(), vec.1);
acc
}),
builtins: Self::standard_builtins(),
parent_hash: H256::new(),
author: Address::new(),
difficulty: U256::from(131_072u64),
gas_limit: U256::from(0u64),
gas_used: U256::from(0u64),
timestamp: U256::from(0u64),
extra_data: vec![],
genesis_state: vec![ // TODO: make correct
(Address::new(), Account::new_basic(U256::from(1) << 200, U256::from(0)))
].into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0, vec.1);
acc
}),
seal_fields: 2,
seal_rlp: { let mut r = RlpStream::new_list(2); r.append(&H256::new()); r.append(&0x42u64); r.out() },
state_root_memo: RefCell::new(None),
}
}
/// Creates the actual Morden network chain spec.
pub fn new_morden_manual() -> Spec {
Spec {
engine_name: "Ethash".to_string(),
engine_params: vec![
("block_reward", encode(&(ether() * U256::from(5u64)))),
("maximum_extra_data_size", encode(&U256::from(32u64))),
("account_start_nonce", encode(&(U256::from(1u64) << 20))),
("gas_limit_bounds_divisor", encode(&1024u64)),
("minimum_difficulty", encode(&131_072u64)),
("difficulty_bound_divisor", encode(&2048u64)),
("duration_limit", encode(&13u64)),
("min_gas_limit", encode(&5000u64)),
("gas_floor_target", encode(&3_141_592u64)),
].into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0.to_string(), vec.1);
acc
}),
builtins: Self::standard_builtins(),
parent_hash: H256::new(),
author: Address::new(),
difficulty: U256::from(0x20000u64),
gas_limit: U256::from(0x2fefd8u64),
gas_used: U256::from(0u64),
timestamp: U256::from(0u64),
extra_data: vec![],
genesis_state: {
let n = U256::from(1) << 20;
vec![
(Address::from_str("0000000000000000000000000000000000000001").unwrap(), Account::new_basic(U256::from(1), n)),
(Address::from_str("0000000000000000000000000000000000000002").unwrap(), Account::new_basic(U256::from(1), n)),
(Address::from_str("0000000000000000000000000000000000000003").unwrap(), Account::new_basic(U256::from(1), n)),
(Address::from_str("0000000000000000000000000000000000000004").unwrap(), Account::new_basic(U256::from(1), n)),
(Address::from_str("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c").unwrap(), Account::new_basic(U256::from(1) << 200, n))
]}.into_iter().fold(HashMap::new(), | mut acc, vec | {
acc.insert(vec.0, vec.1);
acc
}),
seal_fields: 2,
seal_rlp: {
let mut r = RlpStream::new();
r.append(&H256::from_str("00000000000000000000000000000000000000647572616c65787365646c6578").unwrap());
r.append(&FromHex::from_hex("00006d6f7264656e").unwrap());
r.out()
},
state_root_memo: RefCell::new(None),
} }
} }
@ -353,11 +212,8 @@ impl Spec {
Self::from_json(json) Self::from_json(json)
} }
/// Create a new Morden chain spec. /// Create a new Spec which conforms to the Morden chain except that it's a NullEngine consensus.
pub fn new_morden() -> Spec { Self::from_json_utf8(include_bytes!("../res/morden.json")) } pub fn new_test() -> Spec { Self::from_json_utf8(include_bytes!("../res/null_morden.json")) }
/// Create a new Frontier chain spec.
pub fn new_frontier() -> Spec { Self::from_json_utf8(include_bytes!("../res/frontier.json")) }
} }
#[cfg(test)] #[cfg(test)]
@ -365,36 +221,17 @@ mod tests {
use std::str::FromStr; use std::str::FromStr;
use util::hash::*; use util::hash::*;
use util::sha3::*; use util::sha3::*;
use rustc_serialize::json::Json;
use views::*; use views::*;
use super::*; use super::*;
#[test] #[test]
fn morden_manual() { fn test_chain() {
let morden = Spec::new_morden_manual(); let test_spec = Spec::new_test();
assert_eq!(*morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap()); assert_eq!(*test_spec.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block(); let genesis = test_spec.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap()); assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
}
#[test] let _ = test_spec.to_engine();
fn morden() {
let morden = Spec::new_morden();
assert_eq!(*morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
}
#[test]
fn frontier() {
let frontier = Spec::new_frontier();
assert_eq!(*frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
let engine = frontier.to_engine();
} }
} }

View File

@ -1,14 +1,4 @@
use std::cell::*; use util::*;
use std::ops::*;
use std::collections::HashMap;
use util::hash::*;
use util::hashdb::*;
use util::overlaydb::*;
use util::trie::*;
use util::bytes::*;
use util::rlp::*;
use util::uint::*;
use util::error::*;
use account::Account; use account::Account;
use transaction::Transaction; use transaction::Transaction;
use receipt::Receipt; use receipt::Receipt;
@ -37,7 +27,7 @@ impl State {
let mut root = H256::new(); let mut root = H256::new();
{ {
// init trie and reset root too null // init trie and reset root too null
let _ = TrieDBMut::new(&mut db, &mut root); let _ = SecTrieDBMut::new(&mut db, &mut root);
} }
State { State {
@ -49,10 +39,10 @@ impl State {
} }
/// Creates new state with existing state root /// Creates new state with existing state root
pub fn from_existing(mut db: OverlayDB, mut root: H256, account_start_nonce: U256) -> State { pub fn from_existing(db: OverlayDB, root: H256, account_start_nonce: U256) -> State {
{ {
// trie should panic! if root does not exist // trie should panic! if root does not exist
let _ = TrieDB::new(&mut db, &mut root); let _ = SecTrieDB::new(&db, &root);
} }
State { State {
@ -83,6 +73,12 @@ impl State {
&mut self.db &mut self.db
} }
/// Create a new contract at address `contract`. If there is already an account at the address
/// it will have its code reset, ready for `init_code()`.
pub fn new_contract(&mut self, contract: &Address) {
self.require_or_from(contract, false, || Account::new_contract(U256::from(0u8)), |r| r.reset_code());
}
/// Get the balance of account `a`. /// Get the balance of account `a`.
pub fn balance(&self, a: &Address) -> U256 { pub fn balance(&self, a: &Address) -> U256 {
self.get(a, false).as_ref().map(|account| account.balance().clone()).unwrap_or(U256::from(0u8)) self.get(a, false).as_ref().map(|account| account.balance().clone()).unwrap_or(U256::from(0u8))
@ -129,9 +125,10 @@ impl State {
self.require(a, false).set_storage(key, value); self.require(a, false).set_storage(key, value);
} }
/// Mutate storage of account `a` so that it is `value` for `key`. /// Initialise the code of account `a` so that it is `value` for `key`.
pub fn set_code(&mut self, a: &Address, code: Bytes) { /// NOTE: Account should have been created with `new_contract`.
self.require_or_from(a, true, || Account::new_contract(U256::from(0u8))).set_code(code); pub fn init_code(&mut self, a: &Address, code: Bytes) {
self.require_or_from(a, true, || Account::new_contract(U256::from(0u8)), |_|{}).init_code(code);
} }
/// Execute a given transaction. /// Execute a given transaction.
@ -145,7 +142,7 @@ impl State {
unimplemented!(); unimplemented!();
} }
/// Commit accounts to TrieDBMut. This is similar to cpp-ethereum's dev::eth::commit. /// Commit accounts to SecTrieDBMut. This is similar to cpp-ethereum's dev::eth::commit.
/// `accounts` is mutable because we may need to commit the code or storage and record that. /// `accounts` is mutable because we may need to commit the code or storage and record that.
pub fn commit_into(db: &mut HashDB, mut root: H256, accounts: &mut HashMap<Address, Option<Account>>) -> H256 { pub fn commit_into(db: &mut HashDB, mut root: H256, accounts: &mut HashMap<Address, Option<Account>>) -> H256 {
// first, commit the sub trees. // first, commit the sub trees.
@ -161,7 +158,7 @@ impl State {
} }
{ {
let mut trie = TrieDBMut::from_existing(db, &mut root); let mut trie = SecTrieDBMut::from_existing(db, &mut root);
for (address, ref a) in accounts.iter() { for (address, ref a) in accounts.iter() {
match a { match a {
&&Some(ref account) => trie.insert(address, &account.rlp()), &&Some(ref account) => trie.insert(address, &account.rlp()),
@ -187,7 +184,7 @@ impl State {
/// `require_code` requires that the code be cached, too. /// `require_code` requires that the code be cached, too.
fn get(&self, a: &Address, require_code: bool) -> Ref<Option<Account>> { fn get(&self, a: &Address, require_code: bool) -> Ref<Option<Account>> {
self.cache.borrow_mut().entry(a.clone()).or_insert_with(|| self.cache.borrow_mut().entry(a.clone()).or_insert_with(||
TrieDB::new(&self.db, &self.root).get(&a).map(|rlp| Account::from_rlp(rlp))); SecTrieDB::new(&self.db, &self.root).get(&a).map(|rlp| Account::from_rlp(rlp)));
if require_code { if require_code {
if let Some(ref mut account) = self.cache.borrow_mut().get_mut(a).unwrap().as_mut() { if let Some(ref mut account) = self.cache.borrow_mut().get_mut(a).unwrap().as_mut() {
account.cache_code(&self.db); account.cache_code(&self.db);
@ -197,18 +194,20 @@ impl State {
} }
/// Pull account `a` in our cache from the trie DB. `require_code` requires that the code be cached, too. /// Pull account `a` in our cache from the trie DB. `require_code` requires that the code be cached, too.
/// `force_create` creates a new, empty basic account if there is not currently an active account.
fn require(&self, a: &Address, require_code: bool) -> RefMut<Account> { fn require(&self, a: &Address, require_code: bool) -> RefMut<Account> {
self.require_or_from(a, require_code, || Account::new_basic(U256::from(0u8), self.account_start_nonce)) self.require_or_from(a, require_code, || Account::new_basic(U256::from(0u8), self.account_start_nonce), |_|{})
} }
/// Pull account `a` in our cache from the trie DB. `require_code` requires that the code be cached, too. /// Pull account `a` in our cache from the trie DB. `require_code` requires that the code be cached, too.
/// `force_create` creates a new, empty basic account if there is not currently an active account. /// If it doesn't exist, make account equal the evaluation of `default`.
fn require_or_from<F: FnOnce() -> Account>(&self, a: &Address, require_code: bool, default: F) -> RefMut<Account> { fn require_or_from<F: FnOnce() -> Account, G: FnOnce(&mut Account)>(&self, a: &Address, require_code: bool, default: F, not_default: G) -> RefMut<Account> {
self.cache.borrow_mut().entry(a.clone()).or_insert_with(|| self.cache.borrow_mut().entry(a.clone()).or_insert_with(||
TrieDB::new(&self.db, &self.root).get(&a).map(|rlp| Account::from_rlp(rlp))); SecTrieDB::new(&self.db, &self.root).get(&a).map(|rlp| Account::from_rlp(rlp)));
if self.cache.borrow().get(a).unwrap().is_none() { let preexists = self.cache.borrow().get(a).unwrap().is_none();
if preexists {
self.cache.borrow_mut().insert(a.clone(), Some(default())); self.cache.borrow_mut().insert(a.clone(), Some(default()));
} else {
not_default(self.cache.borrow_mut().get_mut(a).unwrap().as_mut().unwrap());
} }
let b = self.cache.borrow_mut(); let b = self.cache.borrow_mut();
@ -237,8 +236,8 @@ fn code_from_database() {
let a = Address::from_str("0000000000000000000000000000000000000000").unwrap(); let a = Address::from_str("0000000000000000000000000000000000000000").unwrap();
let (r, db) = { let (r, db) = {
let mut s = State::new_temp(); let mut s = State::new_temp();
s.require_or_from(&a, false, ||Account::new_contract(U256::from(42u32))); s.require_or_from(&a, false, ||Account::new_contract(U256::from(42u32)), |_|{});
s.set_code(&a, vec![1, 2, 3]); s.init_code(&a, vec![1, 2, 3]);
assert_eq!(s.code(&a), Some([1u8, 2, 3].to_vec())); assert_eq!(s.code(&a), Some([1u8, 2, 3].to_vec()));
s.commit(); s.commit();
assert_eq!(s.code(&a), Some([1u8, 2, 3].to_vec())); assert_eq!(s.code(&a), Some([1u8, 2, 3].to_vec()));
@ -334,7 +333,7 @@ fn ensure_cached() {
let a = Address::from_str("0000000000000000000000000000000000000000").unwrap(); let a = Address::from_str("0000000000000000000000000000000000000000").unwrap();
s.require(&a, false); s.require(&a, false);
s.commit(); s.commit();
assert_eq!(s.root().hex(), "ec68b85fa2e0526dc0e821a5b33135459114f19173ce0479f5c09b21cc25b9a4"); assert_eq!(s.root().hex(), "0ce23f3c809de377b008a4a3ee94a0834aac8bec1f86e28ffe4fdb5a15b0c785");
} }
#[test] #[test]

View File

@ -1,7 +1,4 @@
use util::hash::*; use util::*;
use util::bytes::*;
use util::uint::*;
use util::rlp::*;
#[derive(Eq, PartialEq)] #[derive(Eq, PartialEq)]
pub enum TransactionKind { pub enum TransactionKind {

View File

@ -1,9 +1,5 @@
//! Block oriented views onto rlp. //! Block oriented views onto rlp.
use util::bytes::*; use util::*;
use util::hash::*;
use util::uint::*;
use util::rlp::*;
use util::sha3::*;
use header::*; use header::*;
use transaction::*; use transaction::*;
@ -49,7 +45,7 @@ impl<'a> BlockView<'a> {
/// Return transaction hashes. /// Return transaction hashes.
pub fn transaction_hashes(&self) -> Vec<H256> { pub fn transaction_hashes(&self) -> Vec<H256> {
self.rlp.at(1).iter().map(|rlp| rlp.raw().sha3()).collect() self.rlp.at(1).iter().map(|rlp| rlp.as_raw().sha3()).collect()
} }
/// Return list of uncles of given block. /// Return list of uncles of given block.
@ -59,7 +55,7 @@ impl<'a> BlockView<'a> {
/// Return list of uncle hashes of given block. /// Return list of uncle hashes of given block.
pub fn uncle_hashes(&self) -> Vec<H256> { pub fn uncle_hashes(&self) -> Vec<H256> {
self.rlp.at(2).iter().map(|rlp| rlp.raw().sha3()).collect() self.rlp.at(2).iter().map(|rlp| rlp.as_raw().sha3()).collect()
} }
} }
@ -143,6 +139,6 @@ impl<'a> HeaderView<'a> {
impl<'a> Hashable for HeaderView<'a> { impl<'a> Hashable for HeaderView<'a> {
fn sha3(&self) -> H256 { fn sha3(&self) -> H256 {
self.rlp.raw().sha3() self.rlp.as_raw().sha3()
} }
} }