Spec can now read much from a JSON. Still todo builtins and params.

This commit is contained in:
Gav Wood 2015-12-21 21:08:42 +00:00
parent c3bbf2870c
commit 07aef2499e
2 changed files with 120 additions and 16 deletions

View File

@ -34,7 +34,7 @@ impl Genesis {
pub fn new_frontier() -> Genesis { pub fn new_frontier() -> Genesis {
let root = H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap(); let root = H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap();
let json = base_to_json(include_bytes!("../res/genesis_frontier")); let json = base_to_json(include_bytes!("../res/genesis_frontier"));
let (header, state) = Self::load_genesis_json(&json, &root); let (header, state) = Self::load_genesis_json(json, root);
Self::new_from_header_and_state(header, state) Self::new_from_header_and_state(header, state)
} }
@ -53,7 +53,7 @@ impl Genesis {
} }
/// Loads genesis block from json file /// Loads genesis block from json file
fn load_genesis_json(json: &Json, state_root: &H256) -> (Header, HashMap<Address, Account>) { fn load_genesis_json(json: Json, state_root: H256) -> (Header, HashMap<Address, Account>) {
// once we commit ourselves to some json parsing library (serde?) // once we commit ourselves to some json parsing library (serde?)
// move it to proper data structure // move it to proper data structure
@ -62,11 +62,20 @@ impl Genesis {
let empty_data = encode(&""); let empty_data = encode(&"");
let empty_data_sha3 = empty_data.sha3(); let empty_data_sha3 = empty_data.sha3();
let mut state = HashMap::new();
let accounts = json["alloc"].as_object().expect("Missing genesis state");
for (address, acc) in accounts.iter() {
let addr = Address::from_str(address).unwrap();
let o = acc.as_object().unwrap();
let balance = U256::from_dec_str(o["balance"].as_string().unwrap()).unwrap();
state.insert(addr, Account::new_basic(balance, U256::from(0)));
}
let header = Header { let header = Header {
parent_hash: H256::from_str(&json["parentHash"].as_string().unwrap()[2..]).unwrap(), parent_hash: H256::from_str(&json["parentHash"].as_string().unwrap()[2..]).unwrap(),
uncles_hash: empty_list_sha3.clone(), uncles_hash: empty_list_sha3.clone(),
author: Address::from_str(&json["coinbase"].as_string().unwrap()[2..]).unwrap(), author: Address::from_str(&json["coinbase"].as_string().unwrap()[2..]).unwrap(),
state_root: state_root.clone(), state_root: state_root,
transactions_root: empty_data_sha3.clone(), transactions_root: empty_data_sha3.clone(),
receipts_root: empty_data_sha3.clone(), receipts_root: empty_data_sha3.clone(),
log_bloom: H2048::new(), log_bloom: H2048::new(),
@ -84,15 +93,6 @@ impl Genesis {
} }
}; };
let mut state = HashMap::new();
let accounts = json["alloc"].as_object().expect("Missing genesis state");
for (address, acc) in accounts.iter() {
let addr = Address::from_str(address).unwrap();
let o = acc.as_object().unwrap();
let balance = U256::from_dec_str(o["balance"].as_string().unwrap()).unwrap();
state.insert(addr, Account::new_basic(balance, U256::from(0)));
}
(header, state) (header, state)
} }

View File

@ -1,17 +1,41 @@
use std::collections::hash_map::*; use std::io::Read;
use std::collections::HashMap;
use std::cell::*; use std::cell::*;
use std::str::FromStr; use std::str::FromStr;
use rustc_serialize::base64::FromBase64;
use rustc_serialize::json::Json;
use rustc_serialize::hex::FromHex;
use flate2::read::GzDecoder;
use util::uint::*; use util::uint::*;
use util::hash::*; use util::hash::*;
use util::bytes::*; use util::bytes::*;
use util::triehash::*; use util::triehash::*;
use util::error::*; use util::error::*;
use util::rlp::*; use util::rlp::*;
use account::Account; use util::sha3::*;
use account::*;
use engine::Engine; use engine::Engine;
use builtin::Builtin; use builtin::Builtin;
use null_engine::NullEngine; use null_engine::NullEngine;
use denominations::*; use denominations::*;
use header::*;
/// Converts file from base64 gzipped bytes to json
pub fn base_to_json(source: &[u8]) -> Json {
// there is probably no need to store genesis in based64 gzip,
// but that's what go does, and it was easy to load it this way
let data = source.from_base64().expect("Genesis block is malformed!");
let data_ref: &[u8] = &data;
let mut decoder = GzDecoder::new(data_ref).expect("Gzip is invalid");
let mut s: String = "".to_string();
decoder.read_to_string(&mut s).expect("Gzip is invalid");
Json::from_str(&s).expect("Json is invalid")
}
/// Convert JSON to a string->RLP map.
pub fn json_to_rlp(_json: &Json) -> HashMap<String, Bytes> {
unimplemented!();
}
/// Parameters for a block chain; includes both those intrinsic to the design of the /// Parameters for a block chain; includes both those intrinsic to the design of the
/// chain and those to be interpreted by the active chain engine. /// chain and those to be interpreted by the active chain engine.
@ -43,6 +67,9 @@ pub struct Spec {
} }
impl Spec { impl Spec {
// pub fn new(engine_name: String, engine_params: HashMap<String, Bytes>, builtins: HashMap<Address, Builtin>, genesis: Genesis) {
// }
/// Convert this object into a boxed Engine of the right underlying type. /// Convert this object into a boxed Engine of the right underlying type.
// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead. // TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead.
pub fn to_engine(self) -> Result<Box<Engine>, EthcoreError> { pub fn to_engine(self) -> Result<Box<Engine>, EthcoreError> {
@ -62,13 +89,90 @@ impl Spec {
/// Compose the genesis block for this chain. /// Compose the genesis block for this chain.
pub fn genesis_block(&self) -> Bytes { pub fn genesis_block(&self) -> Bytes {
// TODO let empty_list = RlpStream::new_list(0).out();
unimplemented!(); let empty_list_sha3 = empty_list.sha3();
let header = Header {
parent_hash: self.parent_hash.clone(),
timestamp: self.timestamp.clone(),
number: U256::from(0u8),
author: self.author.clone(),
transactions_root: SHA3_EMPTY.clone(),
uncles_hash: empty_list_sha3.clone(),
extra_data: self.extra_data.clone(),
state_root: self.state_root().clone(),
receipts_root: SHA3_EMPTY.clone(),
log_bloom: H2048::new().clone(),
gas_used: self.gas_used.clone(),
gas_limit: self.gas_limit.clone(),
difficulty: self.difficulty.clone(),
seal: {
let seal = {
let mut s = RlpStream::new_list(self.seal_fields);
s.append_raw(&self.seal_rlp, self.seal_fields);
s.out()
};
let r = Rlp::new(&seal);
(0..self.seal_fields).map(|i| r.at(i).raw().to_vec()).collect()
},
};
let mut ret = RlpStream::new_list(3);
ret.append(&header);
ret.append_raw(&empty_list, 1);
ret.append_raw(&empty_list, 1);
ret.out()
} }
} }
impl Spec { impl Spec {
/// Loads genesis block from json file
pub fn from_json(json: Json) -> Spec {
// once we commit ourselves to some json parsing library (serde?)
// move it to proper data structure
let mut state = HashMap::new();
let accounts = json["alloc"].as_object().expect("Missing genesis state");
for (address, acc) in accounts.iter() {
let addr = Address::from_str(address).unwrap();
let o = acc.as_object().unwrap();
let balance = U256::from_dec_str(o["balance"].as_string().unwrap()).unwrap();
state.insert(addr, Account::new_basic(balance, U256::from(0)));
}
let builtins = {
// TODO: populate from json.
HashMap::new()
};
let (seal_fields, seal_rlp) = {
if json.find("mixhash").is_some() && json.find("nonce").is_some() {
let mut s = RlpStream::new();
s.append(&H256::from_str(&json["mixhash"].as_string().unwrap()[2..]).unwrap());
s.append(&H64::from_str(&json["nonce"].as_string().unwrap()[2..]).unwrap());
(2, s.out())
} else {
// backup algo that will work with sealFields/sealRlp (and without).
(usize::from_str(&json["sealFields"].as_string().unwrap_or("0x")[2..]).unwrap(), json["sealRlp"].as_string().unwrap_or("0x")[2..].from_hex().unwrap())
}
};
Spec {
engine_name: json["engineName"].as_string().unwrap().to_string(),
engine_params: json_to_rlp(&json["engineParams"]),
builtins: builtins,
parent_hash: H256::from_str(&json["parentHash"].as_string().unwrap()[2..]).unwrap(),
author: Address::from_str(&json["coinbase"].as_string().unwrap()[2..]).unwrap(),
difficulty: U256::from_str(&json["difficulty"].as_string().unwrap()[2..]).unwrap(),
gas_limit: U256::from_str(&json["gasLimit"].as_string().unwrap()[2..]).unwrap(),
gas_used: U256::from(0u8),
timestamp: U256::from_str(&json["timestamp"].as_string().unwrap()[2..]).unwrap(),
extra_data: json["extraData"].as_string().unwrap()[2..].from_hex().unwrap(),
genesis_state: state,
seal_fields: seal_fields,
seal_rlp: seal_rlp,
state_root_memo: RefCell::new(json["stateRoot"].as_string().map(|s| H256::from_str(&s[2..]).unwrap())),
}
}
pub fn olympic() -> Spec { pub fn olympic() -> Spec {
Spec { Spec {
engine_name: "Ethash".to_string(), engine_name: "Ethash".to_string(),