Merge branch 'master' into rpc
This commit is contained in:
@@ -103,7 +103,7 @@ impl Account {
|
||||
/// Get (and cache) the contents of the trie's storage at `key`.
|
||||
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
|
||||
self.storage_overlay.borrow_mut().entry(key.clone()).or_insert_with(||{
|
||||
(Filth::Clean, H256::from(SecTrieDB::new(db, &self.storage_root).get(key.bytes()).map(|v| -> U256 {decode(v)}).unwrap_or(U256::zero())))
|
||||
(Filth::Clean, H256::from(SecTrieDB::new(db, &self.storage_root).get(key.bytes()).map_or(U256::zero(), |v| -> U256 {decode(v)})))
|
||||
}).1.clone()
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ impl Account {
|
||||
/// Provide a database to lookup `code_hash`. Should not be called if it is a contract without code.
|
||||
pub fn cache_code(&mut self, db: &HashDB) -> bool {
|
||||
// TODO: fill out self.code_cache;
|
||||
return self.is_cached() ||
|
||||
self.is_cached() ||
|
||||
match self.code_hash {
|
||||
Some(ref h) => match db.lookup(h) {
|
||||
Some(x) => { self.code_cache = x.to_vec(); true },
|
||||
@@ -248,8 +248,8 @@ mod tests {
|
||||
|
||||
let a = Account::from_rlp(&rlp);
|
||||
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
|
||||
assert_eq!(a.storage_at(&mut db, &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
|
||||
assert_eq!(a.storage_at(&mut db, &H256::from(&U256::from(0x01u64))), H256::new());
|
||||
assert_eq!(a.storage_at(&db, &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
|
||||
assert_eq!(a.storage_at(&db, &H256::from(&U256::from(0x01u64))), H256::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -15,10 +15,10 @@ pub enum Existance {
|
||||
|
||||
impl fmt::Display for Existance {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
&Existance::Born => try!(write!(f, "+++")),
|
||||
&Existance::Alive => try!(write!(f, "***")),
|
||||
&Existance::Died => try!(write!(f, "XXX")),
|
||||
match *self {
|
||||
Existance::Born => try!(write!(f, "+++")),
|
||||
Existance::Alive => try!(write!(f, "***")),
|
||||
Existance::Died => try!(write!(f, "XXX")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -72,11 +72,11 @@ impl AccountDiff {
|
||||
code: Diff::new(pre.code.clone(), post.code.clone()),
|
||||
storage: storage.into_iter().map(|k|
|
||||
(k.clone(), Diff::new(
|
||||
pre.storage.get(&k).cloned().unwrap_or(H256::new()),
|
||||
post.storage.get(&k).cloned().unwrap_or(H256::new())
|
||||
pre.storage.get(&k).cloned().unwrap_or_else(H256::new),
|
||||
post.storage.get(&k).cloned().unwrap_or_else(H256::new)
|
||||
))).collect(),
|
||||
};
|
||||
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.len() == 0 {
|
||||
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(r)
|
||||
@@ -112,16 +112,15 @@ impl fmt::Display for AccountDiff {
|
||||
Diff::Changed(ref pre, ref post) => try!(write!(f, "${} ({} {} {})", post, pre, if pre > post {"-"} else {"+"}, *max(pre, post) - *min(pre, post))),
|
||||
_ => {},
|
||||
}
|
||||
match self.code {
|
||||
Diff::Born(ref x) => try!(write!(f, " code {}", x.pretty())),
|
||||
_ => {},
|
||||
if let Diff::Born(ref x) = self.code {
|
||||
try!(write!(f, " code {}", x.pretty()));
|
||||
}
|
||||
try!(write!(f, "\n"));
|
||||
for (k, dv) in self.storage.iter() {
|
||||
match dv {
|
||||
&Diff::Born(ref v) => try!(write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))),
|
||||
&Diff::Changed(ref pre, ref post) => try!(write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))),
|
||||
&Diff::Died(_) => try!(write!(f, " X {}\n", interpreted_hash(k))),
|
||||
for (k, dv) in &self.storage {
|
||||
match *dv {
|
||||
Diff::Born(ref v) => try!(write!(f, " + {} => {}\n", interpreted_hash(k), interpreted_hash(v))),
|
||||
Diff::Changed(ref pre, ref post) => try!(write!(f, " * {} => {} (was {})\n", interpreted_hash(k), interpreted_hash(post), interpreted_hash(pre))),
|
||||
Diff::Died(_) => try!(write!(f, " X {}\n", interpreted_hash(k))),
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,49 @@
|
||||
#![feature(plugin)]
|
||||
// TODO: uncomment once this can be made to work.
|
||||
//#![plugin(docopt_macros)]
|
||||
|
||||
extern crate docopt;
|
||||
extern crate rustc_serialize;
|
||||
extern crate ethcore_util as util;
|
||||
extern crate ethcore;
|
||||
extern crate rustc_serialize;
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
extern crate ctrlc;
|
||||
|
||||
#[cfg(feature = "rpc")]
|
||||
mod rpc;
|
||||
|
||||
use std::io::stdin;
|
||||
use std::env;
|
||||
use log::{LogLevelFilter};
|
||||
use env_logger::LogBuilder;
|
||||
use ctrlc::CtrlC;
|
||||
use util::*;
|
||||
use ethcore::client::*;
|
||||
use ethcore::service::ClientService;
|
||||
use ethcore::service::{ClientService, NetSyncMessage};
|
||||
use ethcore::ethereum;
|
||||
use ethcore::blockchain::CacheSize;
|
||||
use ethcore::sync::*;
|
||||
use ethcore::sync::EthSync;
|
||||
use docopt::Docopt;
|
||||
|
||||
fn setup_log() {
|
||||
const USAGE: &'static str = "
|
||||
Parity. Ethereum Client.
|
||||
|
||||
Usage:
|
||||
parity [options]
|
||||
parity [options] <enode>...
|
||||
|
||||
Options:
|
||||
-l --logging LOGGING Specify the logging level
|
||||
-h --help Show this screen.
|
||||
";
|
||||
|
||||
#[derive(Debug, RustcDecodable)]
|
||||
struct Args {
|
||||
arg_enode: Option<Vec<String>>,
|
||||
flag_logging: Option<String>,
|
||||
}
|
||||
|
||||
fn setup_log(init: &Option<String>) {
|
||||
let mut builder = LogBuilder::new();
|
||||
builder.filter(None, LogLevelFilter::Info);
|
||||
|
||||
@@ -26,12 +51,16 @@ fn setup_log() {
|
||||
builder.parse(&env::var("RUST_LOG").unwrap());
|
||||
}
|
||||
|
||||
if let &Some(ref x) = init {
|
||||
builder.parse(x);
|
||||
}
|
||||
|
||||
builder.init().unwrap();
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature = "rpc")]
|
||||
fn setup_rpc_server(client: Arc<RwLock<Client>>) {
|
||||
fn setup_rpc_server(client: Arc<Client>) {
|
||||
use self::rpc::*;
|
||||
|
||||
let mut server = HttpServer::new(1);
|
||||
@@ -43,49 +72,74 @@ fn setup_rpc_server(client: Arc<RwLock<Client>>) {
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "rpc"))]
|
||||
fn setup_rpc_server(_client: Arc<RwLock<Client>>) {
|
||||
fn setup_rpc_server(_client: Arc<Client>) {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
setup_log();
|
||||
let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
|
||||
|
||||
setup_log(&args.flag_logging);
|
||||
|
||||
let spec = ethereum::new_frontier();
|
||||
let mut service = ClientService::start(spec).unwrap();
|
||||
let init_nodes = match &args.arg_enode {
|
||||
&None => spec.nodes().clone(),
|
||||
&Some(ref enodes) => enodes.clone(),
|
||||
};
|
||||
let mut net_settings = NetworkConfiguration::new();
|
||||
net_settings.boot_nodes = init_nodes;
|
||||
let mut service = ClientService::start(spec, net_settings).unwrap();
|
||||
setup_rpc_server(service.client());
|
||||
let io_handler = Box::new(ClientIoHandler { client: service.client(), timer: 0, info: Default::default() });
|
||||
let io_handler = Arc::new(ClientIoHandler { client: service.client(), info: Default::default(), sync: service.sync() });
|
||||
service.io().register_handler(io_handler).expect("Error registering IO handler");
|
||||
loop {
|
||||
let mut cmd = String::new();
|
||||
stdin().read_line(&mut cmd).unwrap();
|
||||
if cmd == "quit\n" || cmd == "exit\n" || cmd == "q\n" {
|
||||
break;
|
||||
|
||||
let exit = Arc::new(Condvar::new());
|
||||
let e = exit.clone();
|
||||
CtrlC::set_handler(move || { e.notify_all(); });
|
||||
let mutex = Mutex::new(());
|
||||
let _ = exit.wait(mutex.lock().unwrap()).unwrap();
|
||||
}
|
||||
|
||||
struct Informant {
|
||||
chain_info: RwLock<Option<BlockChainInfo>>,
|
||||
cache_info: RwLock<Option<CacheSize>>,
|
||||
report: RwLock<Option<ClientReport>>,
|
||||
}
|
||||
|
||||
impl Default for Informant {
|
||||
fn default() -> Self {
|
||||
Informant {
|
||||
chain_info: RwLock::new(None),
|
||||
cache_info: RwLock::new(None),
|
||||
report: RwLock::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct Informant {
|
||||
chain_info: Option<BlockChainInfo>,
|
||||
cache_info: Option<CacheSize>,
|
||||
report: Option<ClientReport>,
|
||||
}
|
||||
|
||||
impl Informant {
|
||||
pub fn tick(&mut self, client: &Client) {
|
||||
pub fn tick(&self, client: &Client, sync: &EthSync) {
|
||||
// 5 seconds betwen calls. TODO: calculate this properly.
|
||||
let dur = 5usize;
|
||||
|
||||
let chain_info = client.chain_info();
|
||||
let queue_info = client.queue_info();
|
||||
let cache_info = client.cache_info();
|
||||
let report = client.report();
|
||||
let sync_info = sync.status();
|
||||
|
||||
if let (_, &Some(ref last_cache_info), &Some(ref last_report)) = (&self.chain_info, &self.cache_info, &self.report) {
|
||||
println!("[ {} {} ]---[ {} blk/s | {} tx/s | {} gas/s //···{}···// {} ({}) bl {} ({}) ex ]",
|
||||
if let (_, &Some(ref last_cache_info), &Some(ref last_report)) = (self.chain_info.read().unwrap().deref(), self.cache_info.read().unwrap().deref(), self.report.read().unwrap().deref()) {
|
||||
println!("[ {} {} ]---[ {} blk/s | {} tx/s | {} gas/s //··· {}/{} peers, {} downloaded, {}+{} queued ···// {} ({}) bl {} ({}) ex ]",
|
||||
chain_info.best_block_number,
|
||||
chain_info.best_block_hash,
|
||||
(report.blocks_imported - last_report.blocks_imported) / dur,
|
||||
(report.transactions_applied - last_report.transactions_applied) / dur,
|
||||
(report.gas_processed - last_report.gas_processed) / From::from(dur),
|
||||
0, // TODO: peers
|
||||
|
||||
sync_info.num_active_peers,
|
||||
sync_info.num_peers,
|
||||
sync_info.blocks_received,
|
||||
queue_info.unverified_queue_size,
|
||||
queue_info.verified_queue_size,
|
||||
|
||||
cache_info.blocks,
|
||||
cache_info.blocks as isize - last_cache_info.blocks as isize,
|
||||
cache_info.block_details,
|
||||
@@ -93,28 +147,28 @@ impl Informant {
|
||||
);
|
||||
}
|
||||
|
||||
self.chain_info = Some(chain_info);
|
||||
self.cache_info = Some(cache_info);
|
||||
self.report = Some(report);
|
||||
*self.chain_info.write().unwrap().deref_mut() = Some(chain_info);
|
||||
*self.cache_info.write().unwrap().deref_mut() = Some(cache_info);
|
||||
*self.report.write().unwrap().deref_mut() = Some(report);
|
||||
}
|
||||
}
|
||||
|
||||
const INFO_TIMER: TimerToken = 0;
|
||||
|
||||
struct ClientIoHandler {
|
||||
client: Arc<RwLock<Client>>,
|
||||
timer: TimerToken,
|
||||
client: Arc<Client>,
|
||||
sync: Arc<EthSync>,
|
||||
info: Informant,
|
||||
}
|
||||
|
||||
impl IoHandler<NetSyncMessage> for ClientIoHandler {
|
||||
fn initialize<'s>(&'s mut self, io: &mut IoContext<'s, NetSyncMessage>) {
|
||||
self.timer = io.register_timer(5000).expect("Error registering timer");
|
||||
fn initialize(&self, io: &IoContext<NetSyncMessage>) {
|
||||
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
|
||||
}
|
||||
|
||||
fn timeout<'s>(&'s mut self, _io: &mut IoContext<'s, NetSyncMessage>, timer: TimerToken) {
|
||||
if self.timer == timer {
|
||||
let client = self.client.read().unwrap();
|
||||
client.tick();
|
||||
self.info.tick(client.deref());
|
||||
fn timeout(&self, _io: &IoContext<NetSyncMessage>, timer: TimerToken) {
|
||||
if INFO_TIMER == timer {
|
||||
self.info.tick(&self.client, &self.sync);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ use rpc::jsonrpc_core::*;
|
||||
use rpc::{Eth, EthFilter};
|
||||
|
||||
pub struct EthClient {
|
||||
client: Arc<RwLock<Client>>,
|
||||
client: Arc<Client>,
|
||||
}
|
||||
|
||||
impl EthClient {
|
||||
pub fn new(client: Arc<RwLock<Client>>) -> Self {
|
||||
pub fn new(client: Arc<Client>) -> Self {
|
||||
EthClient {
|
||||
client: client
|
||||
}
|
||||
@@ -41,7 +41,7 @@ impl Eth for EthClient {
|
||||
|
||||
fn block_number(&self, params: Params) -> Result<Value, Error> {
|
||||
match params {
|
||||
Params::None => Ok(Value::U64(self.client.read().unwrap().chain_info().best_block_number)),
|
||||
Params::None => Ok(Value::U64(self.client.chain_info().best_block_number)),
|
||||
_ => Err(Error::invalid_params())
|
||||
}
|
||||
}
|
||||
@@ -62,11 +62,11 @@ impl Eth for EthClient {
|
||||
}
|
||||
|
||||
pub struct EthFilterClient {
|
||||
client: Arc<RwLock<Client>>
|
||||
client: Arc<Client>
|
||||
}
|
||||
|
||||
impl EthFilterClient {
|
||||
pub fn new(client: Arc<RwLock<Client>>) -> Self {
|
||||
pub fn new(client: Arc<Client>) -> Self {
|
||||
EthFilterClient {
|
||||
client: client
|
||||
}
|
||||
@@ -83,6 +83,6 @@ impl EthFilter for EthFilterClient {
|
||||
}
|
||||
|
||||
fn filter_changes(&self, _: Params) -> Result<Value, Error> {
|
||||
Ok(Value::String(self.client.read().unwrap().chain_info().best_block_hash.to_hex()))
|
||||
Ok(Value::String(self.client.chain_info().best_block_hash.to_hex()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![allow(ptr_arg)] // Because of &LastHashes -> &Vec<_>
|
||||
|
||||
use common::*;
|
||||
use engine::*;
|
||||
use state::*;
|
||||
@@ -173,7 +175,7 @@ impl<'x, 'y> OpenBlock<'x, 'y> {
|
||||
timestamp: self.block.header.timestamp,
|
||||
difficulty: self.block.header.difficulty.clone(),
|
||||
last_hashes: self.last_hashes.clone(), // TODO: should be a reference.
|
||||
gas_used: self.block.archive.last().map(|t| t.receipt.gas_used).unwrap_or(U256::from(0)),
|
||||
gas_used: self.block.archive.last().map_or(U256::zero(), |t| t.receipt.gas_used),
|
||||
gas_limit: self.block.header.gas_limit.clone(),
|
||||
}
|
||||
}
|
||||
@@ -204,7 +206,7 @@ impl<'x, 'y> OpenBlock<'x, 'y> {
|
||||
s.block.header.state_root = s.block.state.root().clone();
|
||||
s.block.header.receipts_root = ordered_trie_root(s.block.archive.iter().map(|ref e| e.receipt.rlp_bytes()).collect());
|
||||
s.block.header.log_bloom = s.block.archive.iter().fold(LogBloom::zero(), |mut b, e| {b |= &e.receipt.log_bloom; b});
|
||||
s.block.header.gas_used = s.block.archive.last().map(|t| t.receipt.gas_used).unwrap_or(U256::from(0));
|
||||
s.block.header.gas_used = s.block.archive.last().map_or(U256::zero(), |t| t.receipt.gas_used);
|
||||
s.block.header.note_dirty();
|
||||
|
||||
ClosedBlock::new(s, uncle_bytes)
|
||||
@@ -255,7 +257,7 @@ impl SealedBlock {
|
||||
let mut block_rlp = RlpStream::new_list(3);
|
||||
self.block.header.stream_rlp(&mut block_rlp, Seal::With);
|
||||
block_rlp.append_list(self.block.archive.len());
|
||||
for e in self.block.archive.iter() { e.transaction.rlp_append(&mut block_rlp); }
|
||||
for e in &self.block.archive { e.transaction.rlp_append(&mut block_rlp); }
|
||||
block_rlp.append_raw(&self.uncle_bytes, 1);
|
||||
block_rlp.out()
|
||||
}
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
//! A queue of blocks. Sits between network or other I/O and the BlockChain.
|
||||
//! Sorts them ready for blockchain insertion.
|
||||
use std::thread::{JoinHandle, self};
|
||||
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
|
||||
use util::*;
|
||||
use verification::*;
|
||||
use error::*;
|
||||
use engine::Engine;
|
||||
use sync::*;
|
||||
use views::*;
|
||||
use header::*;
|
||||
use service::*;
|
||||
|
||||
/// Block queue status
|
||||
#[derive(Debug)]
|
||||
pub struct BlockQueueInfo {
|
||||
/// Indicates that queue is full
|
||||
pub full: bool,
|
||||
/// Number of queued blocks pending verification
|
||||
pub unverified_queue_size: usize,
|
||||
/// Number of verified queued blocks pending import
|
||||
pub verified_queue_size: usize,
|
||||
}
|
||||
|
||||
/// A queue of blocks. Sits between network or other I/O and the BlockChain.
|
||||
/// Sorts them ready for blockchain insertion.
|
||||
@@ -63,14 +76,15 @@ impl BlockQueue {
|
||||
let deleting = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let mut verifiers: Vec<JoinHandle<()>> = Vec::new();
|
||||
let thread_count = max(::num_cpus::get(), 2) - 1;
|
||||
for _ in 0..thread_count {
|
||||
let thread_count = max(::num_cpus::get(), 3) - 2;
|
||||
for i in 0..thread_count {
|
||||
let verification = verification.clone();
|
||||
let engine = engine.clone();
|
||||
let more_to_verify = more_to_verify.clone();
|
||||
let ready_signal = ready_signal.clone();
|
||||
let deleting = deleting.clone();
|
||||
verifiers.push(thread::spawn(move || BlockQueue::verify(verification, engine, more_to_verify, ready_signal, deleting)));
|
||||
verifiers.push(thread::Builder::new().name(format!("Verifier #{}", i)).spawn(move || BlockQueue::verify(verification, engine, more_to_verify, ready_signal, deleting))
|
||||
.expect("Error starting block verification thread"));
|
||||
}
|
||||
BlockQueue {
|
||||
engine: engine,
|
||||
@@ -204,7 +218,7 @@ impl BlockQueue {
|
||||
verification.verified = new_verified;
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
/// Removes up to `max` verified blocks from the queue
|
||||
pub fn drain(&mut self, max: usize) -> Vec<PreVerifiedBlock> {
|
||||
let mut verification = self.verification.lock().unwrap();
|
||||
let count = min(max, verification.verified.len());
|
||||
@@ -215,8 +229,21 @@ impl BlockQueue {
|
||||
result.push(block);
|
||||
}
|
||||
self.ready_signal.reset();
|
||||
if !verification.verified.is_empty() {
|
||||
self.ready_signal.set();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Get queue status.
|
||||
pub fn queue_info(&self) -> BlockQueueInfo {
|
||||
let verification = self.verification.lock().unwrap();
|
||||
BlockQueueInfo {
|
||||
full: false,
|
||||
verified_queue_size: verification.verified.len(),
|
||||
unverified_queue_size: verification.unverified.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BlockQueue {
|
||||
@@ -234,7 +261,7 @@ impl Drop for BlockQueue {
|
||||
mod tests {
|
||||
use util::*;
|
||||
use spec::*;
|
||||
use queue::*;
|
||||
use block_queue::*;
|
||||
|
||||
#[test]
|
||||
fn test_block_queue() {
|
||||
@@ -153,9 +153,8 @@ impl BlockProvider for BlockChain {
|
||||
fn block(&self, hash: &H256) -> Option<Bytes> {
|
||||
{
|
||||
let read = self.blocks.read().unwrap();
|
||||
match read.get(hash) {
|
||||
Some(v) => return Some(v.clone()),
|
||||
None => ()
|
||||
if let Some(v) = read.get(hash) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +187,7 @@ impl BlockProvider for BlockChain {
|
||||
|
||||
const COLLECTION_QUEUE_SIZE: usize = 2;
|
||||
const MIN_CACHE_SIZE: usize = 1;
|
||||
const MAX_CACHE_SIZE: usize = 1024 * 1024 * 1;
|
||||
const MAX_CACHE_SIZE: usize = 1024 * 1024;
|
||||
|
||||
impl BlockChain {
|
||||
/// Create new instance of blockchain from given Genesis
|
||||
@@ -342,19 +341,19 @@ impl BlockChain {
|
||||
Some(h) => h,
|
||||
None => return None,
|
||||
};
|
||||
Some(self._tree_route((from_details, from), (to_details, to)))
|
||||
Some(self._tree_route((&from_details, &from), (&to_details, &to)))
|
||||
}
|
||||
|
||||
/// Similar to `tree_route` function, but can be used to return a route
|
||||
/// between blocks which may not be in database yet.
|
||||
fn _tree_route(&self, from: (BlockDetails, H256), to: (BlockDetails, H256)) -> TreeRoute {
|
||||
fn _tree_route(&self, from: (&BlockDetails, &H256), to: (&BlockDetails, &H256)) -> TreeRoute {
|
||||
let mut from_branch = vec![];
|
||||
let mut to_branch = vec![];
|
||||
|
||||
let mut from_details = from.0;
|
||||
let mut to_details = to.0;
|
||||
let mut current_from = from.1;
|
||||
let mut current_to = to.1;
|
||||
let mut from_details = from.0.clone();
|
||||
let mut to_details = to.0.clone();
|
||||
let mut current_from = from.1.clone();
|
||||
let mut current_to = to.1.clone();
|
||||
|
||||
// reset from && to to the same level
|
||||
while from_details.number > to_details.number {
|
||||
@@ -409,7 +408,7 @@ impl BlockChain {
|
||||
|
||||
// store block in db
|
||||
self.blocks_db.put(&hash, &bytes).unwrap();
|
||||
let (batch, new_best) = self.block_to_extras_insert_batch(bytes);
|
||||
let (batch, new_best, details) = self.block_to_extras_insert_batch(bytes);
|
||||
|
||||
// update best block
|
||||
let mut best_block = self.best_block.write().unwrap();
|
||||
@@ -420,6 +419,8 @@ impl BlockChain {
|
||||
// update caches
|
||||
let mut write = self.block_details.write().unwrap();
|
||||
write.remove(&header.parent_hash());
|
||||
write.insert(hash.clone(), details);
|
||||
self.note_used(CacheID::Block(hash));
|
||||
|
||||
// update extras database
|
||||
self.extras_db.write(batch).unwrap();
|
||||
@@ -427,7 +428,7 @@ impl BlockChain {
|
||||
|
||||
/// Transforms block into WriteBatch that may be written into database
|
||||
/// Additionally, if it's new best block it returns new best block object.
|
||||
fn block_to_extras_insert_batch(&self, bytes: &[u8]) -> (WriteBatch, Option<BestBlock>) {
|
||||
fn block_to_extras_insert_batch(&self, bytes: &[u8]) -> (WriteBatch, Option<BestBlock>, BlockDetails) {
|
||||
// create views onto rlp
|
||||
let block = BlockView::new(bytes);
|
||||
let header = block.header_view();
|
||||
@@ -459,7 +460,7 @@ impl BlockChain {
|
||||
|
||||
// if it's not new best block, just return
|
||||
if !is_new_best {
|
||||
return (batch, None);
|
||||
return (batch, None, details);
|
||||
}
|
||||
|
||||
// if its new best block we need to make sure that all ancestors
|
||||
@@ -467,7 +468,7 @@ impl BlockChain {
|
||||
// find the route between old best block and the new one
|
||||
let best_hash = self.best_block_hash();
|
||||
let best_details = self.block_details(&best_hash).expect("best block hash is invalid!");
|
||||
let route = self._tree_route((best_details, best_hash), (details, hash.clone()));
|
||||
let route = self._tree_route((&best_details, &best_hash), (&details, &hash));
|
||||
|
||||
match route.blocks.len() {
|
||||
// its our parent
|
||||
@@ -494,7 +495,7 @@ impl BlockChain {
|
||||
total_difficulty: total_difficulty
|
||||
};
|
||||
|
||||
(batch, Some(best_block))
|
||||
(batch, Some(best_block), details)
|
||||
}
|
||||
|
||||
/// Returns true if transaction is known.
|
||||
@@ -527,9 +528,8 @@ impl BlockChain {
|
||||
K: ExtrasSliceConvertable + Eq + Hash + Clone {
|
||||
{
|
||||
let read = cache.read().unwrap();
|
||||
match read.get(hash) {
|
||||
Some(v) => return Some(v.clone()),
|
||||
None => ()
|
||||
if let Some(v) = read.get(hash) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,9 +549,8 @@ impl BlockChain {
|
||||
T: ExtrasIndexable {
|
||||
{
|
||||
let read = cache.read().unwrap();
|
||||
match read.get(hash) {
|
||||
Some(_) => return true,
|
||||
None => ()
|
||||
if let Some(_) = read.get(hash) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,6 +669,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(cyclomatic_complexity)]
|
||||
fn test_small_fork() {
|
||||
let genesis = "f901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a07dba07d6b448a186e9612e5f737d1c909dce473e53199901a302c00646d523c1a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808454c98c8142a059262c330941f3fe2a34d16d6e3c7b30d2ceb37c6a0e9a994c494ee1a61d2410885aa4c8bf8e56e264c0c0".from_hex().unwrap();
|
||||
let b1 = "f90261f901f9a05716670833ec874362d65fea27a7cd35af5897d275b31a44944113111e4e96d2a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0cb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878a0e78628dd45a1f8dc495594d83b76c588a3ee67463260f8b7d4a42f574aeab29aa0e9244cf7503b79c03d3a099e07a80d2dbc77bb0b502d8a89d51ac0d68dd31313b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd882520884562791e580a051b3ecba4e3f2b49c11d42dd0851ec514b1be3138080f72a2b6e83868275d98f8877671f479c414b47f862f86080018304cb2f94095e7baea6a6c7c4c2dfeb977efac326af552d870a801ca09e2709d7ec9bbe6b1bbbf0b2088828d14cd5e8642a1fee22dc74bfa89761a7f9a04bd8813dee4be989accdb708b1c2e325a7e9c695a8024e30e89d6c644e424747c0".from_hex().unwrap();
|
||||
|
||||
@@ -94,16 +94,13 @@ pub fn new_builtin_exec(name: &str) -> Option<Box<Fn(&[u8], &mut [u8])>> {
|
||||
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);
|
||||
if ec::is_valid(&s) {
|
||||
match ec::recover(&s, &it.hash) {
|
||||
Ok(p) => {
|
||||
let r = p.as_slice().sha3();
|
||||
// NICE: optimise and separate out into populate-like function
|
||||
for i in 0..min(32, output.len()) {
|
||||
output[i] = if i < 12 {0} else {r[i]};
|
||||
}
|
||||
if let Ok(p) = ec::recover(&s, &it.hash) {
|
||||
let r = p.as_slice().sha3();
|
||||
// NICE: optimise and separate out into populate-like function
|
||||
for i in 0..min(32, output.len()) {
|
||||
output[i] = if i < 12 {0} else {r[i]};
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
})),
|
||||
|
||||
@@ -6,8 +6,8 @@ use error::*;
|
||||
use header::BlockNumber;
|
||||
use spec::Spec;
|
||||
use engine::Engine;
|
||||
use queue::BlockQueue;
|
||||
use sync::NetSyncMessage;
|
||||
use block_queue::{BlockQueue, BlockQueueInfo};
|
||||
use service::NetSyncMessage;
|
||||
use env_info::LastHashes;
|
||||
use verification::*;
|
||||
use block::*;
|
||||
@@ -46,13 +46,6 @@ impl fmt::Display for BlockChainInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Block queue status
|
||||
#[derive(Debug)]
|
||||
pub struct BlockQueueStatus {
|
||||
/// TODO [arkpar] Please document me
|
||||
pub full: bool,
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
pub type TreeRoute = ::blockchain::TreeRoute;
|
||||
|
||||
@@ -95,13 +88,13 @@ pub trait BlockChainClient : Sync + Send {
|
||||
fn block_receipts(&self, hash: &H256) -> Option<Bytes>;
|
||||
|
||||
/// Import a block into the blockchain.
|
||||
fn import_block(&mut self, bytes: Bytes) -> ImportResult;
|
||||
fn import_block(&self, bytes: Bytes) -> ImportResult;
|
||||
|
||||
/// Get block queue information.
|
||||
fn queue_status(&self) -> BlockQueueStatus;
|
||||
fn queue_info(&self) -> BlockQueueInfo;
|
||||
|
||||
/// Clear block queue and abort all import activity.
|
||||
fn clear_queue(&mut self);
|
||||
fn clear_queue(&self);
|
||||
|
||||
/// Get blockchain information.
|
||||
fn chain_info(&self) -> BlockChainInfo;
|
||||
@@ -132,19 +125,21 @@ pub struct Client {
|
||||
chain: Arc<RwLock<BlockChain>>,
|
||||
engine: Arc<Box<Engine>>,
|
||||
state_db: JournalDB,
|
||||
queue: BlockQueue,
|
||||
report: ClientReport,
|
||||
block_queue: RwLock<BlockQueue>,
|
||||
report: RwLock<ClientReport>,
|
||||
uncommited_states: RwLock<HashMap<H256, JournalDB>>,
|
||||
import_lock: Mutex<()>
|
||||
}
|
||||
|
||||
const HISTORY: u64 = 1000;
|
||||
|
||||
impl Client {
|
||||
/// Create a new client with given spec and DB path.
|
||||
pub fn new(spec: Spec, path: &Path, message_channel: IoChannel<NetSyncMessage> ) -> Result<Client, Error> {
|
||||
pub fn new(spec: Spec, path: &Path, message_channel: IoChannel<NetSyncMessage> ) -> Result<Arc<Client>, Error> {
|
||||
let chain = Arc::new(RwLock::new(BlockChain::new(&spec.genesis_block(), path)));
|
||||
let mut opts = Options::new();
|
||||
opts.create_if_missing(true);
|
||||
opts.set_max_open_files(256);
|
||||
opts.create_if_missing(true);
|
||||
/*opts.set_use_fsync(false);
|
||||
opts.set_bytes_per_sync(8388608);
|
||||
opts.set_disable_data_sync(false);
|
||||
@@ -164,37 +159,36 @@ impl Client {
|
||||
|
||||
let mut state_path = path.to_path_buf();
|
||||
state_path.push("state");
|
||||
let db = DB::open(&opts, state_path.to_str().unwrap()).unwrap();
|
||||
let mut state_db = JournalDB::new(db);
|
||||
let db = Arc::new(DB::open(&opts, state_path.to_str().unwrap()).unwrap());
|
||||
|
||||
let engine = Arc::new(try!(spec.to_engine()));
|
||||
let mut state_db = JournalDB::new_with_arc(db.clone());
|
||||
if engine.spec().ensure_db_good(&mut state_db) {
|
||||
state_db.commit(0, &engine.spec().genesis_header().hash(), None).expect("Error commiting genesis state to state DB");
|
||||
}
|
||||
|
||||
// chain.write().unwrap().ensure_good(&state_db);
|
||||
|
||||
Ok(Client {
|
||||
Ok(Arc::new(Client {
|
||||
chain: chain,
|
||||
engine: engine.clone(),
|
||||
state_db: state_db,
|
||||
queue: BlockQueue::new(engine, message_channel),
|
||||
report: Default::default(),
|
||||
})
|
||||
block_queue: RwLock::new(BlockQueue::new(engine, message_channel)),
|
||||
report: RwLock::new(Default::default()),
|
||||
uncommited_states: RwLock::new(HashMap::new()),
|
||||
import_lock: Mutex::new(()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// This is triggered by a message coming from a block queue when the block is ready for insertion
|
||||
pub fn import_verified_blocks(&mut self) {
|
||||
|
||||
pub fn import_verified_blocks(&self, _io: &IoChannel<NetSyncMessage>) {
|
||||
let mut bad = HashSet::new();
|
||||
let blocks = self.queue.drain(128);
|
||||
let _import_lock = self.import_lock.lock();
|
||||
let blocks = self.block_queue.write().unwrap().drain(128);
|
||||
if blocks.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for block in blocks {
|
||||
if bad.contains(&block.header.parent_hash) {
|
||||
self.queue.mark_as_bad(&block.header.hash());
|
||||
self.block_queue.write().unwrap().mark_as_bad(&block.header.hash());
|
||||
bad.insert(block.header.hash());
|
||||
continue;
|
||||
}
|
||||
@@ -202,7 +196,7 @@ impl Client {
|
||||
let header = &block.header;
|
||||
if let Err(e) = verify_block_family(&header, &block.bytes, self.engine.deref().deref(), self.chain.read().unwrap().deref()) {
|
||||
warn!(target: "client", "Stage 3 block verification failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e);
|
||||
self.queue.mark_as_bad(&header.hash());
|
||||
self.block_queue.write().unwrap().mark_as_bad(&header.hash());
|
||||
bad.insert(block.header.hash());
|
||||
return;
|
||||
};
|
||||
@@ -210,7 +204,7 @@ impl Client {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
warn!(target: "client", "Block import failed for #{} ({}): Parent not found ({}) ", header.number(), header.hash(), header.parent_hash);
|
||||
self.queue.mark_as_bad(&header.hash());
|
||||
self.block_queue.write().unwrap().mark_as_bad(&header.hash());
|
||||
bad.insert(block.header.hash());
|
||||
return;
|
||||
},
|
||||
@@ -228,18 +222,19 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
let result = match enact_verified(&block, self.engine.deref().deref(), self.state_db.clone(), &parent, &last_hashes) {
|
||||
let db = self.state_db.clone();
|
||||
let result = match enact_verified(&block, self.engine.deref().deref(), db, &parent, &last_hashes) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
warn!(target: "client", "Block import failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e);
|
||||
bad.insert(block.header.hash());
|
||||
self.queue.mark_as_bad(&header.hash());
|
||||
self.block_queue.write().unwrap().mark_as_bad(&header.hash());
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = verify_block_final(&header, result.block().header()) {
|
||||
warn!(target: "client", "Stage 4 block verification failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e);
|
||||
self.queue.mark_as_bad(&header.hash());
|
||||
self.block_queue.write().unwrap().mark_as_bad(&header.hash());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -252,12 +247,16 @@ impl Client {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.report.accrue_block(&block);
|
||||
|
||||
self.report.write().unwrap().accrue_block(&block);
|
||||
trace!(target: "client", "Imported #{} ({})", header.number(), header.hash());
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear cached state overlay
|
||||
pub fn clear_state(&self, hash: &H256) {
|
||||
self.uncommited_states.write().unwrap().remove(hash);
|
||||
}
|
||||
|
||||
/// Get info on the cache.
|
||||
pub fn cache_info(&self) -> CacheSize {
|
||||
self.chain.read().unwrap().cache_size()
|
||||
@@ -265,7 +264,7 @@ impl Client {
|
||||
|
||||
/// Get the report.
|
||||
pub fn report(&self) -> ClientReport {
|
||||
self.report.clone()
|
||||
self.report.read().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Tick the client.
|
||||
@@ -328,21 +327,20 @@ impl BlockChainClient for Client {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
fn import_block(&mut self, bytes: Bytes) -> ImportResult {
|
||||
fn import_block(&self, bytes: Bytes) -> ImportResult {
|
||||
let header = BlockView::new(&bytes).header();
|
||||
if self.chain.read().unwrap().is_known(&header.hash()) {
|
||||
return Err(ImportError::AlreadyInChain);
|
||||
}
|
||||
self.queue.import_block(bytes)
|
||||
self.block_queue.write().unwrap().import_block(bytes)
|
||||
}
|
||||
|
||||
fn queue_status(&self) -> BlockQueueStatus {
|
||||
BlockQueueStatus {
|
||||
full: false
|
||||
}
|
||||
fn queue_info(&self) -> BlockQueueInfo {
|
||||
self.block_queue.read().unwrap().queue_info()
|
||||
}
|
||||
|
||||
fn clear_queue(&mut self) {
|
||||
fn clear_queue(&self) {
|
||||
self.block_queue.write().unwrap().clear();
|
||||
}
|
||||
|
||||
fn chain_info(&self) -> BlockChainInfo {
|
||||
|
||||
@@ -25,8 +25,14 @@ pub struct EnvInfo {
|
||||
}
|
||||
|
||||
impl EnvInfo {
|
||||
/// TODO [debris] Please document me
|
||||
/// Create empty env_info initialized with zeros
|
||||
pub fn new() -> EnvInfo {
|
||||
EnvInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EnvInfo {
|
||||
fn default() -> Self {
|
||||
EnvInfo {
|
||||
number: 0,
|
||||
author: Address::new(),
|
||||
@@ -53,11 +59,3 @@ impl FromJson for EnvInfo {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO: it should be the other way around.
|
||||
/// `new` should call `default`.
|
||||
impl Default for EnvInfo {
|
||||
fn default() -> Self {
|
||||
EnvInfo::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,13 +32,13 @@ impl Ethash {
|
||||
}
|
||||
|
||||
fn u64_param(&self, name: &str) -> u64 {
|
||||
*self.u64_params.write().unwrap().entry(name.to_string()).or_insert_with(||
|
||||
self.spec().engine_params.get(name).map(|a| decode(&a)).unwrap_or(0u64))
|
||||
*self.u64_params.write().unwrap().entry(name.to_owned()).or_insert_with(||
|
||||
self.spec().engine_params.get(name).map_or(0u64, |a| decode(&a)))
|
||||
}
|
||||
|
||||
fn u256_param(&self, name: &str) -> U256 {
|
||||
*self.u256_params.write().unwrap().entry(name.to_string()).or_insert_with(||
|
||||
self.spec().engine_params.get(name).map(|a| decode(&a)).unwrap_or(x!(0)))
|
||||
*self.u256_params.write().unwrap().entry(name.to_owned()).or_insert_with(||
|
||||
self.spec().engine_params.get(name).map_or(x!(0), |a| decode(&a)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ impl Engine for Ethash {
|
||||
/// Apply the block reward on finalisation of the block.
|
||||
/// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current).
|
||||
fn on_close_block(&self, block: &mut Block) {
|
||||
let reward = self.spec().engine_params.get("blockReward").map(|a| decode(&a)).unwrap_or(U256::from(0u64));
|
||||
let reward = self.spec().engine_params.get("blockReward").map_or(U256::from(0u64), |a| decode(&a));
|
||||
let fields = block.fields();
|
||||
|
||||
// Bestow block reward
|
||||
@@ -153,6 +153,7 @@ impl Engine for Ethash {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(wrong_self_convention)] // to_ethash should take self
|
||||
impl Ethash {
|
||||
fn calculate_difficuty(&self, header: &Header, parent: &Header) -> U256 {
|
||||
const EXP_DIFF_PERIOD: u64 = 100000;
|
||||
|
||||
@@ -68,10 +68,11 @@ impl Factory {
|
||||
fn jit() -> Box<Evm> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
}
|
||||
impl Default for Factory {
|
||||
/// Returns jitvm factory
|
||||
#[cfg(feature = "jit")]
|
||||
pub fn default() -> Factory {
|
||||
fn default() -> Factory {
|
||||
Factory {
|
||||
evm: VMType::Jit
|
||||
}
|
||||
@@ -79,7 +80,7 @@ impl Factory {
|
||||
|
||||
/// Returns native rust evm factory
|
||||
#[cfg(not(feature = "jit"))]
|
||||
pub fn default() -> Factory {
|
||||
fn default() -> Factory {
|
||||
Factory {
|
||||
evm: VMType::Interpreter
|
||||
}
|
||||
|
||||
@@ -7,19 +7,19 @@ use super::instructions::Instruction;
|
||||
use std::marker::Copy;
|
||||
use evm::{MessageCallResult, ContractCreateResult};
|
||||
|
||||
#[cfg(not(feature = "evm_debug"))]
|
||||
#[cfg(not(feature = "evm-debug"))]
|
||||
macro_rules! evm_debug {
|
||||
($x: expr) => {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm_debug")]
|
||||
#[cfg(feature = "evm-debug")]
|
||||
macro_rules! evm_debug {
|
||||
($x: expr) => {
|
||||
$x
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm_debug")]
|
||||
#[cfg(feature = "evm-debug")]
|
||||
fn color(instruction: Instruction, name: &'static str) -> String {
|
||||
let c = instruction as usize % 6;
|
||||
let colors = [31, 34, 33, 32, 35, 36];
|
||||
@@ -72,7 +72,7 @@ impl<S : Copy> VecStack<S> {
|
||||
|
||||
impl<S : fmt::Display> Stack<S> for VecStack<S> {
|
||||
fn peek(&self, no_from_top: usize) -> &S {
|
||||
return &self.stack[self.stack.len() - no_from_top - 1];
|
||||
&self.stack[self.stack.len() - no_from_top - 1]
|
||||
}
|
||||
|
||||
fn swap_with_top(&mut self, no_from_top: usize) {
|
||||
@@ -157,7 +157,7 @@ impl Memory for Vec<u8> {
|
||||
}
|
||||
|
||||
fn size(&self) -> usize {
|
||||
return self.len()
|
||||
self.len()
|
||||
}
|
||||
|
||||
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
|
||||
@@ -228,6 +228,7 @@ struct CodeReader<'a> {
|
||||
code: &'a Bytes
|
||||
}
|
||||
|
||||
#[allow(len_without_is_empty)]
|
||||
impl<'a> CodeReader<'a> {
|
||||
/// Get `no_of_bytes` from code and convert to U256. Move PC
|
||||
fn read(&mut self, no_of_bytes: usize) -> U256 {
|
||||
@@ -330,6 +331,7 @@ impl evm::Evm for Interpreter {
|
||||
}
|
||||
|
||||
impl Interpreter {
|
||||
#[allow(cyclomatic_complexity)]
|
||||
fn get_gas_cost_mem(&self,
|
||||
ext: &evm::Ext,
|
||||
instruction: Instruction,
|
||||
@@ -716,7 +718,7 @@ impl Interpreter {
|
||||
let big_id = stack.pop_back();
|
||||
let id = big_id.low_u64() as usize;
|
||||
let max = id.wrapping_add(32);
|
||||
let data = params.data.clone().unwrap_or(vec![]);
|
||||
let data = params.data.clone().unwrap_or_else(|| vec![]);
|
||||
let bound = cmp::min(data.len(), max);
|
||||
if id < bound && big_id < U256::from(data.len()) {
|
||||
let mut v = data[id..bound].to_vec();
|
||||
@@ -727,7 +729,7 @@ impl Interpreter {
|
||||
}
|
||||
},
|
||||
instructions::CALLDATASIZE => {
|
||||
stack.push(U256::from(params.data.clone().unwrap_or(vec![]).len()));
|
||||
stack.push(U256::from(params.data.clone().map_or(0, |l| l.len())));
|
||||
},
|
||||
instructions::CODESIZE => {
|
||||
stack.push(U256::from(code.len()));
|
||||
@@ -738,10 +740,10 @@ impl Interpreter {
|
||||
stack.push(U256::from(len));
|
||||
},
|
||||
instructions::CALLDATACOPY => {
|
||||
self.copy_data_to_memory(mem, stack, ¶ms.data.clone().unwrap_or(vec![]));
|
||||
self.copy_data_to_memory(mem, stack, ¶ms.data.clone().unwrap_or_else(|| vec![]));
|
||||
},
|
||||
instructions::CODECOPY => {
|
||||
self.copy_data_to_memory(mem, stack, ¶ms.code.clone().unwrap_or(vec![]));
|
||||
self.copy_data_to_memory(mem, stack, ¶ms.code.clone().unwrap_or_else(|| vec![]));
|
||||
},
|
||||
instructions::EXTCODECOPY => {
|
||||
let address = u256_to_address(&stack.pop_back());
|
||||
@@ -781,7 +783,7 @@ impl Interpreter {
|
||||
fn copy_data_to_memory(&self,
|
||||
mem: &mut Memory,
|
||||
stack: &mut Stack<U256>,
|
||||
data: &Bytes) {
|
||||
data: &[u8]) {
|
||||
let offset = stack.pop_back();
|
||||
let index = stack.pop_back();
|
||||
let size = stack.pop_back();
|
||||
@@ -1051,7 +1053,7 @@ impl Interpreter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_jump_destinations(&self, code: &Bytes) -> HashSet<CodePosition> {
|
||||
fn find_jump_destinations(&self, code: &[u8]) -> HashSet<CodePosition> {
|
||||
let mut jump_dests = HashSet::new();
|
||||
let mut position = 0;
|
||||
|
||||
@@ -1066,7 +1068,7 @@ impl Interpreter {
|
||||
position += 1;
|
||||
}
|
||||
|
||||
return jump_dests;
|
||||
jump_dests
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ struct FakeExt {
|
||||
logs: Vec<FakeLogEntry>,
|
||||
_suicides: HashSet<Address>,
|
||||
info: EnvInfo,
|
||||
_schedule: Schedule
|
||||
schedule: Schedule
|
||||
}
|
||||
|
||||
impl FakeExt {
|
||||
@@ -89,7 +89,7 @@ impl Ext for FakeExt {
|
||||
}
|
||||
|
||||
fn schedule(&self) -> &Schedule {
|
||||
&self._schedule
|
||||
&self.schedule
|
||||
}
|
||||
|
||||
fn env_info(&self) -> &EnvInfo {
|
||||
@@ -122,7 +122,7 @@ fn test_stack_underflow() {
|
||||
};
|
||||
|
||||
match err {
|
||||
evm::Error::StackUnderflow {instruction: _, wanted, on_stack} => {
|
||||
evm::Error::StackUnderflow {wanted, on_stack, ..} => {
|
||||
assert_eq!(wanted, 2);
|
||||
assert_eq!(on_stack, 0);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ impl<'a> Executive<'a> {
|
||||
}
|
||||
|
||||
/// Creates `Externalities` from `Executive`.
|
||||
pub fn to_externalities<'_>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_>) -> Externalities {
|
||||
pub fn as_externalities<'_>(&'_ mut self, origin_info: OriginInfo, substate: &'_ mut Substate, output: OutputPolicy<'_>) -> Externalities {
|
||||
Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output)
|
||||
}
|
||||
|
||||
@@ -123,8 +123,8 @@ impl<'a> Executive<'a> {
|
||||
|
||||
let mut substate = Substate::new();
|
||||
|
||||
let res = match t.action() {
|
||||
&Action::Create => {
|
||||
let res = match *t.action() {
|
||||
Action::Create => {
|
||||
let new_address = contract_address(&sender, &nonce);
|
||||
let params = ActionParams {
|
||||
code_address: new_address.clone(),
|
||||
@@ -139,7 +139,7 @@ impl<'a> Executive<'a> {
|
||||
};
|
||||
self.create(params, &mut substate)
|
||||
},
|
||||
&Action::Call(ref address) => {
|
||||
Action::Call(ref address) => {
|
||||
let params = ActionParams {
|
||||
code_address: address.clone(),
|
||||
address: address.clone(),
|
||||
@@ -177,7 +177,7 @@ impl<'a> Executive<'a> {
|
||||
// if destination is builtin, try to execute it
|
||||
|
||||
let default = [];
|
||||
let data = if let &Some(ref d) = ¶ms.data { d as &[u8] } else { &default as &[u8] };
|
||||
let data = if let Some(ref d) = params.data { d as &[u8] } else { &default as &[u8] };
|
||||
|
||||
let cost = self.engine.cost_of_builtin(¶ms.code_address, data);
|
||||
match cost <= params.gas {
|
||||
@@ -198,7 +198,7 @@ impl<'a> Executive<'a> {
|
||||
let mut unconfirmed_substate = Substate::new();
|
||||
|
||||
let res = {
|
||||
let mut ext = self.to_externalities(OriginInfo::from(¶ms), &mut unconfirmed_substate, OutputPolicy::Return(output));
|
||||
let mut ext = self.as_externalities(OriginInfo::from(¶ms), &mut unconfirmed_substate, OutputPolicy::Return(output));
|
||||
self.engine.vm_factory().create().exec(params, &mut ext)
|
||||
};
|
||||
|
||||
@@ -230,7 +230,7 @@ impl<'a> Executive<'a> {
|
||||
self.state.transfer_balance(¶ms.sender, ¶ms.address, ¶ms.value);
|
||||
|
||||
let res = {
|
||||
let mut ext = self.to_externalities(OriginInfo::from(¶ms), &mut unconfirmed_substate, OutputPolicy::InitContract);
|
||||
let mut ext = self.as_externalities(OriginInfo::from(¶ms), &mut unconfirmed_substate, OutputPolicy::InitContract);
|
||||
self.engine.vm_factory().create().exec(params, &mut ext)
|
||||
};
|
||||
self.enact_result(&res, substate, unconfirmed_substate, backup);
|
||||
@@ -248,7 +248,7 @@ impl<'a> Executive<'a> {
|
||||
let refunds_bound = sstore_refunds + suicide_refunds;
|
||||
|
||||
// real ammount to refund
|
||||
let gas_left_prerefund = match &result { &Ok(x) => x, _ => x!(0) };
|
||||
let gas_left_prerefund = match result { Ok(x) => x, _ => x!(0) };
|
||||
let refunded = cmp::min(refunds_bound, (t.gas - gas_left_prerefund) / U256::from(2));
|
||||
let gas_left = gas_left_prerefund + refunded;
|
||||
|
||||
@@ -265,7 +265,7 @@ impl<'a> Executive<'a> {
|
||||
self.state.add_balance(&self.info.author, &fees_value);
|
||||
|
||||
// perform suicides
|
||||
for address in substate.suicides.iter() {
|
||||
for address in &substate.suicides {
|
||||
trace!("Killing {}", address);
|
||||
self.state.kill_account(address);
|
||||
}
|
||||
@@ -273,11 +273,7 @@ impl<'a> Executive<'a> {
|
||||
match result {
|
||||
Err(evm::Error::Internal) => Err(ExecutionError::Internal),
|
||||
// TODO [ToDr] BadJumpDestination @debris - how to handle that?
|
||||
Err(evm::Error::OutOfGas)
|
||||
| Err(evm::Error::BadJumpDestination { destination: _ })
|
||||
| Err(evm::Error::BadInstruction { instruction: _ })
|
||||
| Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
|
||||
| Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
|
||||
Err(_) => {
|
||||
Ok(Executed {
|
||||
gas: t.gas,
|
||||
gas_used: t.gas,
|
||||
@@ -302,15 +298,15 @@ impl<'a> Executive<'a> {
|
||||
|
||||
fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate, backup: State) {
|
||||
// TODO: handle other evm::Errors same as OutOfGas once they are implemented
|
||||
match result {
|
||||
&Err(evm::Error::OutOfGas)
|
||||
| &Err(evm::Error::BadJumpDestination { destination: _ })
|
||||
| &Err(evm::Error::BadInstruction { instruction: _ })
|
||||
| &Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
|
||||
| &Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
|
||||
match *result {
|
||||
Err(evm::Error::OutOfGas)
|
||||
| Err(evm::Error::BadJumpDestination {..})
|
||||
| Err(evm::Error::BadInstruction {.. })
|
||||
| Err(evm::Error::StackUnderflow {..})
|
||||
| Err(evm::Error::OutOfStack {..}) => {
|
||||
self.state.revert(backup);
|
||||
},
|
||||
&Ok(_) | &Err(evm::Error::Internal) => substate.accrue(un_substate)
|
||||
Ok(_) | Err(evm::Error::Internal) => substate.accrue(un_substate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,9 +158,10 @@ impl<'a> Ext for Externalities<'a> {
|
||||
}
|
||||
|
||||
fn extcode(&self, address: &Address) -> Bytes {
|
||||
self.state.code(address).unwrap_or(vec![])
|
||||
self.state.code(address).unwrap_or_else(|| vec![])
|
||||
}
|
||||
|
||||
#[allow(match_ref_pats)]
|
||||
fn ret(&mut self, gas: &U256, data: &[u8]) -> Result<U256, evm::Error> {
|
||||
match &mut self.output {
|
||||
&mut OutputPolicy::Return(BytesRef::Fixed(ref mut slice)) => unsafe {
|
||||
|
||||
@@ -2,7 +2,7 @@ use util::*;
|
||||
use basic_types::*;
|
||||
use time::now_utc;
|
||||
|
||||
/// TODO [Gav Wood] Please document me
|
||||
/// Type for Block number
|
||||
pub type BlockNumber = u64;
|
||||
|
||||
/// A block header.
|
||||
@@ -171,9 +171,10 @@ impl Header {
|
||||
s.append(&self.gas_used);
|
||||
s.append(&self.timestamp);
|
||||
s.append(&self.extra_data);
|
||||
match with_seal {
|
||||
Seal::With => for b in self.seal.iter() { s.append_raw(&b, 1); },
|
||||
_ => {}
|
||||
if let Seal::With = with_seal {
|
||||
for b in &self.seal {
|
||||
s.append_raw(&b, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,7 +237,7 @@ impl Encodable for Header {
|
||||
self.timestamp.encode(e);
|
||||
self.extra_data.encode(e);
|
||||
|
||||
for b in self.seal.iter() {
|
||||
for b in &self.seal {
|
||||
e.emit_raw(&b);
|
||||
}
|
||||
})
|
||||
|
||||
11
src/lib.rs
11
src/lib.rs
@@ -1,8 +1,11 @@
|
||||
#![warn(missing_docs)]
|
||||
#![feature(cell_extras)]
|
||||
#![feature(augmented_assignments)]
|
||||
//#![feature(plugin)]
|
||||
#![feature(plugin)]
|
||||
//#![plugin(interpolate_idents)]
|
||||
#![plugin(clippy)]
|
||||
#![allow(needless_range_loop, match_bool)]
|
||||
|
||||
//! Ethcore's ethereum implementation
|
||||
//!
|
||||
//! ### Rust version
|
||||
@@ -73,7 +76,6 @@
|
||||
//! sudo make install
|
||||
//! sudo ldconfig
|
||||
//! ```
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate rustc_serialize;
|
||||
@@ -89,6 +91,8 @@ extern crate evmjit;
|
||||
#[macro_use]
|
||||
extern crate ethcore_util as util;
|
||||
|
||||
// NOTE: Add doc parser exception for these pub declarations.
|
||||
|
||||
/// TODO [Gav Wood] Please document me
|
||||
pub mod common;
|
||||
/// TODO [Tomusdrw] Please document me
|
||||
@@ -149,6 +153,5 @@ pub mod sync;
|
||||
pub mod block;
|
||||
/// TODO [arkpar] Please document me
|
||||
pub mod verification;
|
||||
/// TODO [debris] Please document me
|
||||
pub mod queue;
|
||||
pub mod block_queue;
|
||||
pub mod ethereum;
|
||||
|
||||
@@ -11,7 +11,7 @@ pub struct NullEngine {
|
||||
}
|
||||
|
||||
impl NullEngine {
|
||||
/// TODO [Tomusdrw] Please document me
|
||||
/// Returns new instance of NullEngine with default VM Factory
|
||||
pub fn new_boxed(spec: Spec) -> Box<Engine> {
|
||||
Box::new(NullEngine{
|
||||
spec: spec,
|
||||
|
||||
@@ -26,10 +26,10 @@ impl FromJson for PodState {
|
||||
let code = acc.find("code").map(&Bytes::from_json);
|
||||
if balance.is_some() || nonce.is_some() || storage.is_some() || code.is_some() {
|
||||
state.insert(address_from_hex(address), PodAccount{
|
||||
balance: balance.unwrap_or(U256::zero()),
|
||||
nonce: nonce.unwrap_or(U256::zero()),
|
||||
storage: storage.unwrap_or(BTreeMap::new()),
|
||||
code: code.unwrap_or(Vec::new())
|
||||
balance: balance.unwrap_or_else(U256::zero),
|
||||
nonce: nonce.unwrap_or_else(U256::zero),
|
||||
storage: storage.unwrap_or_else(BTreeMap::new),
|
||||
code: code.unwrap_or_else(Vec::new)
|
||||
});
|
||||
}
|
||||
state
|
||||
|
||||
@@ -36,7 +36,7 @@ impl RlpStandard for Receipt {
|
||||
// TODO: make work:
|
||||
//s.append(&self.logs);
|
||||
s.append_list(self.logs.len());
|
||||
for l in self.logs.iter() {
|
||||
for l in &self.logs {
|
||||
l.rlp_append(s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,24 +5,37 @@ use error::*;
|
||||
use std::env;
|
||||
use client::Client;
|
||||
|
||||
/// Message type for external and internal events
|
||||
#[derive(Clone)]
|
||||
pub enum SyncMessage {
|
||||
/// New block has been imported into the blockchain
|
||||
NewChainBlock(Bytes), //TODO: use Cow
|
||||
/// A block is ready
|
||||
BlockVerified,
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
pub type NetSyncMessage = NetworkIoMessage<SyncMessage>;
|
||||
|
||||
/// Client service setup. Creates and registers client and network services with the IO subsystem.
|
||||
pub struct ClientService {
|
||||
net_service: NetworkService<SyncMessage>,
|
||||
client: Arc<RwLock<Client>>,
|
||||
client: Arc<Client>,
|
||||
sync: Arc<EthSync>,
|
||||
}
|
||||
|
||||
impl ClientService {
|
||||
/// Start the service in a separate thread.
|
||||
pub fn start(spec: Spec) -> Result<ClientService, Error> {
|
||||
let mut net_service = try!(NetworkService::start());
|
||||
pub fn start(spec: Spec, net_config: NetworkConfiguration) -> Result<ClientService, Error> {
|
||||
let mut net_service = try!(NetworkService::start(net_config));
|
||||
info!("Starting {}", net_service.host_info());
|
||||
info!("Configured for {} using {} engine", spec.name, spec.engine_name);
|
||||
let mut dir = env::home_dir().unwrap();
|
||||
dir.push(".parity");
|
||||
dir.push(H64::from(spec.genesis_header().hash()).hex());
|
||||
let client = Arc::new(RwLock::new(try!(Client::new(spec, &dir, net_service.io().channel()))));
|
||||
EthSync::register(&mut net_service, client.clone());
|
||||
let client_io = Box::new(ClientIoHandler {
|
||||
let client = try!(Client::new(spec, &dir, net_service.io().channel()));
|
||||
let sync = EthSync::register(&mut net_service, client.clone());
|
||||
let client_io = Arc::new(ClientIoHandler {
|
||||
client: client.clone()
|
||||
});
|
||||
try!(net_service.io().register_handler(client_io));
|
||||
@@ -30,43 +43,62 @@ impl ClientService {
|
||||
Ok(ClientService {
|
||||
net_service: net_service,
|
||||
client: client,
|
||||
sync: sync,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the network service.
|
||||
pub fn add_node(&mut self, _enode: &str) {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
pub fn io(&mut self) -> &mut IoService<NetSyncMessage> {
|
||||
self.net_service.io()
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
pub fn client(&self) -> Arc<RwLock<Client>> {
|
||||
pub fn client(&self) -> Arc<Client> {
|
||||
self.client.clone()
|
||||
|
||||
}
|
||||
|
||||
/// Get shared sync handler
|
||||
pub fn sync(&self) -> Arc<EthSync> {
|
||||
self.sync.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// IO interface for the Client handler
|
||||
struct ClientIoHandler {
|
||||
client: Arc<RwLock<Client>>
|
||||
client: Arc<Client>
|
||||
}
|
||||
|
||||
const CLIENT_TICK_TIMER: TimerToken = 0;
|
||||
const CLIENT_TICK_MS: u64 = 5000;
|
||||
|
||||
impl IoHandler<NetSyncMessage> for ClientIoHandler {
|
||||
fn initialize<'s>(&'s mut self, _io: &mut IoContext<'s, NetSyncMessage>) {
|
||||
fn initialize(&self, io: &IoContext<NetSyncMessage>) {
|
||||
io.register_timer(CLIENT_TICK_TIMER, CLIENT_TICK_MS).expect("Error registering client timer");
|
||||
}
|
||||
|
||||
fn message<'s>(&'s mut self, _io: &mut IoContext<'s, NetSyncMessage>, net_message: &'s mut NetSyncMessage) {
|
||||
match net_message {
|
||||
&mut UserMessage(ref mut message) => {
|
||||
match message {
|
||||
&mut SyncMessage::BlockVerified => {
|
||||
self.client.write().unwrap().import_verified_blocks();
|
||||
},
|
||||
_ => {}, // ignore other messages
|
||||
}
|
||||
|
||||
}
|
||||
_ => {}, // ignore other messages
|
||||
fn timeout(&self, _io: &IoContext<NetSyncMessage>, timer: TimerToken) {
|
||||
if timer == CLIENT_TICK_TIMER {
|
||||
self.client.tick();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(match_ref_pats)]
|
||||
#[allow(single_match)]
|
||||
fn message(&self, io: &IoContext<NetSyncMessage>, net_message: &NetSyncMessage) {
|
||||
if let &UserMessage(ref message) = net_message {
|
||||
match message {
|
||||
&SyncMessage::BlockVerified => {
|
||||
self.client.import_verified_blocks(&io.channel());
|
||||
},
|
||||
_ => {}, // ignore other messages
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
39
src/spec.rs
39
src/spec.rs
@@ -10,7 +10,7 @@ pub fn gzip64res_to_json(source: &[u8]) -> Json {
|
||||
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();
|
||||
let mut s: String = "".to_owned();
|
||||
decoder.read_to_string(&mut s).expect("Gzip is invalid");
|
||||
Json::from_str(&s).expect("Json is invalid")
|
||||
}
|
||||
@@ -18,14 +18,14 @@ pub fn gzip64res_to_json(source: &[u8]) -> Json {
|
||||
/// Convert JSON value to equivlaent RLP representation.
|
||||
// TODO: handle container types.
|
||||
fn json_to_rlp(json: &Json) -> Bytes {
|
||||
match json {
|
||||
&Json::Boolean(o) => encode(&(if o {1u64} else {0})),
|
||||
&Json::I64(o) => encode(&(o as u64)),
|
||||
&Json::U64(o) => encode(&o),
|
||||
&Json::String(ref s) if s.len() >= 2 && &s[0..2] == "0x" && U256::from_str(&s[2..]).is_ok() => {
|
||||
match *json {
|
||||
Json::Boolean(o) => encode(&(if o {1u64} else {0})),
|
||||
Json::I64(o) => encode(&(o as u64)),
|
||||
Json::U64(o) => encode(&o),
|
||||
Json::String(ref s) if s.len() >= 2 && &s[0..2] == "0x" && U256::from_str(&s[2..]).is_ok() => {
|
||||
encode(&U256::from_str(&s[2..]).unwrap())
|
||||
},
|
||||
&Json::String(ref s) => {
|
||||
Json::String(ref s) => {
|
||||
encode(s)
|
||||
},
|
||||
_ => panic!()
|
||||
@@ -73,6 +73,9 @@ pub struct Spec {
|
||||
/// TODO [Gav Wood] Please document me
|
||||
pub engine_name: String,
|
||||
|
||||
/// Known nodes on the network in enode format.
|
||||
pub nodes: Vec<String>,
|
||||
|
||||
// Parameters concerning operation of the specific engine we're using.
|
||||
// Name -> RLP-encoded value
|
||||
/// TODO [Gav Wood] Please document me
|
||||
@@ -108,6 +111,7 @@ pub struct Spec {
|
||||
state_root_memo: RwLock<Option<H256>>,
|
||||
}
|
||||
|
||||
#[allow(wrong_self_convention)] // because to_engine(self) should be to_engine(&self)
|
||||
impl Spec {
|
||||
/// Convert this object into a boxed Engine of the right underlying type.
|
||||
// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
|
||||
@@ -127,6 +131,9 @@ impl Spec {
|
||||
self.state_root_memo.read().unwrap().as_ref().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Get the known knodes of the network in enode format.
|
||||
pub fn nodes(&self) -> &Vec<String> { &self.nodes }
|
||||
|
||||
/// TODO [Gav Wood] Please document me
|
||||
pub fn genesis_header(&self) -> Header {
|
||||
Header {
|
||||
@@ -185,17 +192,21 @@ impl FromJson for Spec {
|
||||
builtins.insert(addr.clone(), builtin);
|
||||
}
|
||||
}
|
||||
let balance = acc.find("balance").and_then(|x| match x { &Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
|
||||
let nonce = acc.find("nonce").and_then(|x| match x { &Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
|
||||
let balance = acc.find("balance").and_then(|x| match *x { Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
|
||||
let nonce = acc.find("nonce").and_then(|x| match *x { Json::String(ref b) => U256::from_dec_str(b).ok(), _ => None });
|
||||
// let balance = if let Some(&Json::String(ref b)) = acc.find("balance") {U256::from_dec_str(b).unwrap_or(U256::from(0))} else {U256::from(0)};
|
||||
// let nonce = if let Some(&Json::String(ref n)) = acc.find("nonce") {U256::from_dec_str(n).unwrap_or(U256::from(0))} else {U256::from(0)};
|
||||
// TODO: handle code & data if they exist.
|
||||
if balance.is_some() || nonce.is_some() {
|
||||
state.insert(addr, GenesisAccount { balance: balance.unwrap_or(U256::from(0)), nonce: nonce.unwrap_or(U256::from(0)) });
|
||||
state.insert(addr, GenesisAccount { balance: balance.unwrap_or_else(U256::zero), nonce: nonce.unwrap_or_else(U256::zero) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let nodes = if let Some(&Json::Array(ref ns)) = json.find("nodes") {
|
||||
ns.iter().filter_map(|n| if let Json::String(ref s) = *n { Some(s.clone()) } else {None}).collect()
|
||||
} else { Vec::new() };
|
||||
|
||||
let genesis = &json["genesis"];//.as_object().expect("No genesis object in JSON");
|
||||
|
||||
let (seal_fields, seal_rlp) = {
|
||||
@@ -212,12 +223,12 @@ impl FromJson for Spec {
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Spec {
|
||||
name: json.find("name").map(|j| j.as_string().unwrap()).unwrap_or("unknown").to_string(),
|
||||
engine_name: json["engineName"].as_string().unwrap().to_string(),
|
||||
name: json.find("name").map_or("unknown", |j| j.as_string().unwrap()).to_owned(),
|
||||
engine_name: json["engineName"].as_string().unwrap().to_owned(),
|
||||
engine_params: json_to_rlp_map(&json["params"]),
|
||||
nodes: nodes,
|
||||
builtins: builtins,
|
||||
parent_hash: H256::from_str(&genesis["parentHash"].as_string().unwrap()[2..]).unwrap(),
|
||||
author: Address::from_str(&genesis["author"].as_string().unwrap()[2..]).unwrap(),
|
||||
@@ -242,7 +253,7 @@ impl Spec {
|
||||
let mut root = H256::new();
|
||||
{
|
||||
let mut t = SecTrieDBMut::new(db, &mut root);
|
||||
for (address, account) in self.genesis_state.iter() {
|
||||
for (address, account) in &self.genesis_state {
|
||||
t.insert(address.as_slice(), &account.rlp());
|
||||
}
|
||||
}
|
||||
|
||||
19
src/state.rs
19
src/state.rs
@@ -88,22 +88,22 @@ impl State {
|
||||
|
||||
/// Get the balance of account `a`.
|
||||
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_or(U256::zero(), |account| account.balance().clone())
|
||||
}
|
||||
|
||||
/// Get the nonce of account `a`.
|
||||
pub fn nonce(&self, a: &Address) -> U256 {
|
||||
self.get(a, false).as_ref().map(|account| account.nonce().clone()).unwrap_or(U256::from(0u8))
|
||||
self.get(a, false).as_ref().map_or(U256::zero(), |account| account.nonce().clone())
|
||||
}
|
||||
|
||||
/// Mutate storage of account `a` so that it is `value` for `key`.
|
||||
pub fn storage_at(&self, a: &Address, key: &H256) -> H256 {
|
||||
self.get(a, false).as_ref().map(|a|a.storage_at(&self.db, key)).unwrap_or(H256::new())
|
||||
self.get(a, false).as_ref().map_or(H256::new(), |a|a.storage_at(&self.db, key))
|
||||
}
|
||||
|
||||
/// Mutate storage of account `a` so that it is `value` for `key`.
|
||||
pub fn code(&self, a: &Address) -> Option<Bytes> {
|
||||
self.get(a, true).as_ref().map(|a|a.code().map(|x|x.to_vec())).unwrap_or(None)
|
||||
self.get(a, true).as_ref().map_or(None, |a|a.code().map(|x|x.to_vec()))
|
||||
}
|
||||
|
||||
/// Add `incr` to the balance of account `a`.
|
||||
@@ -170,6 +170,7 @@ impl State {
|
||||
|
||||
/// 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.
|
||||
#[allow(match_ref_pats)]
|
||||
pub fn commit_into(db: &mut HashDB, root: &mut H256, accounts: &mut HashMap<Address, Option<Account>>) {
|
||||
// first, commit the sub trees.
|
||||
// TODO: is this necessary or can we dispense with the `ref mut a` for just `a`?
|
||||
@@ -186,9 +187,9 @@ impl State {
|
||||
{
|
||||
let mut trie = SecTrieDBMut::from_existing(db, root);
|
||||
for (address, ref a) in accounts.iter() {
|
||||
match a {
|
||||
&&Some(ref account) => trie.insert(address, &account.rlp()),
|
||||
&&None => trie.remove(address),
|
||||
match **a {
|
||||
Some(ref account) => trie.insert(address, &account.rlp()),
|
||||
None => trie.remove(address),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,7 +211,7 @@ impl State {
|
||||
pub fn to_hashmap_pod(&self) -> HashMap<Address, PodAccount> {
|
||||
// TODO: handle database rather than just the cache.
|
||||
self.cache.borrow().iter().fold(HashMap::new(), |mut m, (add, opt)| {
|
||||
if let &Some(ref acc) = opt {
|
||||
if let Some(ref acc) = *opt {
|
||||
m.insert(add.clone(), PodAccount::from_account(acc));
|
||||
}
|
||||
m
|
||||
@@ -221,7 +222,7 @@ impl State {
|
||||
pub fn to_pod(&self) -> PodState {
|
||||
// TODO: handle database rather than just the cache.
|
||||
PodState::new(self.cache.borrow().iter().fold(BTreeMap::new(), |mut m, (add, opt)| {
|
||||
if let &Some(ref acc) = opt {
|
||||
if let Some(ref acc) = *opt {
|
||||
m.insert(add.clone(), PodAccount::from_account(acc));
|
||||
}
|
||||
m
|
||||
|
||||
@@ -15,7 +15,7 @@ impl StateDiff {
|
||||
|
||||
impl fmt::Display for StateDiff {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
for (add, acc) in self.0.iter() {
|
||||
for (add, acc) in &self.0 {
|
||||
try!(write!(f, "{} {}: {}", acc.existance(), add, acc));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -107,6 +107,10 @@ pub struct SyncStatus {
|
||||
pub blocks_total: usize,
|
||||
/// Number of blocks downloaded so far.
|
||||
pub blocks_received: usize,
|
||||
/// Total number of connected peers
|
||||
pub num_peers: usize,
|
||||
/// Total number of active peers
|
||||
pub num_active_peers: usize,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
@@ -195,8 +199,10 @@ impl ChainSync {
|
||||
start_block_number: self.starting_block,
|
||||
last_imported_block_number: self.last_imported_block,
|
||||
highest_block_number: self.highest_block,
|
||||
blocks_total: (self.last_imported_block - self.starting_block) as usize,
|
||||
blocks_received: (self.highest_block - self.starting_block) as usize,
|
||||
blocks_received: (self.last_imported_block - self.starting_block) as usize,
|
||||
blocks_total: (self.highest_block - self.starting_block) as usize,
|
||||
num_peers: self.peers.len(),
|
||||
num_active_peers: self.peers.values().filter(|p| p.asking != PeerAsking::Nothing).count(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +218,7 @@ impl ChainSync {
|
||||
self.downloading_bodies.clear();
|
||||
self.headers.clear();
|
||||
self.bodies.clear();
|
||||
for (_, ref mut p) in self.peers.iter_mut() {
|
||||
for (_, ref mut p) in &mut self.peers {
|
||||
p.asking_blocks.clear();
|
||||
}
|
||||
self.header_ids.clear();
|
||||
@@ -268,6 +274,7 @@ impl ChainSync {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(cyclomatic_complexity)]
|
||||
/// Called by peer once it has new block headers during sync
|
||||
fn on_peer_block_headers(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
self.reset_peer_asking(peer_id, PeerAsking::BlockHeaders);
|
||||
@@ -375,7 +382,7 @@ impl ChainSync {
|
||||
transactions_root: tx_root,
|
||||
uncles: uncles
|
||||
};
|
||||
match self.header_ids.get(&header_id).map(|n| *n) {
|
||||
match self.header_ids.get(&header_id).cloned() {
|
||||
Some(n) => {
|
||||
self.header_ids.remove(&header_id);
|
||||
self.bodies.insert_item(n, body.as_raw().to_vec());
|
||||
@@ -424,6 +431,10 @@ impl ChainSync {
|
||||
let peer_difficulty = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer").difficulty;
|
||||
if difficulty > peer_difficulty {
|
||||
trace!(target: "sync", "Received block {:?} with no known parent. Peer needs syncing...", h);
|
||||
{
|
||||
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
|
||||
peer.latest = header_view.sha3();
|
||||
}
|
||||
self.sync_peer(io, peer_id, true);
|
||||
}
|
||||
}
|
||||
@@ -464,6 +475,9 @@ impl ChainSync {
|
||||
}
|
||||
}
|
||||
};
|
||||
if max_height != x!(0) {
|
||||
self.sync_peer(io, peer_id, true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -540,7 +554,7 @@ impl ChainSync {
|
||||
fn request_blocks(&mut self, io: &mut SyncIo, peer_id: PeerId) {
|
||||
self.clear_peer_download(peer_id);
|
||||
|
||||
if io.chain().queue_status().full {
|
||||
if io.chain().queue_info().full {
|
||||
self.pause_sync();
|
||||
return;
|
||||
}
|
||||
@@ -699,16 +713,13 @@ impl ChainSync {
|
||||
/// Used to recover from an error and re-download parts of the chain detected as bad.
|
||||
fn remove_downloaded_blocks(&mut self, start: BlockNumber) {
|
||||
for n in self.headers.get_tail(&start) {
|
||||
match self.headers.find_item(&n) {
|
||||
Some(ref header_data) => {
|
||||
let header_to_delete = HeaderView::new(&header_data.data);
|
||||
let header_id = HeaderId {
|
||||
transactions_root: header_to_delete.transactions_root(),
|
||||
uncles: header_to_delete.uncles_hash()
|
||||
};
|
||||
self.header_ids.remove(&header_id);
|
||||
},
|
||||
None => {}
|
||||
if let Some(ref header_data) = self.headers.find_item(&n) {
|
||||
let header_to_delete = HeaderView::new(&header_data.data);
|
||||
let header_id = HeaderId {
|
||||
transactions_root: header_to_delete.transactions_root(),
|
||||
uncles: header_to_delete.uncles_hash()
|
||||
};
|
||||
self.header_ids.remove(&header_id);
|
||||
}
|
||||
self.downloading_bodies.remove(&n);
|
||||
self.downloading_headers.remove(&n);
|
||||
@@ -796,12 +807,9 @@ impl ChainSync {
|
||||
packet.append(&chain.best_block_hash);
|
||||
packet.append(&chain.genesis_hash);
|
||||
//TODO: handle timeout for status request
|
||||
match io.send(peer_id, STATUS_PACKET, packet.out()) {
|
||||
Err(e) => {
|
||||
warn!(target:"sync", "Error sending status request: {:?}", e);
|
||||
io.disable_peer(peer_id);
|
||||
}
|
||||
Ok(_) => ()
|
||||
if let Err(e) = io.send(peer_id, STATUS_PACKET, packet.out()) {
|
||||
warn!(target:"sync", "Error sending status request: {:?}", e);
|
||||
io.disable_peer(peer_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -837,12 +845,9 @@ impl ChainSync {
|
||||
let mut data = Bytes::new();
|
||||
let inc = (skip + 1) as BlockNumber;
|
||||
while number <= last && number > 0 && count < max_count {
|
||||
match io.chain().block_header_at(number) {
|
||||
Some(mut hdr) => {
|
||||
data.append(&mut hdr);
|
||||
count += 1;
|
||||
}
|
||||
None => {}
|
||||
if let Some(mut hdr) = io.chain().block_header_at(number) {
|
||||
data.append(&mut hdr);
|
||||
count += 1;
|
||||
}
|
||||
if reverse {
|
||||
if number <= inc {
|
||||
@@ -874,12 +879,9 @@ impl ChainSync {
|
||||
let mut added = 0usize;
|
||||
let mut data = Bytes::new();
|
||||
for i in 0..count {
|
||||
match io.chain().block_body(&try!(r.val_at::<H256>(i))) {
|
||||
Some(mut hdr) => {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
None => {}
|
||||
if let Some(mut hdr) = io.chain().block_body(&try!(r.val_at::<H256>(i))) {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
let mut rlp = RlpStream::new_list(added);
|
||||
@@ -901,12 +903,9 @@ impl ChainSync {
|
||||
let mut added = 0usize;
|
||||
let mut data = Bytes::new();
|
||||
for i in 0..count {
|
||||
match io.chain().state_data(&try!(r.val_at::<H256>(i))) {
|
||||
Some(mut hdr) => {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
None => {}
|
||||
if let Some(mut hdr) = io.chain().state_data(&try!(r.val_at::<H256>(i))) {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
let mut rlp = RlpStream::new_list(added);
|
||||
@@ -927,12 +926,9 @@ impl ChainSync {
|
||||
let mut added = 0usize;
|
||||
let mut data = Bytes::new();
|
||||
for i in 0..count {
|
||||
match io.chain().block_receipts(&try!(r.val_at::<H256>(i))) {
|
||||
Some(mut hdr) => {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
None => {}
|
||||
if let Some(mut hdr) = io.chain().block_receipts(&try!(r.val_at::<H256>(i))) {
|
||||
data.append(&mut hdr);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
let mut rlp = RlpStream::new_list(added);
|
||||
@@ -967,7 +963,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Maintain other peers. Send out any new blocks and transactions
|
||||
pub fn maintain_sync(&mut self, _io: &mut SyncIo) {
|
||||
pub fn _maintain_sync(&mut self, _io: &mut SyncIo) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use client::BlockChainClient;
|
||||
use util::{NetworkContext, PeerId, PacketId,};
|
||||
use util::error::UtilError;
|
||||
use sync::SyncMessage;
|
||||
use service::SyncMessage;
|
||||
|
||||
/// IO interface for the syning handler.
|
||||
/// Provides peer connection management and an interface to the blockchain client.
|
||||
@@ -14,7 +14,7 @@ pub trait SyncIo {
|
||||
/// Send a packet to a peer.
|
||||
fn send(&mut self, peer_id: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError>;
|
||||
/// Get the blockchain
|
||||
fn chain<'s>(&'s mut self) -> &'s mut BlockChainClient;
|
||||
fn chain(&self) -> &BlockChainClient;
|
||||
/// Returns peer client identifier string
|
||||
fn peer_info(&self, peer_id: PeerId) -> String {
|
||||
peer_id.to_string()
|
||||
@@ -22,14 +22,14 @@ pub trait SyncIo {
|
||||
}
|
||||
|
||||
/// Wraps `NetworkContext` and the blockchain client
|
||||
pub struct NetSyncIo<'s, 'h, 'io> where 'h: 's, 'io: 'h {
|
||||
network: &'s mut NetworkContext<'h, 'io, SyncMessage>,
|
||||
chain: &'s mut BlockChainClient
|
||||
pub struct NetSyncIo<'s, 'h> where 'h: 's {
|
||||
network: &'s NetworkContext<'h, SyncMessage>,
|
||||
chain: &'s BlockChainClient
|
||||
}
|
||||
|
||||
impl<'s, 'h, 'io> NetSyncIo<'s, 'h, 'io> {
|
||||
impl<'s, 'h> NetSyncIo<'s, 'h> {
|
||||
/// Creates a new instance from the `NetworkContext` and the blockchain client reference.
|
||||
pub fn new(network: &'s mut NetworkContext<'h, 'io, SyncMessage>, chain: &'s mut BlockChainClient) -> NetSyncIo<'s,'h,'io> {
|
||||
pub fn new(network: &'s NetworkContext<'h, SyncMessage>, chain: &'s BlockChainClient) -> NetSyncIo<'s, 'h> {
|
||||
NetSyncIo {
|
||||
network: network,
|
||||
chain: chain,
|
||||
@@ -37,7 +37,7 @@ impl<'s, 'h, 'io> NetSyncIo<'s, 'h, 'io> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'h, 'op> SyncIo for NetSyncIo<'s, 'h, 'op> {
|
||||
impl<'s, 'h> SyncIo for NetSyncIo<'s, 'h> {
|
||||
fn disable_peer(&mut self, peer_id: PeerId) {
|
||||
self.network.disable_peer(peer_id);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ impl<'s, 'h, 'op> SyncIo for NetSyncIo<'s, 'h, 'op> {
|
||||
self.network.send(peer_id, packet_id, data)
|
||||
}
|
||||
|
||||
fn chain<'a>(&'a mut self) -> &'a mut BlockChainClient {
|
||||
fn chain(&self) -> &BlockChainClient {
|
||||
self.chain
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
/// fn main() {
|
||||
/// let mut service = NetworkService::start().unwrap();
|
||||
/// let dir = env::temp_dir();
|
||||
/// let client = Arc::new(Client::new(ethereum::new_frontier(), &dir).unwrap());
|
||||
/// let client = Client::new(ethereum::new_frontier(), &dir, service.io().channel()).unwrap();
|
||||
/// EthSync::register(&mut service, client);
|
||||
/// }
|
||||
/// ```
|
||||
@@ -25,10 +25,9 @@
|
||||
use std::ops::*;
|
||||
use std::sync::*;
|
||||
use client::Client;
|
||||
use util::network::{NetworkProtocolHandler, NetworkService, NetworkContext, PeerId, NetworkIoMessage};
|
||||
use util::TimerToken;
|
||||
use util::Bytes;
|
||||
use util::network::{NetworkProtocolHandler, NetworkService, NetworkContext, PeerId};
|
||||
use sync::chain::ChainSync;
|
||||
use service::SyncMessage;
|
||||
use sync::io::NetSyncIo;
|
||||
|
||||
mod chain;
|
||||
@@ -38,76 +37,57 @@ mod range_collection;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Message type for external events
|
||||
pub enum SyncMessage {
|
||||
/// New block has been imported into the blockchain
|
||||
NewChainBlock(Bytes),
|
||||
/// A block is ready
|
||||
BlockVerified,
|
||||
}
|
||||
|
||||
/// TODO [arkpar] Please document me
|
||||
pub type NetSyncMessage = NetworkIoMessage<SyncMessage>;
|
||||
|
||||
/// Ethereum network protocol handler
|
||||
pub struct EthSync {
|
||||
/// Shared blockchain client. TODO: this should evetually become an IPC endpoint
|
||||
chain: Arc<RwLock<Client>>,
|
||||
chain: Arc<Client>,
|
||||
/// Sync strategy
|
||||
sync: ChainSync
|
||||
sync: RwLock<ChainSync>
|
||||
}
|
||||
|
||||
pub use self::chain::SyncStatus;
|
||||
|
||||
impl EthSync {
|
||||
/// Creates and register protocol with the network service
|
||||
pub fn register(service: &mut NetworkService<SyncMessage>, chain: Arc<RwLock<Client>>) {
|
||||
let sync = Box::new(EthSync {
|
||||
pub fn register(service: &mut NetworkService<SyncMessage>, chain: Arc<Client>) -> Arc<EthSync> {
|
||||
let sync = Arc::new(EthSync {
|
||||
chain: chain,
|
||||
sync: ChainSync::new(),
|
||||
sync: RwLock::new(ChainSync::new()),
|
||||
});
|
||||
service.register_protocol(sync, "eth", &[62u8, 63u8]).expect("Error registering eth protocol handler");
|
||||
service.register_protocol(sync.clone(), "eth", &[62u8, 63u8]).expect("Error registering eth protocol handler");
|
||||
sync
|
||||
}
|
||||
|
||||
/// Get sync status
|
||||
pub fn status(&self) -> SyncStatus {
|
||||
self.sync.status()
|
||||
self.sync.read().unwrap().status()
|
||||
}
|
||||
|
||||
/// Stop sync
|
||||
pub fn stop(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.abort(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
self.sync.write().unwrap().abort(&mut NetSyncIo::new(io, self.chain.deref()));
|
||||
}
|
||||
|
||||
/// Restart sync
|
||||
pub fn restart(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.restart(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
self.sync.write().unwrap().restart(&mut NetSyncIo::new(io, self.chain.deref()));
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkProtocolHandler<SyncMessage> for EthSync {
|
||||
fn initialize(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.restart(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
io.register_timer(1000).unwrap();
|
||||
fn initialize(&self, _io: &NetworkContext<SyncMessage>) {
|
||||
}
|
||||
|
||||
fn read(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId, packet_id: u8, data: &[u8]) {
|
||||
self.sync.on_packet(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()) , *peer, packet_id, data);
|
||||
fn read(&self, io: &NetworkContext<SyncMessage>, peer: &PeerId, packet_id: u8, data: &[u8]) {
|
||||
self.sync.write().unwrap().on_packet(&mut NetSyncIo::new(io, self.chain.deref()) , *peer, packet_id, data);
|
||||
}
|
||||
|
||||
fn connected(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.on_peer_connected(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()), *peer);
|
||||
fn connected(&self, io: &NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.write().unwrap().on_peer_connected(&mut NetSyncIo::new(io, self.chain.deref()), *peer);
|
||||
}
|
||||
|
||||
fn disconnected(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.on_peer_aborting(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()), *peer);
|
||||
}
|
||||
|
||||
fn timeout(&mut self, io: &mut NetworkContext<SyncMessage>, _timer: TimerToken) {
|
||||
self.sync.maintain_sync(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
}
|
||||
|
||||
fn message(&mut self, _io: &mut NetworkContext<SyncMessage>, _message: &SyncMessage) {
|
||||
fn disconnected(&self, io: &NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.write().unwrap().on_peer_aborting(&mut NetSyncIo::new(io, self.chain.deref()), *peer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ pub trait RangeCollection<K, V> {
|
||||
/// Remove all elements >= `tail`
|
||||
fn insert_item(&mut self, key: K, value: V);
|
||||
/// Get an iterator over ranges
|
||||
fn range_iter<'c>(&'c self) -> RangeIterator<'c, K, V>;
|
||||
fn range_iter(& self) -> RangeIterator<K, V>;
|
||||
}
|
||||
|
||||
/// Range iterator. For each range yelds a key for the first element of the range and a vector of values.
|
||||
@@ -60,7 +60,7 @@ impl<'c, K:'c, V:'c> Iterator for RangeIterator<'c, K, V> where K: Add<Output =
|
||||
}
|
||||
|
||||
impl<K, V> RangeCollection<K, V> for Vec<(K, Vec<V>)> where K: Ord + PartialEq + Add<Output = K> + Sub<Output = K> + Copy + FromUsize + ToUsize {
|
||||
fn range_iter<'c>(&'c self) -> RangeIterator<'c, K, V> {
|
||||
fn range_iter(&self) -> RangeIterator<K, V> {
|
||||
RangeIterator {
|
||||
range: self.len(),
|
||||
collection: self
|
||||
@@ -191,6 +191,7 @@ impl<K, V> RangeCollection<K, V> for Vec<(K, Vec<V>)> where K: Ord + PartialEq +
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(cyclomatic_complexity)]
|
||||
fn test_range() {
|
||||
use std::cmp::{Ordering};
|
||||
|
||||
|
||||
@@ -1,38 +1,40 @@
|
||||
use util::*;
|
||||
use client::{BlockChainClient, BlockStatus, TreeRoute, BlockQueueStatus, BlockChainInfo};
|
||||
use client::{BlockChainClient, BlockStatus, TreeRoute, BlockChainInfo};
|
||||
use block_queue::BlockQueueInfo;
|
||||
use header::{Header as BlockHeader, BlockNumber};
|
||||
use error::*;
|
||||
use sync::io::SyncIo;
|
||||
use sync::chain::ChainSync;
|
||||
|
||||
struct TestBlockChainClient {
|
||||
blocks: HashMap<H256, Bytes>,
|
||||
numbers: HashMap<usize, H256>,
|
||||
blocks: RwLock<HashMap<H256, Bytes>>,
|
||||
numbers: RwLock<HashMap<usize, H256>>,
|
||||
genesis_hash: H256,
|
||||
last_hash: H256,
|
||||
difficulty: U256
|
||||
last_hash: RwLock<H256>,
|
||||
difficulty: RwLock<U256>,
|
||||
}
|
||||
|
||||
impl TestBlockChainClient {
|
||||
fn new() -> TestBlockChainClient {
|
||||
|
||||
let mut client = TestBlockChainClient {
|
||||
blocks: HashMap::new(),
|
||||
numbers: HashMap::new(),
|
||||
blocks: RwLock::new(HashMap::new()),
|
||||
numbers: RwLock::new(HashMap::new()),
|
||||
genesis_hash: H256::new(),
|
||||
last_hash: H256::new(),
|
||||
difficulty: From::from(0),
|
||||
last_hash: RwLock::new(H256::new()),
|
||||
difficulty: RwLock::new(From::from(0)),
|
||||
};
|
||||
client.add_blocks(1, true); // add genesis block
|
||||
client.genesis_hash = client.last_hash.clone();
|
||||
client.genesis_hash = client.last_hash.read().unwrap().clone();
|
||||
client
|
||||
}
|
||||
|
||||
pub fn add_blocks(&mut self, count: usize, empty: bool) {
|
||||
for n in self.numbers.len()..(self.numbers.len() + count) {
|
||||
let len = self.numbers.read().unwrap().len();
|
||||
for n in len..(len + count) {
|
||||
let mut header = BlockHeader::new();
|
||||
header.difficulty = From::from(n);
|
||||
header.parent_hash = self.last_hash.clone();
|
||||
header.parent_hash = self.last_hash.read().unwrap().clone();
|
||||
header.number = n as BlockNumber;
|
||||
let mut uncles = RlpStream::new_list(if empty {0} else {1});
|
||||
if !empty {
|
||||
@@ -50,12 +52,12 @@ impl TestBlockChainClient {
|
||||
|
||||
impl BlockChainClient for TestBlockChainClient {
|
||||
fn block_header(&self, h: &H256) -> Option<Bytes> {
|
||||
self.blocks.get(h).map(|r| Rlp::new(r).at(0).as_raw().to_vec())
|
||||
self.blocks.read().unwrap().get(h).map(|r| Rlp::new(r).at(0).as_raw().to_vec())
|
||||
|
||||
}
|
||||
|
||||
fn block_body(&self, h: &H256) -> Option<Bytes> {
|
||||
self.blocks.get(h).map(|r| {
|
||||
self.blocks.read().unwrap().get(h).map(|r| {
|
||||
let mut stream = RlpStream::new_list(2);
|
||||
stream.append_raw(Rlp::new(&r).at(1).as_raw(), 1);
|
||||
stream.append_raw(Rlp::new(&r).at(2).as_raw(), 1);
|
||||
@@ -64,30 +66,30 @@ impl BlockChainClient for TestBlockChainClient {
|
||||
}
|
||||
|
||||
fn block(&self, h: &H256) -> Option<Bytes> {
|
||||
self.blocks.get(h).map(|b| b.clone())
|
||||
self.blocks.read().unwrap().get(h).cloned()
|
||||
}
|
||||
|
||||
fn block_status(&self, h: &H256) -> BlockStatus {
|
||||
match self.blocks.get(h) {
|
||||
match self.blocks.read().unwrap().get(h) {
|
||||
Some(_) => BlockStatus::InChain,
|
||||
None => BlockStatus::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fn block_header_at(&self, n: BlockNumber) -> Option<Bytes> {
|
||||
self.numbers.get(&(n as usize)).and_then(|h| self.block_header(h))
|
||||
self.numbers.read().unwrap().get(&(n as usize)).and_then(|h| self.block_header(h))
|
||||
}
|
||||
|
||||
fn block_body_at(&self, n: BlockNumber) -> Option<Bytes> {
|
||||
self.numbers.get(&(n as usize)).and_then(|h| self.block_body(h))
|
||||
self.numbers.read().unwrap().get(&(n as usize)).and_then(|h| self.block_body(h))
|
||||
}
|
||||
|
||||
fn block_at(&self, n: BlockNumber) -> Option<Bytes> {
|
||||
self.numbers.get(&(n as usize)).map(|h| self.blocks.get(h).unwrap().clone())
|
||||
self.numbers.read().unwrap().get(&(n as usize)).map(|h| self.blocks.read().unwrap().get(h).unwrap().clone())
|
||||
}
|
||||
|
||||
fn block_status_at(&self, n: BlockNumber) -> BlockStatus {
|
||||
if (n as usize) < self.blocks.len() {
|
||||
if (n as usize) < self.blocks.read().unwrap().len() {
|
||||
BlockStatus::InChain
|
||||
} else {
|
||||
BlockStatus::Unknown
|
||||
@@ -110,14 +112,14 @@ impl BlockChainClient for TestBlockChainClient {
|
||||
None
|
||||
}
|
||||
|
||||
fn import_block(&mut self, b: Bytes) -> ImportResult {
|
||||
fn import_block(&self, b: Bytes) -> ImportResult {
|
||||
let header = Rlp::new(&b).val_at::<BlockHeader>(0);
|
||||
let number: usize = header.number as usize;
|
||||
if number > self.blocks.len() {
|
||||
panic!("Unexpected block number. Expected {}, got {}", self.blocks.len(), number);
|
||||
if number > self.blocks.read().unwrap().len() {
|
||||
panic!("Unexpected block number. Expected {}, got {}", self.blocks.read().unwrap().len(), number);
|
||||
}
|
||||
if number > 0 {
|
||||
match self.blocks.get(&header.parent_hash) {
|
||||
match self.blocks.read().unwrap().get(&header.parent_hash) {
|
||||
Some(parent) => {
|
||||
let parent = Rlp::new(parent).val_at::<BlockHeader>(0);
|
||||
if parent.number != (header.number - 1) {
|
||||
@@ -129,43 +131,46 @@ impl BlockChainClient for TestBlockChainClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
if number == self.numbers.len() {
|
||||
self.difficulty = self.difficulty + header.difficulty;
|
||||
self.last_hash = header.hash();
|
||||
self.blocks.insert(header.hash(), b);
|
||||
self.numbers.insert(number, header.hash());
|
||||
let len = self.numbers.read().unwrap().len();
|
||||
if number == len {
|
||||
*self.difficulty.write().unwrap().deref_mut() += header.difficulty;
|
||||
mem::replace(self.last_hash.write().unwrap().deref_mut(), header.hash());
|
||||
self.blocks.write().unwrap().insert(header.hash(), b);
|
||||
self.numbers.write().unwrap().insert(number, header.hash());
|
||||
let mut parent_hash = header.parent_hash;
|
||||
if number > 0 {
|
||||
let mut n = number - 1;
|
||||
while n > 0 && self.numbers[&n] != parent_hash {
|
||||
*self.numbers.get_mut(&n).unwrap() = parent_hash.clone();
|
||||
while n > 0 && self.numbers.read().unwrap()[&n] != parent_hash {
|
||||
*self.numbers.write().unwrap().get_mut(&n).unwrap() = parent_hash.clone();
|
||||
n -= 1;
|
||||
parent_hash = Rlp::new(&self.blocks[&parent_hash]).val_at::<BlockHeader>(0).parent_hash;
|
||||
parent_hash = Rlp::new(&self.blocks.read().unwrap()[&parent_hash]).val_at::<BlockHeader>(0).parent_hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
self.blocks.insert(header.hash(), b.to_vec());
|
||||
self.blocks.write().unwrap().insert(header.hash(), b.to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn queue_status(&self) -> BlockQueueStatus {
|
||||
BlockQueueStatus {
|
||||
fn queue_info(&self) -> BlockQueueInfo {
|
||||
BlockQueueInfo {
|
||||
full: false,
|
||||
verified_queue_size: 0,
|
||||
unverified_queue_size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_queue(&mut self) {
|
||||
fn clear_queue(&self) {
|
||||
}
|
||||
|
||||
fn chain_info(&self) -> BlockChainInfo {
|
||||
BlockChainInfo {
|
||||
total_difficulty: self.difficulty,
|
||||
pending_total_difficulty: self.difficulty,
|
||||
total_difficulty: *self.difficulty.read().unwrap(),
|
||||
pending_total_difficulty: *self.difficulty.read().unwrap(),
|
||||
genesis_hash: self.genesis_hash.clone(),
|
||||
best_block_hash: self.last_hash.clone(),
|
||||
best_block_number: self.blocks.len() as BlockNumber - 1,
|
||||
best_block_hash: self.last_hash.read().unwrap().clone(),
|
||||
best_block_number: self.blocks.read().unwrap().len() as BlockNumber - 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,7 +213,7 @@ impl<'p> SyncIo for TestIo<'p> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn chain<'a>(&'a mut self) -> &'a mut BlockChainClient {
|
||||
fn chain(&self) -> &BlockChainClient {
|
||||
self.chain
|
||||
}
|
||||
}
|
||||
@@ -265,17 +270,14 @@ impl TestNet {
|
||||
|
||||
pub fn sync_step(&mut self) {
|
||||
for peer in 0..self.peers.len() {
|
||||
match self.peers[peer].queue.pop_front() {
|
||||
Some(packet) => {
|
||||
let mut p = self.peers.get_mut(packet.recipient).unwrap();
|
||||
trace!("--- {} -> {} ---", peer, packet.recipient);
|
||||
p.sync.on_packet(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(peer as PeerId)), peer as PeerId, packet.packet_id, &packet.data);
|
||||
trace!("----------------");
|
||||
},
|
||||
None => {}
|
||||
if let Some(packet) = self.peers[peer].queue.pop_front() {
|
||||
let mut p = self.peers.get_mut(packet.recipient).unwrap();
|
||||
trace!("--- {} -> {} ---", peer, packet.recipient);
|
||||
p.sync.on_packet(&mut TestIo::new(&mut p.chain, &mut p.queue, Some(peer as PeerId)), peer as PeerId, packet.packet_id, &packet.data);
|
||||
trace!("----------------");
|
||||
}
|
||||
let mut p = self.peers.get_mut(peer).unwrap();
|
||||
p.sync.maintain_sync(&mut TestIo::new(&mut p.chain, &mut p.queue, None));
|
||||
p.sync._maintain_sync(&mut TestIo::new(&mut p.chain, &mut p.queue, None));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +302,7 @@ fn full_sync_two_peers() {
|
||||
net.peer_mut(2).chain.add_blocks(1000, false);
|
||||
net.sync();
|
||||
assert!(net.peer(0).chain.block_at(1000).is_some());
|
||||
assert_eq!(net.peer(0).chain.blocks, net.peer(1).chain.blocks);
|
||||
assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -313,7 +315,7 @@ fn full_sync_empty_blocks() {
|
||||
}
|
||||
net.sync();
|
||||
assert!(net.peer(0).chain.block_at(1000).is_some());
|
||||
assert_eq!(net.peer(0).chain.blocks, net.peer(1).chain.blocks);
|
||||
assert_eq!(net.peer(0).chain.blocks.read().unwrap().deref(), net.peer(1).chain.blocks.read().unwrap().deref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -329,9 +331,9 @@ fn forked_sync() {
|
||||
net.peer_mut(1).chain.add_blocks(100, false); //fork between 1 and 2
|
||||
net.peer_mut(2).chain.add_blocks(10, true);
|
||||
// peer 1 has the best chain of 601 blocks
|
||||
let peer1_chain = net.peer(1).chain.numbers.clone();
|
||||
let peer1_chain = net.peer(1).chain.numbers.read().unwrap().clone();
|
||||
net.sync();
|
||||
assert_eq!(net.peer(0).chain.numbers, peer1_chain);
|
||||
assert_eq!(net.peer(1).chain.numbers, peer1_chain);
|
||||
assert_eq!(net.peer(2).chain.numbers, peer1_chain);
|
||||
assert_eq!(net.peer(0).chain.numbers.read().unwrap().deref(), &peer1_chain);
|
||||
assert_eq!(net.peer(1).chain.numbers.read().unwrap().deref(), &peer1_chain);
|
||||
assert_eq!(net.peer(2).chain.numbers.read().unwrap().deref(), &peer1_chain);
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
|
||||
let mut fail = false;
|
||||
//let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); fail = true };
|
||||
let mut fail_unless = |cond: bool, s: &str | if !cond && !fail {
|
||||
failed.push(format!("[{}] {}: {}", vm, name.to_string(), s));
|
||||
failed.push(format!("[{}] {}: {}", vm, name, s));
|
||||
fail = true
|
||||
};
|
||||
|
||||
@@ -187,15 +187,9 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
|
||||
BTreeMap::from_json(&s["storage"]).into_iter().foreach(|(k, v)| state.set_storage(&address, k, v));
|
||||
});
|
||||
|
||||
let mut info = EnvInfo::new();
|
||||
|
||||
test.find("env").map(|env| {
|
||||
info.author = xjson!(&env["currentCoinbase"]);
|
||||
info.difficulty = xjson!(&env["currentDifficulty"]);
|
||||
info.gas_limit = xjson!(&env["currentGasLimit"]);
|
||||
info.number = xjson!(&env["currentNumber"]);
|
||||
info.timestamp = xjson!(&env["currentTimestamp"]);
|
||||
});
|
||||
let info = test.find("env").map(|env| {
|
||||
EnvInfo::from_json(env)
|
||||
}).unwrap_or_default();
|
||||
|
||||
let engine = TestEngine::new(1, vm.clone());
|
||||
|
||||
@@ -245,7 +239,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
|
||||
test.find("post").map(|pre| for (addr, s) in pre.as_object().unwrap() {
|
||||
let address = Address::from(addr.as_ref());
|
||||
|
||||
fail_unless(state.code(&address).unwrap_or(vec![]) == Bytes::from_json(&s["code"]), "code is incorrect");
|
||||
fail_unless(state.code(&address).unwrap_or_else(|| vec![]) == Bytes::from_json(&s["code"]), "code is incorrect");
|
||||
fail_unless(state.balance(&address) == xjson!(&s["balance"]), "balance is incorrect");
|
||||
fail_unless(state.nonce(&address) == xjson!(&s["nonce"]), "nonce is incorrect");
|
||||
BTreeMap::from_json(&s["storage"]).iter().foreach(|(k, v)| fail_unless(&state.storage_at(&address, &k) == v, "storage is incorrect"));
|
||||
@@ -266,7 +260,7 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
|
||||
}
|
||||
|
||||
|
||||
for f in failed.iter() {
|
||||
for f in &failed {
|
||||
println!("FAILED: {:?}", f);
|
||||
}
|
||||
|
||||
@@ -277,11 +271,10 @@ fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
|
||||
declare_test!{ExecutiveTests_vmArithmeticTest, "VMTests/vmArithmeticTest"}
|
||||
declare_test!{ExecutiveTests_vmBitwiseLogicOperationTest, "VMTests/vmBitwiseLogicOperationTest"}
|
||||
// this one crashes with some vm internal error. Separately they pass.
|
||||
declare_test_ignore!{ExecutiveTests_vmBlockInfoTest, "VMTests/vmBlockInfoTest"}
|
||||
declare_test!{ignore => ExecutiveTests_vmBlockInfoTest, "VMTests/vmBlockInfoTest"}
|
||||
declare_test!{ExecutiveTests_vmEnvironmentalInfoTest, "VMTests/vmEnvironmentalInfoTest"}
|
||||
declare_test!{ExecutiveTests_vmIOandFlowOperationsTest, "VMTests/vmIOandFlowOperationsTest"}
|
||||
// this one take way too long.
|
||||
declare_test_ignore!{ExecutiveTests_vmInputLimits, "VMTests/vmInputLimits"}
|
||||
declare_test!{heavy => ExecutiveTests_vmInputLimits, "VMTests/vmInputLimits"}
|
||||
declare_test!{ExecutiveTests_vmLogTest, "VMTests/vmLogTest"}
|
||||
declare_test!{ExecutiveTests_vmPerformanceTest, "VMTests/vmPerformanceTest"}
|
||||
declare_test!{ExecutiveTests_vmPushDupSwapTest, "VMTests/vmPushDupSwapTest"}
|
||||
|
||||
@@ -15,7 +15,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
|
||||
let mut fail = false;
|
||||
{
|
||||
let mut fail_unless = |cond: bool| if !cond && !fail {
|
||||
failed.push(name.to_string());
|
||||
failed.push(name.clone());
|
||||
flush(format!("FAIL\n"));
|
||||
fail = true;
|
||||
true
|
||||
@@ -73,20 +73,20 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
|
||||
|
||||
declare_test!{StateTests_stBlockHashTest, "StateTests/stBlockHashTest"}
|
||||
declare_test!{StateTests_stCallCodes, "StateTests/stCallCodes"}
|
||||
declare_test_ignore!{StateTests_stCallCreateCallCodeTest, "StateTests/stCallCreateCallCodeTest"} //<< Out of stack
|
||||
declare_test!{StateTests_stDelegatecallTest, "StateTests/stDelegatecallTest"} //<< FAIL - gas too high
|
||||
declare_test!{ignore => StateTests_stCallCreateCallCodeTest, "StateTests/stCallCreateCallCodeTest"} //<< Out of stack
|
||||
declare_test!{StateTests_stDelegatecallTest, "StateTests/stDelegatecallTest"}
|
||||
declare_test!{StateTests_stExample, "StateTests/stExample"}
|
||||
declare_test!{StateTests_stInitCodeTest, "StateTests/stInitCodeTest"}
|
||||
declare_test!{StateTests_stLogTests, "StateTests/stLogTests"}
|
||||
declare_test!{StateTests_stMemoryStressTest, "StateTests/stMemoryStressTest"}
|
||||
declare_test!{StateTests_stMemoryTest, "StateTests/stMemoryTest"}
|
||||
declare_test!{heavy => StateTests_stMemoryStressTest, "StateTests/stMemoryStressTest"}
|
||||
declare_test!{heavy => StateTests_stMemoryTest, "StateTests/stMemoryTest"}
|
||||
declare_test!{StateTests_stPreCompiledContracts, "StateTests/stPreCompiledContracts"}
|
||||
declare_test_ignore!{StateTests_stQuadraticComplexityTest, "StateTests/stQuadraticComplexityTest"} //<< Too long
|
||||
declare_test_ignore!{StateTests_stRecursiveCreate, "StateTests/stRecursiveCreate"} //<< Out of stack
|
||||
declare_test!{heavy => StateTests_stQuadraticComplexityTest, "StateTests/stQuadraticComplexityTest"} //<< Too long
|
||||
declare_test!{ignore => StateTests_stRecursiveCreate, "StateTests/stRecursiveCreate"} //<< Out of stack
|
||||
declare_test!{StateTests_stRefundTest, "StateTests/stRefundTest"}
|
||||
declare_test!{StateTests_stSolidityTest, "StateTests/stSolidityTest"}
|
||||
declare_test_ignore!{StateTests_stSpecialTest, "StateTests/stSpecialTest"} //<< Signal 11
|
||||
declare_test_ignore!{StateTests_stSystemOperationsTest, "StateTests/stSystemOperationsTest"} //<< Signal 11
|
||||
declare_test!{ignore => StateTests_stSpecialTest, "StateTests/stSpecialTest"} //<< Out of Stack
|
||||
declare_test!{ignore => StateTests_stSystemOperationsTest, "StateTests/stSystemOperationsTest"} //<< Out of stack
|
||||
declare_test!{StateTests_stTransactionTest, "StateTests/stTransactionTest"}
|
||||
declare_test!{StateTests_stTransitionTest, "StateTests/stTransitionTest"}
|
||||
declare_test!{StateTests_stWalletTest, "StateTests/stWalletTest"}
|
||||
|
||||
@@ -1,24 +1,34 @@
|
||||
pub use common::*;
|
||||
|
||||
macro_rules! test {
|
||||
($name: expr) => {
|
||||
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! declare_test {
|
||||
($id: ident, $name: expr) => {
|
||||
#[test]
|
||||
#[allow(non_snake_case)]
|
||||
fn $id() {
|
||||
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).len() == 0);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! declare_test_ignore {
|
||||
($id: ident, $name: expr) => {
|
||||
#[test]
|
||||
(ignore => $id: ident, $name: expr) => {
|
||||
#[ignore]
|
||||
#[test]
|
||||
#[allow(non_snake_case)]
|
||||
fn $id() {
|
||||
assert!(do_json_test(include_bytes!(concat!("../../res/ethereum/tests/", $name, ".json"))).len() == 0);
|
||||
test!($name);
|
||||
}
|
||||
};
|
||||
(heavy => $id: ident, $name: expr) => {
|
||||
#[cfg(feature = "test-heavy")]
|
||||
#[test]
|
||||
#[allow(non_snake_case)]
|
||||
fn $id() {
|
||||
test!($name);
|
||||
}
|
||||
};
|
||||
($id: ident, $name: expr) => {
|
||||
#[test]
|
||||
#[allow(non_snake_case)]
|
||||
fn $id() {
|
||||
test!($name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,13 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
|
||||
let ot = RefCell::new(Transaction::new());
|
||||
for (name, test) in json.as_object().unwrap() {
|
||||
let mut fail = false;
|
||||
let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); println!("Transaction: {:?}", ot.borrow()); fail = true };
|
||||
let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.clone()); println!("Transaction: {:?}", ot.borrow()); fail = true };
|
||||
let schedule = match test.find("blocknumber")
|
||||
.and_then(|j| j.as_string())
|
||||
.and_then(|s| BlockNumber::from_str(s).ok())
|
||||
.unwrap_or(0) { x if x < 900000 => &old_schedule, _ => &new_schedule };
|
||||
let rlp = Bytes::from_json(&test["rlp"]);
|
||||
let res = UntrustedRlp::new(&rlp).as_val().map_err(|e| From::from(e)).and_then(|t: Transaction| t.validate(schedule, schedule.have_delegate_call));
|
||||
let res = UntrustedRlp::new(&rlp).as_val().map_err(From::from).and_then(|t: Transaction| t.validate(schedule, schedule.have_delegate_call));
|
||||
fail_unless(test.find("transaction").is_none() == res.is_err());
|
||||
if let (Some(&Json::Object(ref tx)), Some(&Json::String(ref expect_sender))) = (test.find("transaction"), test.find("sender")) {
|
||||
let t = res.unwrap();
|
||||
@@ -30,11 +30,11 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
|
||||
fail_unless(to == &xjson!(&tx["to"]));
|
||||
} else {
|
||||
*ot.borrow_mut() = t.clone();
|
||||
fail_unless(Bytes::from_json(&tx["to"]).len() == 0);
|
||||
fail_unless(Bytes::from_json(&tx["to"]).is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
for f in failed.iter() {
|
||||
for f in &failed {
|
||||
println!("FAILED: {:?}", f);
|
||||
}
|
||||
failed
|
||||
@@ -65,14 +65,14 @@ declare_test!{TransactionTests/ttTransactionTest}
|
||||
declare_test!{TransactionTests/tt10mbDataField}
|
||||
declare_test!{TransactionTests/ttWrongRLPTransaction}
|
||||
declare_test!{TransactionTests/Homestead/ttTransactionTest}
|
||||
declare_test!{TransactionTests/Homestead/tt10mbDataField}
|
||||
declare_test!{heavy => TransactionTests/Homestead/tt10mbDataField}
|
||||
declare_test!{TransactionTests/Homestead/ttWrongRLPTransaction}
|
||||
declare_test!{TransactionTests/RandomTests/tr201506052141PYTHON}*/
|
||||
|
||||
declare_test!{TransactionTests_ttTransactionTest, "TransactionTests/ttTransactionTest"}
|
||||
declare_test_ignore!{TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"}
|
||||
declare_test!{heavy => TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"}
|
||||
declare_test!{TransactionTests_ttWrongRLPTransaction, "TransactionTests/ttWrongRLPTransaction"}
|
||||
declare_test!{TransactionTests_Homestead_ttTransactionTest, "TransactionTests/Homestead/ttTransactionTest"}
|
||||
declare_test_ignore!{TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"}
|
||||
declare_test!{heavy => TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"}
|
||||
declare_test!{TransactionTests_Homestead_ttWrongRLPTransaction, "TransactionTests/Homestead/ttWrongRLPTransaction"}
|
||||
declare_test!{TransactionTests_RandomTests_tr201506052141PYTHON, "TransactionTests/RandomTests/tr201506052141PYTHON"}
|
||||
|
||||
@@ -117,9 +117,8 @@ impl Transaction {
|
||||
};
|
||||
s.append(&self.value);
|
||||
s.append(&self.data);
|
||||
match with_seal {
|
||||
Seal::With => { s.append(&(self.v as u16)).append(&self.r).append(&self.s); },
|
||||
_ => {}
|
||||
if let Seal::With = with_seal {
|
||||
s.append(&(self.v as u16)).append(&self.r).append(&self.s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +137,7 @@ impl FromJson for Transaction {
|
||||
gas_price: xjson!(&json["gasPrice"]),
|
||||
gas: xjson!(&json["gasLimit"]),
|
||||
action: match Bytes::from_json(&json["to"]) {
|
||||
ref x if x.len() == 0 => Action::Create,
|
||||
ref x if x.is_empty() => Action::Create,
|
||||
ref x => Action::Call(Address::from_slice(x)),
|
||||
},
|
||||
value: xjson!(&json["value"]),
|
||||
@@ -303,4 +302,4 @@ fn signing() {
|
||||
let key = KeyPair::create().unwrap();
|
||||
let t = Transaction::new_create(U256::from(42u64), b"Hello!".to_vec(), U256::from(3000u64), U256::from(50_000u64), U256::from(1u64)).signed(&key.secret());
|
||||
assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ pub fn verify_block_unordered(header: Header, bytes: Bytes, engine: &Engine) ->
|
||||
/// Phase 3 verification. Check block information against parent and uncles.
|
||||
pub fn verify_block_family<BC>(header: &Header, bytes: &[u8], engine: &Engine, bc: &BC) -> Result<(), Error> where BC: BlockProvider {
|
||||
// TODO: verify timestamp
|
||||
let parent = try!(bc.block_header(&header.parent_hash).ok_or::<Error>(From::from(BlockError::UnknownParent(header.parent_hash.clone()))));
|
||||
let parent = try!(bc.block_header(&header.parent_hash).ok_or_else(|| Error::from(BlockError::UnknownParent(header.parent_hash.clone()))));
|
||||
try!(verify_parent(&header, &parent));
|
||||
try!(engine.verify_block_family(&header, &parent, Some(bytes)));
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn verify_block_family<BC>(header: &Header, bytes: &[u8], engine: &Engine, b
|
||||
// cB.p^7 -------------/
|
||||
// cB.p^8
|
||||
let mut expected_uncle_parent = header.parent_hash.clone();
|
||||
let uncle_parent = try!(bc.block_header(&uncle.parent_hash).ok_or::<Error>(From::from(BlockError::UnknownUncleParent(uncle.parent_hash.clone()))));
|
||||
let uncle_parent = try!(bc.block_header(&uncle.parent_hash).ok_or_else(|| Error::from(BlockError::UnknownUncleParent(uncle.parent_hash.clone()))));
|
||||
for _ in 0..depth {
|
||||
match bc.block_details(&expected_uncle_parent) {
|
||||
Some(details) => {
|
||||
@@ -284,7 +284,7 @@ mod tests {
|
||||
|
||||
/// Get raw block data
|
||||
fn block(&self, hash: &H256) -> Option<Bytes> {
|
||||
self.blocks.get(hash).map(|b| b.clone())
|
||||
self.blocks.get(hash).cloned()
|
||||
}
|
||||
|
||||
/// Get the familial details concerning a block.
|
||||
@@ -302,7 +302,7 @@ mod tests {
|
||||
|
||||
/// Get the hash of given block's number.
|
||||
fn block_hash(&self, index: BlockNumber) -> Option<H256> {
|
||||
self.numbers.get(&index).map(|h| h.clone())
|
||||
self.numbers.get(&index).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ impl<'a> BlockView<'a> {
|
||||
|
||||
/// Return List of transactions in given block.
|
||||
pub fn transaction_views(&self) -> Vec<TransactionView> {
|
||||
self.rlp.at(1).iter().map(|rlp| TransactionView::new_from_rlp(rlp)).collect()
|
||||
self.rlp.at(1).iter().map(TransactionView::new_from_rlp).collect()
|
||||
}
|
||||
|
||||
/// Return transaction hashes.
|
||||
@@ -156,7 +156,7 @@ impl<'a> BlockView<'a> {
|
||||
|
||||
/// Return List of transactions in given block.
|
||||
pub fn uncle_views(&self) -> Vec<HeaderView> {
|
||||
self.rlp.at(2).iter().map(|rlp| HeaderView::new_from_rlp(rlp)).collect()
|
||||
self.rlp.at(2).iter().map(HeaderView::new_from_rlp).collect()
|
||||
}
|
||||
|
||||
/// Return list of uncle hashes of given block.
|
||||
|
||||
Reference in New Issue
Block a user