Upgrade ethereum types (#10670)
* cargo upgrade "ethereum-types" --all --allow-prerelease * [ethash] fix compilation errors * [ethkey] fix compilation errors * [journaldb] fix compilation errors * [dir] fix compilation errors * [ethabi] update to 0.7 * wip * [eip-712] fix compilation errors * [ethjson] fix compilation errors * [Cargo.toml] add TODO to remove patches * [ethstore] fix compilation errors * use patched keccak-hash with new primitive-types * wip * [ethcore-network-devp2p] fix compilation errors * [vm] fix compilation errors * [common-types, evm, wasm] fix compilation errors * [ethcore-db] Require AsRef instead of Deref for keys * [ethcore-blockchain] fix some compilation errors * [blooms-db] fix compilation errors Thanks a lot @dvdplm :) * we don't need no rlp ethereum feature * [ethcore] fix some compilation errors * [parity-ipfs-api] fix compilation error * [ethcore-light] fix compilation errors * [Cargo.lock] update parity-common * [ethcore-private-tx] fix some compilation errors * wip * [ethcore-private-tx] fix compilation errors * [parity-updater] fix compilation errors * [parity-rpc] fix compilation errors * [parity-bin] fix other compilation errors * update to new ethereum-types * update keccak-hash * [fastmap] fix compilation in tests * [blooms-db] fix compilation in tests * [common-types] fix compilation in tests * [triehash-ethereum] fix compilation in tests * [ethkey] fix compilation in tests * [pwasm-run-test] fix compilation errors * [wasm] fix compilation errors * [ethjson] fix compilation in tests * [eip-712] fix compilation in tests * [ethcore-blockchain] fix compilation in tests * [ethstore] fix compilation in tests * [ethstore-accounts] fix compilation in tests * [parity-hash-fetch] fix compilation in tests * [parity-whisper] fix compilation in tests * [ethcore-miner] fix compilation in tests * [ethcore-network-devp2p] fix compilation in tests * [*] upgrade rand to 0.6 * [evm] get rid of num-bigint conversions * [ethcore] downgrade trie-standardmap and criterion * [ethcore] fix some warnings * [ethcore] fix compilation in tests * [evmbin] fix compilation in tests * [updater] fix compilation in tests * [ethash] fix compilation in tests * [ethcore-secretstore] fix compilation in tests * [ethcore-sync] fix compilation in tests * [parity-rpc] fix compilation in tests * [ethcore] finally fix compilation in tests FUCK YEAH!!! * [ethstore] lazy_static is unused * [ethcore] fix test * fix up bad merge * [Cargo.toml] remove unused patches * [*] replace some git dependencies with crates.io * [Cargo.toml] remove unused lazy_static * [*] clean up * [ethcore] fix transaction_filter_deprecated test * [private-tx] fix serialization tests * fix more serialization tests * [ethkey] fix smoky test * [rpc] fix tests, please? * [ethcore] remove commented out code * Apply suggestions from code review Co-Authored-By: Tomasz Drwięga <tomusdrw@users.noreply.github.com> * [ethstore] remove unused dev-dependency * [ethcore] remove resolved TODO * [*] resolve keccak-hash TODO * [*] s/Address::default()/Address::zero() * [rpc] remove Subscribers::new_test * [rpc] remove EthPubSubClient::new_test * [ethcore] use trie-standardmap from crates.io * [dir] fix db_root_path * [ethcore] simplify snapshot::tests::helpers::fill_storage * Apply suggestions from code review Co-Authored-By: David <dvdplm@gmail.com> * [ethcore-secretstore] resolve TODO in serialization * [ethcore-network-devp2p] resolve TODO in save_key * [Cargo.lock] update triehash * [*] use ethabi from crates.io * [ethkey] use secp256k1 from master branch * [Cargo.lock] update eth-secp256k1
This commit is contained in:
parent
33d3bfae8b
commit
dae5d75dd6
586
Cargo.lock
generated
586
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -45,11 +45,11 @@ ethcore-network = { path = "util/network" }
|
|||||||
ethcore-private-tx = { path = "ethcore/private-tx" }
|
ethcore-private-tx = { path = "ethcore/private-tx" }
|
||||||
ethcore-service = { path = "ethcore/service" }
|
ethcore-service = { path = "ethcore/service" }
|
||||||
ethcore-sync = { path = "ethcore/sync" }
|
ethcore-sync = { path = "ethcore/sync" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
ethkey = { path = "accounts/ethkey" }
|
ethkey = { path = "accounts/ethkey" }
|
||||||
ethstore = { path = "accounts/ethstore" }
|
ethstore = { path = "accounts/ethstore" }
|
||||||
node-filter = { path = "ethcore/node-filter" }
|
node-filter = { path = "ethcore/node-filter" }
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
cli-signer= { path = "cli-signer" }
|
cli-signer= { path = "cli-signer" }
|
||||||
parity-daemonize = "0.3"
|
parity-daemonize = "0.3"
|
||||||
parity-hash-fetch = { path = "updater/hash-fetch" }
|
parity-hash-fetch = { path = "updater/hash-fetch" }
|
||||||
@ -63,7 +63,7 @@ parity-whisper = { path = "whisper" }
|
|||||||
parity-path = "0.1"
|
parity-path = "0.1"
|
||||||
dir = { path = "util/dir" }
|
dir = { path = "util/dir" }
|
||||||
panic_hook = { path = "util/panic-hook" }
|
panic_hook = { path = "util/panic-hook" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
migration-rocksdb = { path = "util/migration-rocksdb" }
|
migration-rocksdb = { path = "util/migration-rocksdb" }
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
kvdb-rocksdb = "0.1.3"
|
kvdb-rocksdb = "0.1.3"
|
||||||
@ -81,7 +81,6 @@ pretty_assertions = "0.1"
|
|||||||
ipnetwork = "0.12.6"
|
ipnetwork = "0.12.6"
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
fake-fetch = { path = "util/fake-fetch" }
|
fake-fetch = { path = "util/fake-fetch" }
|
||||||
lazy_static = "1.2.0"
|
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
winapi = { version = "0.3.4", features = ["winsock2", "winuser", "shellapi"] }
|
winapi = { version = "0.3.4", features = ["winsock2", "winuser", "shellapi"] }
|
||||||
|
@ -17,5 +17,5 @@ serde_derive = "1.0"
|
|||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
|
@ -8,13 +8,13 @@ byteorder = "1.0"
|
|||||||
edit-distance = "2.0"
|
edit-distance = "2.0"
|
||||||
parity-crypto = "0.4.0"
|
parity-crypto = "0.4.0"
|
||||||
eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1" }
|
eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
lazy_static = "1.0"
|
lazy_static = "1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
memzero = { path = "../../util/memzero" }
|
memzero = { path = "../../util/memzero" }
|
||||||
parity-wordlist = "1.2"
|
parity-wordlist = "1.2"
|
||||||
quick-error = "1.2.2"
|
quick-error = "1.2.2"
|
||||||
rand = "0.4"
|
rand = "0.6"
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
|
@ -47,7 +47,7 @@ impl Generator for BrainPrefix {
|
|||||||
for _ in 0..self.iterations {
|
for _ in 0..self.iterations {
|
||||||
let phrase = wordlist::random_phrase(self.no_of_words);
|
let phrase = wordlist::random_phrase(self.no_of_words);
|
||||||
let keypair = Brain::new(phrase.clone()).generate().unwrap();
|
let keypair = Brain::new(phrase.clone()).generate().unwrap();
|
||||||
if keypair.address().starts_with(&self.prefix) {
|
if keypair.address().as_ref().starts_with(&self.prefix) {
|
||||||
self.last_phrase = phrase;
|
self.last_phrase = phrase;
|
||||||
return Ok(keypair)
|
return Ok(keypair)
|
||||||
}
|
}
|
||||||
@ -65,6 +65,6 @@ mod tests {
|
|||||||
fn prefix_generator() {
|
fn prefix_generator() {
|
||||||
let prefix = vec![0x00u8];
|
let prefix = vec![0x00u8];
|
||||||
let keypair = BrainPrefix::new(prefix.clone(), usize::max_value(), 12).generate().unwrap();
|
let keypair = BrainPrefix::new(prefix.clone(), usize::max_value(), 12).generate().unwrap();
|
||||||
assert!(keypair.address().starts_with(&prefix));
|
assert!(keypair.address().as_bytes().starts_with(&prefix));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -57,7 +57,7 @@ pub mod ecdh {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let publ = key::PublicKey::from_slice(context, &pdata)?;
|
let publ = key::PublicKey::from_slice(context, &pdata)?;
|
||||||
let sec = key::SecretKey::from_slice(context, &secret)?;
|
let sec = key::SecretKey::from_slice(context, secret.as_bytes())?;
|
||||||
let shared = ecdh::SharedSecret::new_raw(context, &publ, &sec);
|
let shared = ecdh::SharedSecret::new_raw(context, &publ, &sec);
|
||||||
|
|
||||||
Secret::from_unsafe_slice(&shared[0..32])
|
Secret::from_unsafe_slice(&shared[0..32])
|
||||||
@ -89,12 +89,12 @@ pub mod ecies {
|
|||||||
msg[0] = 0x04u8;
|
msg[0] = 0x04u8;
|
||||||
{
|
{
|
||||||
let msgd = &mut msg[1..];
|
let msgd = &mut msg[1..];
|
||||||
msgd[0..64].copy_from_slice(r.public());
|
msgd[0..64].copy_from_slice(r.public().as_bytes());
|
||||||
let iv = H128::random();
|
let iv = H128::random();
|
||||||
msgd[64..80].copy_from_slice(&iv);
|
msgd[64..80].copy_from_slice(iv.as_bytes());
|
||||||
{
|
{
|
||||||
let cipher = &mut msgd[(64 + 16)..(64 + 16 + plain.len())];
|
let cipher = &mut msgd[(64 + 16)..(64 + 16 + plain.len())];
|
||||||
aes::encrypt_128_ctr(ekey, &iv, plain, cipher)?;
|
aes::encrypt_128_ctr(ekey, iv.as_bytes(), plain, cipher)?;
|
||||||
}
|
}
|
||||||
let mut hmac = hmac::Signer::with(&mkey);
|
let mut hmac = hmac::Signer::with(&mkey);
|
||||||
{
|
{
|
||||||
@ -156,7 +156,7 @@ pub mod ecies {
|
|||||||
let mut hasher = digest::Hasher::sha256();
|
let mut hasher = digest::Hasher::sha256();
|
||||||
let ctrs = [(ctr >> 24) as u8, (ctr >> 16) as u8, (ctr >> 8) as u8, ctr as u8];
|
let ctrs = [(ctr >> 24) as u8, (ctr >> 16) as u8, (ctr >> 8) as u8, ctr as u8];
|
||||||
hasher.update(&ctrs);
|
hasher.update(&ctrs);
|
||||||
hasher.update(secret);
|
hasher.update(secret.as_bytes());
|
||||||
hasher.update(s1);
|
hasher.update(s1);
|
||||||
let d = hasher.finish();
|
let d = hasher.finish();
|
||||||
&mut dest[written..(written + 32)].copy_from_slice(&d);
|
&mut dest[written..(written + 32)].copy_from_slice(&d);
|
||||||
|
@ -64,7 +64,7 @@ impl Label for H256 {
|
|||||||
fn len() -> usize { 32 }
|
fn len() -> usize { 32 }
|
||||||
|
|
||||||
fn store(&self, target: &mut [u8]) {
|
fn store(&self, target: &mut [u8]) {
|
||||||
self.copy_to(&mut target[0..32]);
|
(&mut target[0..32]).copy_from_slice(self.as_bytes());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -180,7 +180,7 @@ impl ExtendedKeyPair {
|
|||||||
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
|
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
|
||||||
let (master_key, chain_code) = derivation::seed_pair(seed);
|
let (master_key, chain_code) = derivation::seed_pair(seed);
|
||||||
Ok(ExtendedKeyPair::with_secret(
|
Ok(ExtendedKeyPair::with_secret(
|
||||||
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
|
Secret::from_unsafe_slice(master_key.as_bytes()).map_err(|_| DerivationError::InvalidSeed)?,
|
||||||
chain_code,
|
chain_code,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@ -208,12 +208,13 @@ impl ExtendedKeyPair {
|
|||||||
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
|
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
|
||||||
mod derivation {
|
mod derivation {
|
||||||
use parity_crypto::hmac;
|
use parity_crypto::hmac;
|
||||||
use ethereum_types::{U256, U512, H512, H256};
|
use ethereum_types::{BigEndianHash, U256, U512, H512, H256};
|
||||||
use secp256k1::key::{SecretKey, PublicKey};
|
use secp256k1::key::{SecretKey, PublicKey};
|
||||||
use SECP256K1;
|
use SECP256K1;
|
||||||
use keccak;
|
use keccak;
|
||||||
use math::curve_order;
|
use math::curve_order;
|
||||||
use super::{Label, Derivation};
|
use super::{Label, Derivation};
|
||||||
|
use std::convert::TryInto;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
@ -237,18 +238,18 @@ mod derivation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
|
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
|
||||||
let private: U256 = private_key.into();
|
let private: U256 = private_key.into_uint();
|
||||||
|
|
||||||
// produces 512-bit derived hmac (I)
|
// produces 512-bit derived hmac (I)
|
||||||
let skey = hmac::SigKey::sha512(&*chain_code);
|
let skey = hmac::SigKey::sha512(chain_code.as_bytes());
|
||||||
let i_512 = hmac::sign(&skey, &data[..]);
|
let i_512 = hmac::sign(&skey, &data[..]);
|
||||||
|
|
||||||
// left most 256 bits are later added to original private key
|
// left most 256 bits are later added to original private key
|
||||||
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into();
|
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into_uint();
|
||||||
// right most 256 bits are new chain code for later derivations
|
// right most 256 bits are new chain code for later derivations
|
||||||
let next_chain_code = H256::from(&i_512[32..64]);
|
let next_chain_code = H256::from_slice(&i_512[32..64]);
|
||||||
|
|
||||||
let child_key = private_add(hmac_key, private).into();
|
let child_key = BigEndianHash::from_uint(&private_add(hmac_key, private));
|
||||||
(child_key, next_chain_code)
|
(child_key, next_chain_code)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -257,7 +258,7 @@ mod derivation {
|
|||||||
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
|
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
|
||||||
let mut data = vec![0u8; 33 + T::len()];
|
let mut data = vec![0u8; 33 + T::len()];
|
||||||
|
|
||||||
let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key)
|
let sec_private = SecretKey::from_slice(&SECP256K1, private_key.as_bytes())
|
||||||
.expect("Caller should provide valid private key");
|
.expect("Caller should provide valid private key");
|
||||||
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
|
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
|
||||||
.expect("Caller should provide valid private key");
|
.expect("Caller should provide valid private key");
|
||||||
@ -276,7 +277,7 @@ mod derivation {
|
|||||||
// corresponding public keys of the original and derived private keys
|
// corresponding public keys of the original and derived private keys
|
||||||
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
|
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
|
||||||
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
|
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
|
||||||
let private: U256 = private_key.into();
|
let private: U256 = private_key.into_uint();
|
||||||
|
|
||||||
// 0x00 (padding) -- private_key -- index
|
// 0x00 (padding) -- private_key -- index
|
||||||
// 0 -- 1..33 -- 33..end
|
// 0 -- 1..33 -- 33..end
|
||||||
@ -293,9 +294,8 @@ mod derivation {
|
|||||||
|
|
||||||
// todo: surely can be optimized
|
// todo: surely can be optimized
|
||||||
fn modulo(u1: U512, u2: U256) -> U256 {
|
fn modulo(u1: U512, u2: U256) -> U256 {
|
||||||
let dv = u1 / U512::from(u2);
|
let m = u1 % U512::from(u2);
|
||||||
let md = u1 - (dv * U512::from(u2));
|
m.try_into().expect("U512 modulo U256 should fit into U256; qed")
|
||||||
md.into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
|
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
|
||||||
@ -306,7 +306,7 @@ mod derivation {
|
|||||||
|
|
||||||
let mut public_sec_raw = [0u8; 65];
|
let mut public_sec_raw = [0u8; 65];
|
||||||
public_sec_raw[0] = 4;
|
public_sec_raw[0] = 4;
|
||||||
public_sec_raw[1..65].copy_from_slice(&*public_key);
|
public_sec_raw[1..65].copy_from_slice(public_key.as_bytes());
|
||||||
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
|
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
|
||||||
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
|
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
|
||||||
|
|
||||||
@ -317,15 +317,15 @@ mod derivation {
|
|||||||
index.store(&mut data[33..(33 + T::len())]);
|
index.store(&mut data[33..(33 + T::len())]);
|
||||||
|
|
||||||
// HMAC512SHA produces [derived private(256); new chain code(256)]
|
// HMAC512SHA produces [derived private(256); new chain code(256)]
|
||||||
let skey = hmac::SigKey::sha512(&*chain_code);
|
let skey = hmac::SigKey::sha512(chain_code.as_bytes());
|
||||||
let i_512 = hmac::sign(&skey, &data[..]);
|
let i_512 = hmac::sign(&skey, &data[..]);
|
||||||
|
|
||||||
let new_private = H256::from(&i_512[0..32]);
|
let new_private = H256::from_slice(&i_512[0..32]);
|
||||||
let new_chain_code = H256::from(&i_512[32..64]);
|
let new_chain_code = H256::from_slice(&i_512[32..64]);
|
||||||
|
|
||||||
// Generated private key can (extremely rarely) be out of secp256k1 key field
|
// Generated private key can (extremely rarely) be out of secp256k1 key field
|
||||||
if curve_order() <= new_private.clone().into() { return Err(Error::MissingIndex); }
|
if curve_order() <= new_private.into_uint() { return Err(Error::MissingIndex); }
|
||||||
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
|
let new_private_sec = SecretKey::from_slice(&SECP256K1, new_private.as_bytes())
|
||||||
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
|
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
|
||||||
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
|
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
|
||||||
.expect("Valid private key produces valid public key");
|
.expect("Valid private key produces valid public key");
|
||||||
@ -337,7 +337,7 @@ mod derivation {
|
|||||||
let serialized = new_public.serialize_vec(&SECP256K1, false);
|
let serialized = new_public.serialize_vec(&SECP256K1, false);
|
||||||
|
|
||||||
Ok((
|
Ok((
|
||||||
H512::from(&serialized[1..65]),
|
H512::from_slice(&serialized[1..65]),
|
||||||
new_chain_code,
|
new_chain_code,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@ -348,18 +348,18 @@ mod derivation {
|
|||||||
|
|
||||||
pub fn chain_code(secret: H256) -> H256 {
|
pub fn chain_code(secret: H256) -> H256 {
|
||||||
// 10,000 rounds of sha3
|
// 10,000 rounds of sha3
|
||||||
let mut running_sha3 = sha3(&*secret);
|
let mut running_sha3 = sha3(secret.as_bytes());
|
||||||
for _ in 0..99999 { running_sha3 = sha3(&*running_sha3); }
|
for _ in 0..99999 { running_sha3 = sha3(running_sha3.as_bytes()); }
|
||||||
running_sha3
|
running_sha3
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn point(secret: H256) -> Result<H512, Error> {
|
pub fn point(secret: H256) -> Result<H512, Error> {
|
||||||
let sec = SecretKey::from_slice(&SECP256K1, &*secret)
|
let sec = SecretKey::from_slice(&SECP256K1, secret.as_bytes())
|
||||||
.map_err(|_| Error::InvalidPoint)?;
|
.map_err(|_| Error::InvalidPoint)?;
|
||||||
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
|
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
|
||||||
.map_err(|_| Error::InvalidPoint)?;
|
.map_err(|_| Error::InvalidPoint)?;
|
||||||
let serialized = public_sec.serialize_vec(&SECP256K1, false);
|
let serialized = public_sec.serialize_vec(&SECP256K1, false);
|
||||||
Ok(H512::from(&serialized[1..65]))
|
Ok(H512::from_slice(&serialized[1..65]))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
|
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
|
||||||
@ -378,12 +378,13 @@ mod tests {
|
|||||||
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
|
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
|
||||||
use secret::Secret;
|
use secret::Secret;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use ethereum_types::{H128, H256};
|
use ethereum_types::{H128, H256, H512};
|
||||||
use super::{derivation, Derivation};
|
use super::{derivation, Derivation};
|
||||||
|
|
||||||
fn master_chain_basic() -> (H256, H256) {
|
fn master_chain_basic() -> (H256, H256) {
|
||||||
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
|
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
|
||||||
.expect("Seed should be valid H128")
|
.expect("Seed should be valid H128")
|
||||||
|
.as_bytes()
|
||||||
.to_vec();
|
.to_vec();
|
||||||
|
|
||||||
derivation::seed_pair(&*seed)
|
derivation::seed_pair(&*seed)
|
||||||
@ -399,27 +400,39 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn smoky() {
|
fn smoky() {
|
||||||
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
||||||
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
|
let extended_secret = ExtendedSecret::with_code(secret.clone(), H256::zero());
|
||||||
|
|
||||||
// hardened
|
// hardened
|
||||||
assert_eq!(&**extended_secret.as_raw(), &*secret);
|
assert_eq!(&**extended_secret.as_raw(), &*secret);
|
||||||
assert_eq!(&**extended_secret.derive(2147483648.into()).as_raw(), &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into());
|
assert_eq!(
|
||||||
assert_eq!(&**extended_secret.derive(2147483649.into()).as_raw(), &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into());
|
**extended_secret.derive(2147483648.into()).as_raw(),
|
||||||
|
H256::from_str("0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6").unwrap(),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
**extended_secret.derive(2147483649.into()).as_raw(),
|
||||||
|
H256::from_str("44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f").unwrap(),
|
||||||
|
);
|
||||||
|
|
||||||
// normal
|
// normal
|
||||||
assert_eq!(&**extended_secret.derive(0.into()).as_raw(), &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into());
|
assert_eq!(**extended_secret.derive(0.into()).as_raw(), H256::from_str("bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6").unwrap());
|
||||||
assert_eq!(&**extended_secret.derive(1.into()).as_raw(), &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into());
|
assert_eq!(**extended_secret.derive(1.into()).as_raw(), H256::from_str("bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc").unwrap());
|
||||||
assert_eq!(&**extended_secret.derive(2.into()).as_raw(), &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into());
|
assert_eq!(**extended_secret.derive(2.into()).as_raw(), H256::from_str("86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268").unwrap());
|
||||||
|
|
||||||
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
||||||
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
|
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
|
||||||
assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into());
|
assert_eq!(
|
||||||
|
*derived_public.public(),
|
||||||
|
H512::from_str("f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94").unwrap(),
|
||||||
|
);
|
||||||
|
|
||||||
let keypair = ExtendedKeyPair::with_secret(
|
let keypair = ExtendedKeyPair::with_secret(
|
||||||
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
|
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
|
||||||
064.into(),
|
H256::from_low_u64_be(64),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(),
|
||||||
|
H256::from_str("edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c").unwrap(),
|
||||||
);
|
);
|
||||||
assert_eq!(&**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(), &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -427,7 +440,7 @@ mod tests {
|
|||||||
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
||||||
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
|
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
|
||||||
|
|
||||||
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
|
let extended_secret = ExtendedSecret::with_code(secret.clone(), H256::zero());
|
||||||
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
||||||
|
|
||||||
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
|
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
|
||||||
@ -442,15 +455,18 @@ mod tests {
|
|||||||
fn h256_hard() {
|
fn h256_hard() {
|
||||||
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
||||||
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
|
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
|
||||||
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into());
|
let extended_secret = ExtendedSecret::with_code(secret.clone(), H256::from_low_u64_be(1));
|
||||||
|
|
||||||
assert_eq!(&**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(), &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into());
|
assert_eq!(
|
||||||
|
**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(),
|
||||||
|
H256::from_str("2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486").unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn match_() {
|
fn match_() {
|
||||||
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
|
||||||
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into());
|
let extended_secret = ExtendedSecret::with_code(secret.clone(), H256::from_low_u64_be(1));
|
||||||
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
|
||||||
|
|
||||||
let derived_secret0 = extended_secret.derive(0.into());
|
let derived_secret0 = extended_secret.derive(0.into());
|
||||||
@ -465,6 +481,7 @@ mod tests {
|
|||||||
fn test_seeds() {
|
fn test_seeds() {
|
||||||
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
|
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
|
||||||
.expect("Seed should be valid H128")
|
.expect("Seed should be valid H128")
|
||||||
|
.as_bytes()
|
||||||
.to_vec();
|
.to_vec();
|
||||||
|
|
||||||
// private key from bitcoin test vector
|
// private key from bitcoin test vector
|
||||||
|
@ -16,14 +16,13 @@
|
|||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use secp256k1::key;
|
use secp256k1::key;
|
||||||
use rustc_hex::ToHex;
|
|
||||||
use keccak::Keccak256;
|
|
||||||
use super::{Secret, Public, Address, SECP256K1, Error};
|
use super::{Secret, Public, Address, SECP256K1, Error};
|
||||||
|
use parity_crypto::Keccak256 as _;
|
||||||
|
|
||||||
pub fn public_to_address(public: &Public) -> Address {
|
pub fn public_to_address(public: &Public) -> Address {
|
||||||
let hash = public.keccak256();
|
let hash = public.keccak256();
|
||||||
let mut result = Address::default();
|
let mut result = Address::zero();
|
||||||
result.copy_from_slice(&hash[12..]);
|
result.as_bytes_mut().copy_from_slice(&hash[12..]);
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,9 +35,9 @@ pub struct KeyPair {
|
|||||||
|
|
||||||
impl fmt::Display for KeyPair {
|
impl fmt::Display for KeyPair {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||||
writeln!(f, "secret: {}", self.secret.to_hex())?;
|
writeln!(f, "secret: {:x}", self.secret)?;
|
||||||
writeln!(f, "public: {}", self.public.to_hex())?;
|
writeln!(f, "public: {:x}", self.public)?;
|
||||||
write!(f, "address: {}", self.address().to_hex())
|
write!(f, "address: {:x}", self.address())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,7 +50,7 @@ impl KeyPair {
|
|||||||
let serialized = pub_key.serialize_vec(context, false);
|
let serialized = pub_key.serialize_vec(context, false);
|
||||||
|
|
||||||
let mut public = Public::default();
|
let mut public = Public::default();
|
||||||
public.copy_from_slice(&serialized[1..65]);
|
public.as_bytes_mut().copy_from_slice(&serialized[1..65]);
|
||||||
|
|
||||||
let keypair = KeyPair {
|
let keypair = KeyPair {
|
||||||
secret: secret,
|
secret: secret,
|
||||||
@ -70,7 +69,7 @@ impl KeyPair {
|
|||||||
let serialized = publ.serialize_vec(context, false);
|
let serialized = publ.serialize_vec(context, false);
|
||||||
let secret = Secret::from(sec);
|
let secret = Secret::from(sec);
|
||||||
let mut public = Public::default();
|
let mut public = Public::default();
|
||||||
public.copy_from_slice(&serialized[1..65]);
|
public.as_bytes_mut().copy_from_slice(&serialized[1..65]);
|
||||||
|
|
||||||
KeyPair {
|
KeyPair {
|
||||||
secret: secret,
|
secret: secret,
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
use super::{SECP256K1, Public, Secret, Error};
|
use super::{SECP256K1, Public, Secret, Error};
|
||||||
use secp256k1::key;
|
use secp256k1::key;
|
||||||
use secp256k1::constants::{GENERATOR_X, GENERATOR_Y, CURVE_ORDER};
|
use secp256k1::constants::{GENERATOR_X, GENERATOR_Y, CURVE_ORDER};
|
||||||
use ethereum_types::{U256, H256};
|
use ethereum_types::{BigEndianHash as _, U256, H256};
|
||||||
|
|
||||||
/// Whether the public key is valid.
|
/// Whether the public key is valid.
|
||||||
pub fn public_is_valid(public: &Public) -> bool {
|
pub fn public_is_valid(public: &Public) -> bool {
|
||||||
@ -78,7 +78,7 @@ pub fn generation_point() -> Public {
|
|||||||
|
|
||||||
/// Return secp256k1 elliptic curve order
|
/// Return secp256k1 elliptic curve order
|
||||||
pub fn curve_order() -> U256 {
|
pub fn curve_order() -> U256 {
|
||||||
H256::from_slice(&CURVE_ORDER).into()
|
H256::from_slice(&CURVE_ORDER).into_uint()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_secp256k1_public(public: &Public) -> Result<key::PublicKey, Error> {
|
fn to_secp256k1_public(public: &Public) -> Result<key::PublicKey, Error> {
|
||||||
@ -93,7 +93,7 @@ fn to_secp256k1_public(public: &Public) -> Result<key::PublicKey, Error> {
|
|||||||
|
|
||||||
fn set_public(public: &mut Public, key_public: &key::PublicKey) {
|
fn set_public(public: &mut Public, key_public: &key::PublicKey) {
|
||||||
let key_public_serialized = key_public.serialize_vec(&SECP256K1, false);
|
let key_public_serialized = key_public.serialize_vec(&SECP256K1, false);
|
||||||
public.copy_from_slice(&key_public_serialized[1..65]);
|
public.as_bytes_mut().copy_from_slice(&key_public_serialized[1..65]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
@ -37,7 +37,7 @@ impl Generator for Prefix {
|
|||||||
fn generate(&mut self) -> Result<KeyPair, Error> {
|
fn generate(&mut self) -> Result<KeyPair, Error> {
|
||||||
for _ in 0..self.iterations {
|
for _ in 0..self.iterations {
|
||||||
let keypair = Random.generate()?;
|
let keypair = Random.generate()?;
|
||||||
if keypair.address().starts_with(&self.prefix) {
|
if keypair.address().as_ref().starts_with(&self.prefix) {
|
||||||
return Ok(keypair)
|
return Ok(keypair)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -54,6 +54,6 @@ mod tests {
|
|||||||
fn prefix_generator() {
|
fn prefix_generator() {
|
||||||
let prefix = vec![0xffu8];
|
let prefix = vec![0xffu8];
|
||||||
let keypair = Prefix::new(prefix.clone(), usize::max_value()).generate().unwrap();
|
let keypair = Prefix::new(prefix.clone(), usize::max_value()).generate().unwrap();
|
||||||
assert!(keypair.address().starts_with(&prefix));
|
assert!(keypair.address().as_bytes().starts_with(&prefix));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use rand::os::OsRng;
|
use rand::rngs::OsRng;
|
||||||
use super::{Generator, KeyPair, SECP256K1};
|
use super::{Generator, KeyPair, SECP256K1};
|
||||||
|
|
||||||
/// Randomly generates new keypair, instantiating the RNG each time.
|
/// Randomly generates new keypair, instantiating the RNG each time.
|
||||||
|
@ -59,14 +59,14 @@ impl Secret {
|
|||||||
if key.len() != 32 {
|
if key.len() != 32 {
|
||||||
return None
|
return None
|
||||||
}
|
}
|
||||||
let mut h = H256::default();
|
let mut h = H256::zero();
|
||||||
h.copy_from_slice(&key[0..32]);
|
h.as_bytes_mut().copy_from_slice(&key[0..32]);
|
||||||
Some(Secret { inner: Memzero::from(h) })
|
Some(Secret { inner: Memzero::from(h) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates zero key, which is invalid for crypto operations, but valid for math operation.
|
/// Creates zero key, which is invalid for crypto operations, but valid for math operation.
|
||||||
pub fn zero() -> Self {
|
pub fn zero() -> Self {
|
||||||
Secret { inner: Memzero::from(H256::default()) }
|
Secret { inner: Memzero::from(H256::zero()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Imports and validates the key.
|
/// Imports and validates the key.
|
||||||
|
@ -68,24 +68,44 @@ impl Signature {
|
|||||||
/// Create a signature object from the sig.
|
/// Create a signature object from the sig.
|
||||||
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self {
|
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self {
|
||||||
let mut sig = [0u8; 65];
|
let mut sig = [0u8; 65];
|
||||||
sig[0..32].copy_from_slice(&r);
|
sig[0..32].copy_from_slice(r.as_ref());
|
||||||
sig[32..64].copy_from_slice(&s);
|
sig[32..64].copy_from_slice(s.as_ref());
|
||||||
sig[64] = v;
|
sig[64] = v;
|
||||||
Signature(sig)
|
Signature(sig)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if this is a "low" signature.
|
/// Check if this is a "low" signature.
|
||||||
pub fn is_low_s(&self) -> bool {
|
pub fn is_low_s(&self) -> bool {
|
||||||
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
|
// "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"
|
||||||
|
const MASK: H256 = H256([
|
||||||
|
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||||
|
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
|
||||||
|
0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D,
|
||||||
|
0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0,
|
||||||
|
]);
|
||||||
|
H256::from_slice(self.s()) <= MASK
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if each component of the signature is in range.
|
/// Check if each component of the signature is in range.
|
||||||
pub fn is_valid(&self) -> bool {
|
pub fn is_valid(&self) -> bool {
|
||||||
|
// "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
|
||||||
|
const MASK: H256 = H256([
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
|
||||||
|
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
|
||||||
|
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41,
|
||||||
|
]);
|
||||||
|
const ONE: H256 = H256([
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
|
||||||
|
]);
|
||||||
|
let r = H256::from_slice(self.r());
|
||||||
|
let s = H256::from_slice(self.s());
|
||||||
self.v() <= 1 &&
|
self.v() <= 1 &&
|
||||||
H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
|
r < MASK && r >= ONE &&
|
||||||
H256::from_slice(self.r()) >= 1.into() &&
|
s < MASK && s >= ONE
|
||||||
H256::from_slice(self.s()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() &&
|
|
||||||
H256::from_slice(self.s()) >= 1.into()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -190,7 +210,7 @@ impl DerefMut for Signature {
|
|||||||
|
|
||||||
pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
|
pub fn sign(secret: &Secret, message: &Message) -> Result<Signature, Error> {
|
||||||
let context = &SECP256K1;
|
let context = &SECP256K1;
|
||||||
let sec = SecretKey::from_slice(context, &secret)?;
|
let sec = SecretKey::from_slice(context, secret.as_ref())?;
|
||||||
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
|
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
|
||||||
let (rec_id, data) = s.serialize_compact(context);
|
let (rec_id, data) = s.serialize_compact(context);
|
||||||
let mut data_arr = [0; 65];
|
let mut data_arr = [0; 65];
|
||||||
@ -208,7 +228,7 @@ pub fn verify_public(public: &Public, signature: &Signature, message: &Message)
|
|||||||
|
|
||||||
let pdata: [u8; 65] = {
|
let pdata: [u8; 65] = {
|
||||||
let mut temp = [4u8; 65];
|
let mut temp = [4u8; 65];
|
||||||
temp[1..65].copy_from_slice(&**public);
|
temp[1..65].copy_from_slice(public.as_bytes());
|
||||||
temp
|
temp
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -233,7 +253,7 @@ pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error
|
|||||||
let serialized = pubkey.serialize_vec(context, false);
|
let serialized = pubkey.serialize_vec(context, false);
|
||||||
|
|
||||||
let mut public = Public::default();
|
let mut public = Public::default();
|
||||||
public.copy_from_slice(&serialized[1..65]);
|
public.as_bytes_mut().copy_from_slice(&serialized[1..65]);
|
||||||
Ok(public)
|
Ok(public)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
rand = "0.4"
|
rand = "0.6"
|
||||||
ethkey = { path = "../ethkey" }
|
ethkey = { path = "../ethkey" }
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
@ -17,12 +17,11 @@ time = "0.1.34"
|
|||||||
itertools = "0.5"
|
itertools = "0.5"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
parity-crypto = "0.4.0"
|
parity-crypto = "0.4.0"
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
dir = { path = "../../util/dir" }
|
dir = { path = "../../util/dir" }
|
||||||
smallvec = "0.6"
|
smallvec = "0.6"
|
||||||
parity-wordlist = "1.0"
|
parity-wordlist = "1.0"
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
lazy_static = "1.2.0"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
matches = "0.1"
|
matches = "0.1"
|
||||||
|
@ -21,4 +21,4 @@ path = "src/main.rs"
|
|||||||
doc = false
|
doc = false
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempdir = "0.3.5"
|
tempdir = "0.3"
|
||||||
|
@ -74,7 +74,7 @@ impl From<Crypto> for String {
|
|||||||
impl Crypto {
|
impl Crypto {
|
||||||
/// Encrypt account secret
|
/// Encrypt account secret
|
||||||
pub fn with_secret(secret: &Secret, password: &Password, iterations: u32) -> Result<Self, crypto::Error> {
|
pub fn with_secret(secret: &Secret, password: &Password, iterations: u32) -> Result<Self, crypto::Error> {
|
||||||
Crypto::with_plain(&*secret, password, iterations)
|
Crypto::with_plain(secret.as_ref(), password, iterations)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encrypt custom plain data
|
/// Encrypt custom plain data
|
||||||
|
@ -68,7 +68,7 @@ impl KeyDirectory for MemoryDirectory {
|
|||||||
fn unique_repr(&self) -> Result<u64, Error> {
|
fn unique_repr(&self) -> Result<u64, Error> {
|
||||||
let mut val = 0u64;
|
let mut val = 0u64;
|
||||||
let accounts = self.accounts.read();
|
let accounts = self.accounts.read();
|
||||||
for acc in accounts.keys() { val = val ^ acc.low_u64() }
|
for acc in accounts.keys() { val = val ^ acc.to_low_u64_be() }
|
||||||
Ok(val)
|
Ok(val)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1084,7 +1084,7 @@ mod tests {
|
|||||||
SecretVaultRef::Root,
|
SecretVaultRef::Root,
|
||||||
&address,
|
&address,
|
||||||
&"test".into(),
|
&"test".into(),
|
||||||
Derivation::HardHash(H256::from(0)),
|
Derivation::HardHash(H256::zero()),
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
// there should be 2 accounts in the store
|
// there should be 2 accounts in the store
|
||||||
|
@ -36,8 +36,6 @@ extern crate ethereum_types;
|
|||||||
extern crate ethkey as _ethkey;
|
extern crate ethkey as _ethkey;
|
||||||
extern crate parity_wordlist;
|
extern crate parity_wordlist;
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate lazy_static;
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log;
|
extern crate log;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use rand::{Rng, OsRng};
|
use rand::{Rng, RngCore, rngs::OsRng, distributions::Alphanumeric};
|
||||||
|
|
||||||
pub trait Random {
|
pub trait Random {
|
||||||
fn random() -> Self where Self: Sized;
|
fn random() -> Self where Self: Sized;
|
||||||
@ -41,5 +41,5 @@ impl Random for [u8; 32] {
|
|||||||
/// Generate a random string of given length.
|
/// Generate a random string of given length.
|
||||||
pub fn random_string(length: usize) -> String {
|
pub fn random_string(length: usize) -> String {
|
||||||
let mut rng = OsRng::new().expect("Not able to operate without random source.");
|
let mut rng = OsRng::new().expect("Not able to operate without random source.");
|
||||||
rng.gen_ascii_chars().take(length).collect()
|
rng.sample_iter(&Alphanumeric).take(length).collect()
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
extern crate rand;
|
extern crate rand;
|
||||||
extern crate ethstore;
|
extern crate ethstore;
|
||||||
|
extern crate ethereum_types;
|
||||||
|
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
@ -23,6 +24,8 @@ use ethstore::{EthStore, SimpleSecretStore, SecretVaultRef, StoreAccountRef};
|
|||||||
use ethstore::ethkey::{Random, Generator, Secret, KeyPair, verify_address};
|
use ethstore::ethkey::{Random, Generator, Secret, KeyPair, verify_address};
|
||||||
use ethstore::accounts_dir::RootDiskDirectory;
|
use ethstore::accounts_dir::RootDiskDirectory;
|
||||||
use util::TransientDir;
|
use util::TransientDir;
|
||||||
|
use ethereum_types::Address;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn secret_store_create() {
|
fn secret_store_create() {
|
||||||
@ -114,9 +117,9 @@ fn secret_store_laod_geth_files() {
|
|||||||
let dir = RootDiskDirectory::at(test_path());
|
let dir = RootDiskDirectory::at(test_path());
|
||||||
let store = EthStore::open(Box::new(dir)).unwrap();
|
let store = EthStore::open(Box::new(dir)).unwrap();
|
||||||
assert_eq!(store.accounts().unwrap(), vec![
|
assert_eq!(store.accounts().unwrap(), vec![
|
||||||
StoreAccountRef::root("3f49624084b67849c7b4e805c5988c21a430f9d9".into()),
|
StoreAccountRef::root(Address::from_str("3f49624084b67849c7b4e805c5988c21a430f9d9").unwrap()),
|
||||||
StoreAccountRef::root("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf".into()),
|
StoreAccountRef::root(Address::from_str("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf").unwrap()),
|
||||||
StoreAccountRef::root("63121b431a52f8043c16fcf0d1df9cb7b5f66649".into()),
|
StoreAccountRef::root(Address::from_str("63121b431a52f8043c16fcf0d1df9cb7b5f66649").unwrap()),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -125,8 +128,8 @@ fn secret_store_load_pat_files() {
|
|||||||
let dir = RootDiskDirectory::at(pat_path());
|
let dir = RootDiskDirectory::at(pat_path());
|
||||||
let store = EthStore::open(Box::new(dir)).unwrap();
|
let store = EthStore::open(Box::new(dir)).unwrap();
|
||||||
assert_eq!(store.accounts().unwrap(), vec![
|
assert_eq!(store.accounts().unwrap(), vec![
|
||||||
StoreAccountRef::root("3f49624084b67849c7b4e805c5988c21a430f9d9".into()),
|
StoreAccountRef::root(Address::from_str("3f49624084b67849c7b4e805c5988c21a430f9d9").unwrap()),
|
||||||
StoreAccountRef::root("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf".into()),
|
StoreAccountRef::root(Address::from_str("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf").unwrap()),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -140,8 +143,8 @@ fn test_decrypting_files_with_short_ciphertext() {
|
|||||||
let store = EthStore::open(Box::new(dir)).unwrap();
|
let store = EthStore::open(Box::new(dir)).unwrap();
|
||||||
let accounts = store.accounts().unwrap();
|
let accounts = store.accounts().unwrap();
|
||||||
assert_eq!(accounts, vec![
|
assert_eq!(accounts, vec![
|
||||||
StoreAccountRef::root("31e9d1e6d844bd3a536800ef8d8be6a9975db509".into()),
|
StoreAccountRef::root(Address::from_str("31e9d1e6d844bd3a536800ef8d8be6a9975db509").unwrap()),
|
||||||
StoreAccountRef::root("d1e64e5480bfaf733ba7d48712decb8227797a4e".into()),
|
StoreAccountRef::root(Address::from_str("d1e64e5480bfaf733ba7d48712decb8227797a4e").unwrap()),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let message = Default::default();
|
let message = Default::default();
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::{env, fs};
|
use std::{env, fs};
|
||||||
use rand::{Rng, OsRng};
|
use rand::{RngCore, rngs::OsRng};
|
||||||
use ethstore::accounts_dir::{KeyDirectory, RootDiskDirectory};
|
use ethstore::accounts_dir::{KeyDirectory, RootDiskDirectory};
|
||||||
use ethstore::{Error, SafeAccount};
|
use ethstore::{Error, SafeAccount};
|
||||||
|
|
||||||
|
@ -528,7 +528,7 @@ mod tests {
|
|||||||
let derived_addr = ap.derive_account(
|
let derived_addr = ap.derive_account(
|
||||||
&kp.address(),
|
&kp.address(),
|
||||||
None,
|
None,
|
||||||
Derivation::SoftHash(H256::from(999)),
|
Derivation::SoftHash(H256::from_low_u64_be(999)),
|
||||||
false,
|
false,
|
||||||
).expect("Derivation should not fail");
|
).expect("Derivation should not fail");
|
||||||
|
|
||||||
@ -546,7 +546,7 @@ mod tests {
|
|||||||
let derived_addr = ap.derive_account(
|
let derived_addr = ap.derive_account(
|
||||||
&kp.address(),
|
&kp.address(),
|
||||||
None,
|
None,
|
||||||
Derivation::SoftHash(H256::from(999)),
|
Derivation::SoftHash(H256::from_low_u64_be(999)),
|
||||||
true,
|
true,
|
||||||
).expect("Derivation should not fail");
|
).expect("Derivation should not fail");
|
||||||
|
|
||||||
@ -567,7 +567,7 @@ mod tests {
|
|||||||
let derived_addr = ap.derive_account(
|
let derived_addr = ap.derive_account(
|
||||||
&kp.address(),
|
&kp.address(),
|
||||||
None,
|
None,
|
||||||
Derivation::SoftHash(H256::from(1999)),
|
Derivation::SoftHash(H256::from_low_u64_be(1999)),
|
||||||
true,
|
true,
|
||||||
).expect("Derivation should not fail");
|
).expect("Derivation should not fail");
|
||||||
ap.unlock_account_permanently(derived_addr, "base".into())
|
ap.unlock_account_permanently(derived_addr, "base".into())
|
||||||
@ -579,7 +579,7 @@ mod tests {
|
|||||||
let signed_msg2 = ap.sign_derived(
|
let signed_msg2 = ap.sign_derived(
|
||||||
&kp.address(),
|
&kp.address(),
|
||||||
None,
|
None,
|
||||||
Derivation::SoftHash(H256::from(1999)),
|
Derivation::SoftHash(H256::from_low_u64_be(1999)),
|
||||||
msg,
|
msg,
|
||||||
).expect("Derived signing with existing unlocked account should not fail");
|
).expect("Derived signing with existing unlocked account should not fail");
|
||||||
|
|
||||||
|
@ -153,7 +153,7 @@ impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::AddressBook;
|
use super::{AddressBook, Address};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
use crate::account_data::AccountMeta;
|
use crate::account_data::AccountMeta;
|
||||||
@ -162,12 +162,12 @@ mod tests {
|
|||||||
fn should_save_and_reload_address_book() {
|
fn should_save_and_reload_address_book() {
|
||||||
let tempdir = TempDir::new("").unwrap();
|
let tempdir = TempDir::new("").unwrap();
|
||||||
let mut b = AddressBook::new(tempdir.path());
|
let mut b = AddressBook::new(tempdir.path());
|
||||||
b.set_name(1.into(), "One".to_owned());
|
b.set_name(Address::from_low_u64_be(1), "One".to_owned());
|
||||||
b.set_meta(1.into(), "{1:1}".to_owned());
|
b.set_meta(Address::from_low_u64_be(1), "{1:1}".to_owned());
|
||||||
let b = AddressBook::new(tempdir.path());
|
let b = AddressBook::new(tempdir.path());
|
||||||
assert_eq!(b.get(), vec![
|
assert_eq!(b.get(), vec![
|
||||||
(1, AccountMeta {name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None})
|
(Address::from_low_u64_be(1), AccountMeta {name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None})
|
||||||
].into_iter().map(|(a, b)| (a.into(), b)).collect::<HashMap<_, _>>());
|
].into_iter().collect::<HashMap<_, _>>());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -175,15 +175,15 @@ mod tests {
|
|||||||
let tempdir = TempDir::new("").unwrap();
|
let tempdir = TempDir::new("").unwrap();
|
||||||
let mut b = AddressBook::new(tempdir.path());
|
let mut b = AddressBook::new(tempdir.path());
|
||||||
|
|
||||||
b.set_name(1.into(), "One".to_owned());
|
b.set_name(Address::from_low_u64_be(1), "One".to_owned());
|
||||||
b.set_name(2.into(), "Two".to_owned());
|
b.set_name(Address::from_low_u64_be(2), "Two".to_owned());
|
||||||
b.set_name(3.into(), "Three".to_owned());
|
b.set_name(Address::from_low_u64_be(3), "Three".to_owned());
|
||||||
b.remove(2.into());
|
b.remove(Address::from_low_u64_be(2).into());
|
||||||
|
|
||||||
let b = AddressBook::new(tempdir.path());
|
let b = AddressBook::new(tempdir.path());
|
||||||
assert_eq!(b.get(), vec![
|
assert_eq!(b.get(), vec![
|
||||||
(1, AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
(Address::from_low_u64_be(1), AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
||||||
(3, AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
(Address::from_low_u64_be(3), AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
||||||
].into_iter().map(|(a, b)| (a.into(), b)).collect::<HashMap<_, _>>());
|
].into_iter().collect::<HashMap<_, _>>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ name = "cli-signer"
|
|||||||
version = "1.4.0"
|
version = "1.4.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
rpassword = "1.0"
|
rpassword = "1.0"
|
||||||
parity-rpc = { path = "../rpc" }
|
parity-rpc = { path = "../rpc" }
|
||||||
|
@ -7,7 +7,7 @@ name = "parity-rpc-client"
|
|||||||
version = "1.4.0"
|
version = "1.4.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
@ -18,4 +18,4 @@ parking_lot = "0.7"
|
|||||||
jsonrpc-core = "10.0.1"
|
jsonrpc-core = "10.0.1"
|
||||||
jsonrpc-ws-server = "10.0.1"
|
jsonrpc-ws-server = "10.0.1"
|
||||||
parity-rpc = { path = "../../rpc" }
|
parity-rpc = { path = "../../rpc" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
|
@ -6,8 +6,8 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
crunchy = "0.1.0"
|
crunchy = "0.1.0"
|
||||||
either = "1.0.0"
|
either = "1.0.0"
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
memmap = "0.6"
|
memmap = "0.6"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
|
@ -52,14 +52,14 @@ mod progpow;
|
|||||||
pub use cache::{NodeCacheBuilder, OptimizeFor};
|
pub use cache::{NodeCacheBuilder, OptimizeFor};
|
||||||
pub use compute::{ProofOfWork, quick_get_difficulty, slow_hash_block_number};
|
pub use compute::{ProofOfWork, quick_get_difficulty, slow_hash_block_number};
|
||||||
use compute::Light;
|
use compute::Light;
|
||||||
use ethereum_types::{U256, U512};
|
use ethereum_types::{BigEndianHash, U256, U512};
|
||||||
use keccak::H256;
|
use keccak::H256;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
pub use seed_compute::SeedHashCompute;
|
pub use seed_compute::SeedHashCompute;
|
||||||
pub use shared::ETHASH_EPOCH_LENGTH;
|
pub use shared::ETHASH_EPOCH_LENGTH;
|
||||||
use std::mem;
|
use std::mem;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::convert::TryFrom;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
struct LightCache {
|
struct LightCache {
|
||||||
@ -161,12 +161,12 @@ impl EthashManager {
|
|||||||
|
|
||||||
/// Convert an Ethash boundary to its original difficulty. Basically just `f(x) = 2^256 / x`.
|
/// Convert an Ethash boundary to its original difficulty. Basically just `f(x) = 2^256 / x`.
|
||||||
pub fn boundary_to_difficulty(boundary: ðereum_types::H256) -> U256 {
|
pub fn boundary_to_difficulty(boundary: ðereum_types::H256) -> U256 {
|
||||||
difficulty_to_boundary_aux(&**boundary)
|
difficulty_to_boundary_aux(&boundary.into_uint())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert an Ethash difficulty to the target boundary. Basically just `f(x) = 2^256 / x`.
|
/// Convert an Ethash difficulty to the target boundary. Basically just `f(x) = 2^256 / x`.
|
||||||
pub fn difficulty_to_boundary(difficulty: &U256) -> ethereum_types::H256 {
|
pub fn difficulty_to_boundary(difficulty: &U256) -> ethereum_types::H256 {
|
||||||
difficulty_to_boundary_aux(difficulty).into()
|
BigEndianHash::from_uint(&difficulty_to_boundary_aux(difficulty))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn difficulty_to_boundary_aux<T: Into<U512>>(difficulty: T) -> ethereum_types::U256 {
|
fn difficulty_to_boundary_aux<T: Into<U512>>(difficulty: T) -> ethereum_types::U256 {
|
||||||
@ -177,8 +177,8 @@ fn difficulty_to_boundary_aux<T: Into<U512>>(difficulty: T) -> ethereum_types::U
|
|||||||
if difficulty == U512::one() {
|
if difficulty == U512::one() {
|
||||||
U256::max_value()
|
U256::max_value()
|
||||||
} else {
|
} else {
|
||||||
// difficulty > 1, so result should never overflow 256 bits
|
const PROOF: &str = "difficulty > 1, so result never overflows 256 bits; qed";
|
||||||
U256::from((U512::one() << 256) / difficulty)
|
U256::try_from((U512::one() << 256) / difficulty).expect(PROOF)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -203,10 +203,10 @@ fn test_lru() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_difficulty_to_boundary() {
|
fn test_difficulty_to_boundary() {
|
||||||
use ethereum_types::H256;
|
use ethereum_types::{H256, BigEndianHash};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
assert_eq!(difficulty_to_boundary(&U256::from(1)), H256::from(U256::max_value()));
|
assert_eq!(difficulty_to_boundary(&U256::from(1)), BigEndianHash::from_uint(&U256::max_value()));
|
||||||
assert_eq!(difficulty_to_boundary(&U256::from(2)), H256::from_str("8000000000000000000000000000000000000000000000000000000000000000").unwrap());
|
assert_eq!(difficulty_to_boundary(&U256::from(2)), H256::from_str("8000000000000000000000000000000000000000000000000000000000000000").unwrap());
|
||||||
assert_eq!(difficulty_to_boundary(&U256::from(4)), H256::from_str("4000000000000000000000000000000000000000000000000000000000000000").unwrap());
|
assert_eq!(difficulty_to_boundary(&U256::from(4)), H256::from_str("4000000000000000000000000000000000000000000000000000000000000000").unwrap());
|
||||||
assert_eq!(difficulty_to_boundary(&U256::from(32)), H256::from_str("0800000000000000000000000000000000000000000000000000000000000000").unwrap());
|
assert_eq!(difficulty_to_boundary(&U256::from(32)), H256::from_str("0800000000000000000000000000000000000000000000000000000000000000").unwrap());
|
||||||
@ -220,9 +220,18 @@ fn test_difficulty_to_boundary_regression() {
|
|||||||
// https://github.com/paritytech/parity-ethereum/issues/8397
|
// https://github.com/paritytech/parity-ethereum/issues/8397
|
||||||
for difficulty in 1..9 {
|
for difficulty in 1..9 {
|
||||||
assert_eq!(U256::from(difficulty), boundary_to_difficulty(&difficulty_to_boundary(&difficulty.into())));
|
assert_eq!(U256::from(difficulty), boundary_to_difficulty(&difficulty_to_boundary(&difficulty.into())));
|
||||||
assert_eq!(H256::from(difficulty), difficulty_to_boundary(&boundary_to_difficulty(&difficulty.into())));
|
assert_eq!(
|
||||||
assert_eq!(U256::from(difficulty), boundary_to_difficulty(&boundary_to_difficulty(&difficulty.into()).into()));
|
H256::from_low_u64_be(difficulty),
|
||||||
assert_eq!(H256::from(difficulty), difficulty_to_boundary(&difficulty_to_boundary(&difficulty.into()).into()));
|
difficulty_to_boundary(&boundary_to_difficulty(&H256::from_low_u64_be(difficulty))),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
U256::from(difficulty),
|
||||||
|
boundary_to_difficulty(&BigEndianHash::from_uint(&boundary_to_difficulty(&H256::from_low_u64_be(difficulty)))),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
H256::from_low_u64_be(difficulty),
|
||||||
|
difficulty_to_boundary(&difficulty_to_boundary(&difficulty.into()).into_uint()),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -235,5 +244,5 @@ fn test_difficulty_to_boundary_panics_on_zero() {
|
|||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
#[should_panic]
|
||||||
fn test_boundary_to_difficulty_panics_on_zero() {
|
fn test_boundary_to_difficulty_panics_on_zero() {
|
||||||
boundary_to_difficulty(ðereum_types::H256::from(0));
|
boundary_to_difficulty(ðereum_types::H256::zero());
|
||||||
}
|
}
|
||||||
|
@ -15,9 +15,9 @@ common-types = { path = "types" }
|
|||||||
crossbeam = "0.4"
|
crossbeam = "0.4"
|
||||||
derive_more = "0.14.0"
|
derive_more = "0.14.0"
|
||||||
env_logger = { version = "0.5", optional = true }
|
env_logger = { version = "0.5", optional = true }
|
||||||
ethabi = "6.0"
|
ethabi = "8.0"
|
||||||
ethabi-contract = "6.0"
|
ethabi-contract = "8.0"
|
||||||
ethabi-derive = "6.0"
|
ethabi-derive = "8.0"
|
||||||
ethash = { path = "../ethash" }
|
ethash = { path = "../ethash" }
|
||||||
ethcore-blockchain = { path = "./blockchain" }
|
ethcore-blockchain = { path = "./blockchain" }
|
||||||
ethcore-bloom-journal = { path = "../util/bloom" }
|
ethcore-bloom-journal = { path = "../util/bloom" }
|
||||||
@ -26,7 +26,7 @@ ethcore-db = { path = "./db" }
|
|||||||
ethcore-io = { path = "../util/io" }
|
ethcore-io = { path = "../util/io" }
|
||||||
ethcore-miner = { path = "../miner" }
|
ethcore-miner = { path = "../miner" }
|
||||||
ethcore-stratum = { path = "../miner/stratum", optional = true }
|
ethcore-stratum = { path = "../miner/stratum", optional = true }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
ethjson = { path = "../json" }
|
ethjson = { path = "../json" }
|
||||||
ethkey = { path = "../accounts/ethkey" }
|
ethkey = { path = "../accounts/ethkey" }
|
||||||
evm = { path = "evm" }
|
evm = { path = "evm" }
|
||||||
@ -35,7 +35,7 @@ hash-db = "0.11.0"
|
|||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
itertools = "0.5"
|
itertools = "0.5"
|
||||||
journaldb = { path = "../util/journaldb" }
|
journaldb = { path = "../util/journaldb" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
keccak-hasher = { path = "../util/keccak-hasher" }
|
keccak-hasher = { path = "../util/keccak-hasher" }
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
kvdb-memorydb = "0.1"
|
kvdb-memorydb = "0.1"
|
||||||
@ -55,15 +55,15 @@ parity-snappy = "0.1"
|
|||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
trie-db = "0.11.0"
|
trie-db = "0.11.0"
|
||||||
patricia-trie-ethereum = { path = "../util/patricia-trie-ethereum" }
|
patricia-trie-ethereum = { path = "../util/patricia-trie-ethereum" }
|
||||||
rand = "0.4"
|
rand = "0.6"
|
||||||
rayon = "1.0"
|
rayon = "1.0"
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
rlp_derive = { path = "../util/rlp-derive" }
|
rlp_derive = { path = "../util/rlp-derive" }
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
stats = { path = "../util/stats" }
|
stats = { path = "../util/stats" }
|
||||||
tempdir = {version="0.3", optional = true}
|
tempdir = { version = "0.3", optional = true }
|
||||||
time-utils = { path = "../util/time-utils" }
|
time-utils = { path = "../util/time-utils" }
|
||||||
trace-time = "0.1"
|
trace-time = "0.1"
|
||||||
triehash-ethereum = { version = "0.2", path = "../util/triehash-ethereum" }
|
triehash-ethereum = { version = "0.2", path = "../util/triehash-ethereum" }
|
||||||
@ -71,6 +71,7 @@ unexpected = { path = "../util/unexpected" }
|
|||||||
using_queue = { path = "../miner/using-queue" }
|
using_queue = { path = "../miner/using-queue" }
|
||||||
vm = { path = "vm" }
|
vm = { path = "vm" }
|
||||||
wasm = { path = "wasm" }
|
wasm = { path = "wasm" }
|
||||||
|
rand_xorshift = "0.1.1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
blooms-db = { path = "../util/blooms-db" }
|
blooms-db = { path = "../util/blooms-db" }
|
||||||
@ -82,7 +83,7 @@ kvdb-rocksdb = "0.1.3"
|
|||||||
parity-runtime = { path = "../util/runtime" }
|
parity-runtime = { path = "../util/runtime" }
|
||||||
rlp_compress = { path = "../util/rlp-compress" }
|
rlp_compress = { path = "../util/rlp-compress" }
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
trie-standardmap = "0.1"
|
trie-standardmap = "0.12.3"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
parity = ["work-notify", "price-info", "stratum"]
|
parity = ["work-notify", "price-info", "stratum"]
|
||||||
|
@ -12,7 +12,7 @@ ansi_term = "0.10"
|
|||||||
blooms-db = { path = "../../util/blooms-db" }
|
blooms-db = { path = "../../util/blooms-db" }
|
||||||
common-types = { path = "../types" }
|
common-types = { path = "../types" }
|
||||||
ethcore-db = { path = "../db" }
|
ethcore-db = { path = "../db" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
itertools = "0.5"
|
itertools = "0.5"
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
@ -20,14 +20,14 @@ log = "0.4"
|
|||||||
parity-bytes = "0.1"
|
parity-bytes = "0.1"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
rayon = "1.0"
|
rayon = "1.0"
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
rlp_compress = { path = "../../util/rlp-compress" }
|
rlp_compress = { path = "../../util/rlp-compress" }
|
||||||
rlp_derive = { path = "../../util/rlp-derive" }
|
rlp_derive = { path = "../../util/rlp-derive" }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.5"
|
env_logger = "0.5"
|
||||||
ethkey = { path = "../../accounts/ethkey" }
|
ethkey = { path = "../../accounts/ethkey" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
kvdb-memorydb = "0.1"
|
kvdb-memorydb = "0.1"
|
||||||
|
@ -284,7 +284,7 @@ impl BlockProvider for BlockChain {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read from DB and populate cache
|
// Read from DB and populate cache
|
||||||
let b = self.db.key_value().get(db::COL_HEADERS, hash)
|
let b = self.db.key_value().get(db::COL_HEADERS, hash.as_bytes())
|
||||||
.expect("Low level database error when fetching block header data. Some issue with disk?")?;
|
.expect("Low level database error when fetching block header data. Some issue with disk?")?;
|
||||||
|
|
||||||
let header = encoded::Header::new(decompress(&b, blocks_swapper()).into_vec());
|
let header = encoded::Header::new(decompress(&b, blocks_swapper()).into_vec());
|
||||||
@ -314,7 +314,7 @@ impl BlockProvider for BlockChain {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Read from DB and populate cache
|
// Read from DB and populate cache
|
||||||
let b = self.db.key_value().get(db::COL_BODIES, hash)
|
let b = self.db.key_value().get(db::COL_BODIES, hash.as_bytes())
|
||||||
.expect("Low level database error when fetching block body data. Some issue with disk?")?;
|
.expect("Low level database error when fetching block body data. Some issue with disk?")?;
|
||||||
|
|
||||||
let body = encoded::Body::new(decompress(&b, blocks_swapper()).into_vec());
|
let body = encoded::Body::new(decompress(&b, blocks_swapper()).into_vec());
|
||||||
@ -469,7 +469,7 @@ impl<'a> Iterator for AncestryWithMetadataIter<'a> {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
self.current = H256::default();
|
self.current = H256::zero();
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -572,13 +572,13 @@ impl BlockChain {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut batch = DBTransaction::new();
|
let mut batch = DBTransaction::new();
|
||||||
batch.put(db::COL_HEADERS, &hash, block.header_rlp().as_raw());
|
batch.put(db::COL_HEADERS, hash.as_bytes(), block.header_rlp().as_raw());
|
||||||
batch.put(db::COL_BODIES, &hash, &Self::block_to_body(genesis));
|
batch.put(db::COL_BODIES, hash.as_bytes(), &Self::block_to_body(genesis));
|
||||||
|
|
||||||
batch.write(db::COL_EXTRA, &hash, &details);
|
batch.write(db::COL_EXTRA, &hash, &details);
|
||||||
batch.write(db::COL_EXTRA, &header.number(), &hash);
|
batch.write(db::COL_EXTRA, &header.number(), &hash);
|
||||||
|
|
||||||
batch.put(db::COL_EXTRA, b"best", &hash);
|
batch.put(db::COL_EXTRA, b"best", hash.as_bytes());
|
||||||
bc.db.key_value().write(batch).expect("Low level database error when fetching 'best' block. Some issue with disk?");
|
bc.db.key_value().write(batch).expect("Low level database error when fetching 'best' block. Some issue with disk?");
|
||||||
hash
|
hash
|
||||||
}
|
}
|
||||||
@ -639,7 +639,7 @@ impl BlockChain {
|
|||||||
if hash != bc.genesis_hash() {
|
if hash != bc.genesis_hash() {
|
||||||
trace!("First block calculated: {:?}", hash);
|
trace!("First block calculated: {:?}", hash);
|
||||||
let mut batch = db.key_value().transaction();
|
let mut batch = db.key_value().transaction();
|
||||||
batch.put(db::COL_EXTRA, b"first", &hash);
|
batch.put(db::COL_EXTRA, b"first", hash.as_bytes());
|
||||||
db.key_value().write(batch).expect("Low level database error when writing 'first' block. Some issue with disk?");
|
db.key_value().write(batch).expect("Low level database error when writing 'first' block. Some issue with disk?");
|
||||||
bc.first_block = Some(hash);
|
bc.first_block = Some(hash);
|
||||||
}
|
}
|
||||||
@ -788,8 +788,8 @@ impl BlockChain {
|
|||||||
let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper());
|
let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper());
|
||||||
|
|
||||||
// store block in db
|
// store block in db
|
||||||
batch.put(db::COL_HEADERS, &hash, &compressed_header);
|
batch.put(db::COL_HEADERS, hash.as_bytes(), &compressed_header);
|
||||||
batch.put(db::COL_BODIES, &hash, &compressed_body);
|
batch.put(db::COL_BODIES, hash.as_bytes(), &compressed_body);
|
||||||
|
|
||||||
let maybe_parent = self.block_details(&block_parent_hash);
|
let maybe_parent = self.block_details(&block_parent_hash);
|
||||||
|
|
||||||
@ -932,7 +932,7 @@ impl BlockChain {
|
|||||||
*pending_best_ancient_block = Some(None);
|
*pending_best_ancient_block = Some(None);
|
||||||
} else if block_number > ancient_number {
|
} else if block_number > ancient_number {
|
||||||
trace!(target: "blockchain", "Updating the best ancient block to {}.", block_number);
|
trace!(target: "blockchain", "Updating the best ancient block to {}.", block_number);
|
||||||
batch.put(db::COL_EXTRA, b"ancient", &block_hash);
|
batch.put(db::COL_EXTRA, b"ancient", block_hash.as_bytes());
|
||||||
*pending_best_ancient_block = Some(Some(BestAncientBlock {
|
*pending_best_ancient_block = Some(Some(BestAncientBlock {
|
||||||
hash: *block_hash,
|
hash: *block_hash,
|
||||||
number: block_number,
|
number: block_number,
|
||||||
@ -1072,8 +1072,8 @@ impl BlockChain {
|
|||||||
let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper());
|
let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper());
|
||||||
|
|
||||||
// store block in db
|
// store block in db
|
||||||
batch.put(db::COL_HEADERS, &hash, &compressed_header);
|
batch.put(db::COL_HEADERS, hash.as_bytes(), &compressed_header);
|
||||||
batch.put(db::COL_BODIES, &hash, &compressed_body);
|
batch.put(db::COL_BODIES, hash.as_bytes(), &compressed_body);
|
||||||
|
|
||||||
let info = self.block_info(&block.header_view(), route, &extras);
|
let info = self.block_info(&block.header_view(), route, &extras);
|
||||||
|
|
||||||
@ -1172,7 +1172,7 @@ impl BlockChain {
|
|||||||
{
|
{
|
||||||
let mut best_block = self.pending_best_block.write();
|
let mut best_block = self.pending_best_block.write();
|
||||||
if is_best && update.info.location != BlockLocation::Branch {
|
if is_best && update.info.location != BlockLocation::Branch {
|
||||||
batch.put(db::COL_EXTRA, b"best", &update.info.hash);
|
batch.put(db::COL_EXTRA, b"best", update.info.hash.as_bytes());
|
||||||
*best_block = Some(BestBlock {
|
*best_block = Some(BestBlock {
|
||||||
total_difficulty: update.info.total_difficulty,
|
total_difficulty: update.info.total_difficulty,
|
||||||
header: update.block.decode_header(),
|
header: update.block.decode_header(),
|
||||||
@ -1259,7 +1259,7 @@ impl BlockChain {
|
|||||||
current: if self.is_known(&first) {
|
current: if self.is_known(&first) {
|
||||||
first
|
first
|
||||||
} else {
|
} else {
|
||||||
H256::default() // zero hash
|
H256::zero() // zero hash
|
||||||
},
|
},
|
||||||
chain: self
|
chain: self
|
||||||
}
|
}
|
||||||
@ -1571,6 +1571,7 @@ mod tests {
|
|||||||
use keccak_hash::keccak;
|
use keccak_hash::keccak;
|
||||||
use rustc_hex::FromHex;
|
use rustc_hex::FromHex;
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
struct TestBlockChainDB {
|
struct TestBlockChainDB {
|
||||||
_blooms_dir: TempDir,
|
_blooms_dir: TempDir,
|
||||||
@ -1629,8 +1630,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn insert_block_batch(batch: &mut DBTransaction, bc: &BlockChain, block: encoded::Block, receipts: Vec<Receipt>) -> ImportRoute {
|
fn insert_block_batch(batch: &mut DBTransaction, bc: &BlockChain, block: encoded::Block, receipts: Vec<Receipt>) -> ImportRoute {
|
||||||
use crate::ExtrasInsert;
|
|
||||||
|
|
||||||
let fork_choice = {
|
let fork_choice = {
|
||||||
let header = block.header_view();
|
let header = block.header_view();
|
||||||
let parent_hash = header.parent_hash();
|
let parent_hash = header.parent_hash();
|
||||||
@ -2057,7 +2056,7 @@ mod tests {
|
|||||||
fn find_transaction_by_hash() {
|
fn find_transaction_by_hash() {
|
||||||
let genesis = "f901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0af81e09f8c46ca322193edfda764fa7e88e81923f802f1d325ec0b0308ac2cd0a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083023e38808454c98c8142a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421880102030405060708c0c0".from_hex().unwrap();
|
let genesis = "f901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0af81e09f8c46ca322193edfda764fa7e88e81923f802f1d325ec0b0308ac2cd0a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083023e38808454c98c8142a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421880102030405060708c0c0".from_hex().unwrap();
|
||||||
let b1 = "f904a8f901faa0ce1f26f798dd03c8782d63b3e42e79a64eaea5694ea686ac5d7ce3df5171d1aea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0a65c2364cd0f1542d761823dc0109c6b072f14c20459598c5455c274601438f4a070616ebd7ad2ed6fb7860cf7e9df00163842351c38a87cac2c1cb193895035a2a05c5b4fc43c2d45787f54e1ae7d27afdb4ad16dfc567c5692070d5c4556e0b1d7b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200000183023ec683021536845685109780a029f07836e4e59229b3a065913afc27702642c683bba689910b2b2fd45db310d3888957e6d004a31802f902a7f85f800a8255f094aaaf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca0575da4e21b66fa764be5f74da9389e67693d066fb0d1312e19e17e501da00ecda06baf5a5327595f6619dfc2fcb3f2e6fb410b5810af3cb52d0e7508038e91a188f85f010a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba04fa966bf34b93abc1bcd665554b7f316b50f928477b50be0f3285ead29d18c5ba017bba0eeec1625ab433746955e125d46d80b7fdc97386c51266f842d8e02192ef85f020a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca004377418ae981cc32b1312b4a427a1d69a821b28db8584f5f2bd8c6d42458adaa053a1dba1af177fac92f3b6af0a9fa46a22adf56e686c93794b6a012bf254abf5f85f030a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca04fe13febd28a05f4fcb2f451d7ddc2dda56486d9f8c79a62b0ba4da775122615a0651b2382dd402df9ebc27f8cb4b2e0f3cea68dda2dca0ee9603608f0b6f51668f85f040a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba078e6a0ba086a08f8450e208a399bb2f2d2a0d984acd2517c7c7df66ccfab567da013254002cd45a97fac049ae00afbc43ed0d9961d0c56a3b2382c80ce41c198ddf85f050a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba0a7174d8f43ea71c8e3ca9477691add8d80ac8e0ed89d8d8b572041eef81f4a54a0534ea2e28ec4da3b5b944b18c51ec84a5cf35f5b3343c5fb86521fd2d388f506f85f060a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba034bd04065833536a10c77ee2a43a5371bc6d34837088b861dd9d4b7f44074b59a078807715786a13876d3455716a6b9cb2186b7a4887a5c31160fc877454958616c0".from_hex().unwrap();
|
let b1 = "f904a8f901faa0ce1f26f798dd03c8782d63b3e42e79a64eaea5694ea686ac5d7ce3df5171d1aea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0a65c2364cd0f1542d761823dc0109c6b072f14c20459598c5455c274601438f4a070616ebd7ad2ed6fb7860cf7e9df00163842351c38a87cac2c1cb193895035a2a05c5b4fc43c2d45787f54e1ae7d27afdb4ad16dfc567c5692070d5c4556e0b1d7b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200000183023ec683021536845685109780a029f07836e4e59229b3a065913afc27702642c683bba689910b2b2fd45db310d3888957e6d004a31802f902a7f85f800a8255f094aaaf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca0575da4e21b66fa764be5f74da9389e67693d066fb0d1312e19e17e501da00ecda06baf5a5327595f6619dfc2fcb3f2e6fb410b5810af3cb52d0e7508038e91a188f85f010a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba04fa966bf34b93abc1bcd665554b7f316b50f928477b50be0f3285ead29d18c5ba017bba0eeec1625ab433746955e125d46d80b7fdc97386c51266f842d8e02192ef85f020a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca004377418ae981cc32b1312b4a427a1d69a821b28db8584f5f2bd8c6d42458adaa053a1dba1af177fac92f3b6af0a9fa46a22adf56e686c93794b6a012bf254abf5f85f030a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca04fe13febd28a05f4fcb2f451d7ddc2dda56486d9f8c79a62b0ba4da775122615a0651b2382dd402df9ebc27f8cb4b2e0f3cea68dda2dca0ee9603608f0b6f51668f85f040a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba078e6a0ba086a08f8450e208a399bb2f2d2a0d984acd2517c7c7df66ccfab567da013254002cd45a97fac049ae00afbc43ed0d9961d0c56a3b2382c80ce41c198ddf85f050a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba0a7174d8f43ea71c8e3ca9477691add8d80ac8e0ed89d8d8b572041eef81f4a54a0534ea2e28ec4da3b5b944b18c51ec84a5cf35f5b3343c5fb86521fd2d388f506f85f060a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba034bd04065833536a10c77ee2a43a5371bc6d34837088b861dd9d4b7f44074b59a078807715786a13876d3455716a6b9cb2186b7a4887a5c31160fc877454958616c0".from_hex().unwrap();
|
||||||
let b1_hash: H256 = "f53f268d23a71e85c7d6d83a9504298712b84c1a2ba220441c86eeda0bf0b6e3".into();
|
let b1_hash = H256::from_str("f53f268d23a71e85c7d6d83a9504298712b84c1a2ba220441c86eeda0bf0b6e3").unwrap();
|
||||||
|
|
||||||
let db = new_db();
|
let db = new_db();
|
||||||
let bc = new_chain(encoded::Block::new(genesis), db.clone());
|
let bc = new_chain(encoded::Block::new(genesis), db.clone());
|
||||||
@ -2130,7 +2129,7 @@ mod tests {
|
|||||||
let db = new_db();
|
let db = new_db();
|
||||||
let bc = new_chain(genesis.last().encoded(), db.clone());
|
let bc = new_chain(genesis.last().encoded(), db.clone());
|
||||||
insert_block(&db, &bc, b1.last().encoded(), vec![Receipt {
|
insert_block(&db, &bc, b1.last().encoded(), vec![Receipt {
|
||||||
outcome: TransactionOutcome::StateRoot(H256::default()),
|
outcome: TransactionOutcome::StateRoot(H256::zero()),
|
||||||
gas_used: 10_000.into(),
|
gas_used: 10_000.into(),
|
||||||
log_bloom: Default::default(),
|
log_bloom: Default::default(),
|
||||||
logs: vec![
|
logs: vec![
|
||||||
@ -2139,7 +2138,7 @@ mod tests {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
Receipt {
|
Receipt {
|
||||||
outcome: TransactionOutcome::StateRoot(H256::default()),
|
outcome: TransactionOutcome::StateRoot(H256::zero()),
|
||||||
gas_used: 10_000.into(),
|
gas_used: 10_000.into(),
|
||||||
log_bloom: Default::default(),
|
log_bloom: Default::default(),
|
||||||
logs: vec![
|
logs: vec![
|
||||||
@ -2148,7 +2147,7 @@ mod tests {
|
|||||||
}]);
|
}]);
|
||||||
insert_block(&db, &bc, b2.last().encoded(), vec![
|
insert_block(&db, &bc, b2.last().encoded(), vec![
|
||||||
Receipt {
|
Receipt {
|
||||||
outcome: TransactionOutcome::StateRoot(H256::default()),
|
outcome: TransactionOutcome::StateRoot(H256::zero()),
|
||||||
gas_used: 10_000.into(),
|
gas_used: 10_000.into(),
|
||||||
log_bloom: Default::default(),
|
log_bloom: Default::default(),
|
||||||
logs: vec![
|
logs: vec![
|
||||||
@ -2158,7 +2157,7 @@ mod tests {
|
|||||||
]);
|
]);
|
||||||
insert_block(&db, &bc, b3.last().encoded(), vec![
|
insert_block(&db, &bc, b3.last().encoded(), vec![
|
||||||
Receipt {
|
Receipt {
|
||||||
outcome: TransactionOutcome::StateRoot(H256::default()),
|
outcome: TransactionOutcome::StateRoot(H256::zero()),
|
||||||
gas_used: 10_000.into(),
|
gas_used: 10_000.into(),
|
||||||
log_bloom: Default::default(),
|
log_bloom: Default::default(),
|
||||||
logs: vec![
|
logs: vec![
|
||||||
@ -2237,11 +2236,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_bloom_filter_simple() {
|
fn test_bloom_filter_simple() {
|
||||||
let bloom_b1: Bloom = "00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000".into();
|
let bloom_b1 = Bloom::from_str("00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000").unwrap();
|
||||||
|
|
||||||
let bloom_b2: Bloom = "00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
|
let bloom_b2 = Bloom::from_str("00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
|
||||||
|
|
||||||
let bloom_ba: Bloom = "00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
|
let bloom_ba = Bloom::from_str("00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
|
||||||
|
|
||||||
let genesis = BlockBuilder::genesis();
|
let genesis = BlockBuilder::genesis();
|
||||||
let b1 = genesis.add_block_with(|| BlockOptions {
|
let b1 = genesis.add_block_with(|| BlockOptions {
|
||||||
@ -2305,11 +2304,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_insert_unordered() {
|
fn test_insert_unordered() {
|
||||||
let bloom_b1: Bloom = "00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000".into();
|
let bloom_b1 = Bloom::from_str("00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000").unwrap();
|
||||||
|
|
||||||
let bloom_b2: Bloom = "00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
|
let bloom_b2 = Bloom::from_str("00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
|
||||||
|
|
||||||
let bloom_b3: Bloom = "00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
|
let bloom_b3 = Bloom::from_str("00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
|
||||||
|
|
||||||
let genesis = BlockBuilder::genesis();
|
let genesis = BlockBuilder::genesis();
|
||||||
let b1 = genesis.add_block_with_bloom(bloom_b1);
|
let b1 = genesis.add_block_with_bloom(bloom_b1);
|
||||||
|
@ -68,7 +68,7 @@ impl From<BlockInfo> for ImportRoute {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use ethereum_types::{H256, U256};
|
use ethereum_types::{U256, BigEndianHash};
|
||||||
use crate::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData};
|
use crate::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData};
|
||||||
use super::ImportRoute;
|
use super::ImportRoute;
|
||||||
|
|
||||||
@ -84,7 +84,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn import_route_branch() {
|
fn import_route_branch() {
|
||||||
let info = BlockInfo {
|
let info = BlockInfo {
|
||||||
hash: H256::from(U256::from(1)),
|
hash: BigEndianHash::from_uint(&U256::from(1)),
|
||||||
number: 0,
|
number: 0,
|
||||||
total_difficulty: U256::from(0),
|
total_difficulty: U256::from(0),
|
||||||
location: BlockLocation::Branch,
|
location: BlockLocation::Branch,
|
||||||
@ -93,14 +93,14 @@ mod tests {
|
|||||||
assert_eq!(ImportRoute::from(info), ImportRoute {
|
assert_eq!(ImportRoute::from(info), ImportRoute {
|
||||||
retracted: vec![],
|
retracted: vec![],
|
||||||
enacted: vec![],
|
enacted: vec![],
|
||||||
omitted: vec![H256::from(U256::from(1))],
|
omitted: vec![BigEndianHash::from_uint(&U256::from(1))],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn import_route_canon_chain() {
|
fn import_route_canon_chain() {
|
||||||
let info = BlockInfo {
|
let info = BlockInfo {
|
||||||
hash: H256::from(U256::from(1)),
|
hash: BigEndianHash::from_uint(&U256::from(1)),
|
||||||
number: 0,
|
number: 0,
|
||||||
total_difficulty: U256::from(0),
|
total_difficulty: U256::from(0),
|
||||||
location: BlockLocation::CanonChain,
|
location: BlockLocation::CanonChain,
|
||||||
@ -108,7 +108,7 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(ImportRoute::from(info), ImportRoute {
|
assert_eq!(ImportRoute::from(info), ImportRoute {
|
||||||
retracted: vec![],
|
retracted: vec![],
|
||||||
enacted: vec![H256::from(U256::from(1))],
|
enacted: vec![BigEndianHash::from_uint(&U256::from(1))],
|
||||||
omitted: vec![],
|
omitted: vec![],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -116,19 +116,19 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn import_route_branch_becoming_canon_chain() {
|
fn import_route_branch_becoming_canon_chain() {
|
||||||
let info = BlockInfo {
|
let info = BlockInfo {
|
||||||
hash: H256::from(U256::from(2)),
|
hash: BigEndianHash::from_uint(&U256::from(2)),
|
||||||
number: 0,
|
number: 0,
|
||||||
total_difficulty: U256::from(0),
|
total_difficulty: U256::from(0),
|
||||||
location: BlockLocation::BranchBecomingCanonChain(BranchBecomingCanonChainData {
|
location: BlockLocation::BranchBecomingCanonChain(BranchBecomingCanonChainData {
|
||||||
ancestor: H256::from(U256::from(0)),
|
ancestor: BigEndianHash::from_uint(&U256::from(0)),
|
||||||
enacted: vec![H256::from(U256::from(1))],
|
enacted: vec![BigEndianHash::from_uint(&U256::from(1))],
|
||||||
retracted: vec![H256::from(U256::from(3)), H256::from(U256::from(4))],
|
retracted: vec![BigEndianHash::from_uint(&U256::from(3)), BigEndianHash::from_uint(&U256::from(4))],
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(ImportRoute::from(info), ImportRoute {
|
assert_eq!(ImportRoute::from(info), ImportRoute {
|
||||||
retracted: vec![H256::from(U256::from(3)), H256::from(U256::from(4))],
|
retracted: vec![BigEndianHash::from_uint(&U256::from(3)), BigEndianHash::from_uint(&U256::from(4))],
|
||||||
enacted: vec![H256::from(U256::from(1)), H256::from(U256::from(2))],
|
enacted: vec![BigEndianHash::from_uint(&U256::from(1)), BigEndianHash::from_uint(&U256::from(2))],
|
||||||
omitted: vec![],
|
omitted: vec![],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,5 @@ edition = "2018"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
types = { path = "../types", package = "common-types" }
|
types = { path = "../types", package = "common-types" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
bytes = { version = "0.1", package = "parity-bytes" }
|
bytes = { version = "0.1", package = "parity-bytes" }
|
||||||
|
@ -9,9 +9,9 @@ edition = "2018"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common-types = { path = "../types" }
|
common-types = { path = "../types" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
rlp_derive = { path = "../../util/rlp-derive" }
|
rlp_derive = { path = "../../util/rlp-derive" }
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
//! Database utilities and definitions.
|
//! Database utilities and definitions.
|
||||||
|
|
||||||
use std::ops::Deref;
|
use std::convert::AsRef;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
@ -82,7 +82,7 @@ impl<K, V> Cache<K, V> for HashMap<K, V> where K: Hash + Eq {
|
|||||||
/// Should be used to get database key associated with given value.
|
/// Should be used to get database key associated with given value.
|
||||||
pub trait Key<T> {
|
pub trait Key<T> {
|
||||||
/// The db key associated with this value.
|
/// The db key associated with this value.
|
||||||
type Target: Deref<Target = [u8]>;
|
type Target: AsRef<[u8]>;
|
||||||
|
|
||||||
/// Returns db key.
|
/// Returns db key.
|
||||||
fn key(&self) -> Self::Target;
|
fn key(&self) -> Self::Target;
|
||||||
@ -91,16 +91,16 @@ pub trait Key<T> {
|
|||||||
/// Should be used to write value into database.
|
/// Should be used to write value into database.
|
||||||
pub trait Writable {
|
pub trait Writable {
|
||||||
/// Writes the value into the database.
|
/// Writes the value into the database.
|
||||||
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) where T: rlp::Encodable, R: Deref<Target = [u8]>;
|
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) where T: rlp::Encodable, R: AsRef<[u8]>;
|
||||||
|
|
||||||
/// Deletes key from the databse.
|
/// Deletes key from the databse.
|
||||||
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) where T: rlp::Encodable, R: Deref<Target = [u8]>;
|
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) where T: rlp::Encodable, R: AsRef<[u8]>;
|
||||||
|
|
||||||
/// Writes the value into the database and updates the cache.
|
/// Writes the value into the database and updates the cache.
|
||||||
fn write_with_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, T>, key: K, value: T, policy: CacheUpdatePolicy) where
|
fn write_with_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, T>, key: K, value: T, policy: CacheUpdatePolicy) where
|
||||||
K: Key<T, Target = R> + Hash + Eq,
|
K: Key<T, Target = R> + Hash + Eq,
|
||||||
T: rlp::Encodable,
|
T: rlp::Encodable,
|
||||||
R: Deref<Target = [u8]> {
|
R: AsRef<[u8]> {
|
||||||
self.write(col, &key, &value);
|
self.write(col, &key, &value);
|
||||||
match policy {
|
match policy {
|
||||||
CacheUpdatePolicy::Overwrite => {
|
CacheUpdatePolicy::Overwrite => {
|
||||||
@ -116,7 +116,7 @@ pub trait Writable {
|
|||||||
fn extend_with_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, T>, values: HashMap<K, T>, policy: CacheUpdatePolicy) where
|
fn extend_with_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, T>, values: HashMap<K, T>, policy: CacheUpdatePolicy) where
|
||||||
K: Key<T, Target = R> + Hash + Eq,
|
K: Key<T, Target = R> + Hash + Eq,
|
||||||
T: rlp::Encodable,
|
T: rlp::Encodable,
|
||||||
R: Deref<Target = [u8]> {
|
R: AsRef<[u8]> {
|
||||||
match policy {
|
match policy {
|
||||||
CacheUpdatePolicy::Overwrite => {
|
CacheUpdatePolicy::Overwrite => {
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
@ -137,7 +137,7 @@ pub trait Writable {
|
|||||||
fn extend_with_option_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, Option<T>>, values: HashMap<K, Option<T>>, policy: CacheUpdatePolicy) where
|
fn extend_with_option_cache<K, T, R>(&mut self, col: Option<u32>, cache: &mut Cache<K, Option<T>>, values: HashMap<K, Option<T>>, policy: CacheUpdatePolicy) where
|
||||||
K: Key<T, Target = R> + Hash + Eq,
|
K: Key<T, Target = R> + Hash + Eq,
|
||||||
T: rlp::Encodable,
|
T: rlp::Encodable,
|
||||||
R: Deref<Target = [u8]> {
|
R: AsRef<[u8]> {
|
||||||
match policy {
|
match policy {
|
||||||
CacheUpdatePolicy::Overwrite => {
|
CacheUpdatePolicy::Overwrite => {
|
||||||
for (key, value) in values {
|
for (key, value) in values {
|
||||||
@ -167,7 +167,7 @@ pub trait Readable {
|
|||||||
/// Returns value for given key.
|
/// Returns value for given key.
|
||||||
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T> where
|
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T> where
|
||||||
T: rlp::Decodable,
|
T: rlp::Decodable,
|
||||||
R: Deref<Target = [u8]>;
|
R: AsRef<[u8]>;
|
||||||
|
|
||||||
/// Returns value for given key either in cache or in database.
|
/// Returns value for given key either in cache or in database.
|
||||||
fn read_with_cache<K, T, C>(&self, col: Option<u32>, cache: &RwLock<C>, key: &K) -> Option<T> where
|
fn read_with_cache<K, T, C>(&self, col: Option<u32>, cache: &RwLock<C>, key: &K) -> Option<T> where
|
||||||
@ -189,12 +189,12 @@ pub trait Readable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns true if given value exists.
|
/// Returns true if given value exists.
|
||||||
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool where R: Deref<Target= [u8]>;
|
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool where R: AsRef<[u8]>;
|
||||||
|
|
||||||
/// Returns true if given value exists either in cache or in database.
|
/// Returns true if given value exists either in cache or in database.
|
||||||
fn exists_with_cache<K, T, R, C>(&self, col: Option<u32>, cache: &RwLock<C>, key: &K) -> bool where
|
fn exists_with_cache<K, T, R, C>(&self, col: Option<u32>, cache: &RwLock<C>, key: &K) -> bool where
|
||||||
K: Eq + Hash + Key<T, Target = R>,
|
K: Eq + Hash + Key<T, Target = R>,
|
||||||
R: Deref<Target = [u8]>,
|
R: AsRef<[u8]>,
|
||||||
C: Cache<K, T> {
|
C: Cache<K, T> {
|
||||||
{
|
{
|
||||||
let read = cache.read();
|
let read = cache.read();
|
||||||
@ -208,31 +208,31 @@ pub trait Readable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Writable for DBTransaction {
|
impl Writable for DBTransaction {
|
||||||
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) where T: rlp::Encodable, R: Deref<Target = [u8]> {
|
fn write<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>, value: &T) where T: rlp::Encodable, R: AsRef<[u8]> {
|
||||||
self.put(col, &key.key(), &rlp::encode(value));
|
self.put(col, key.key().as_ref(), &rlp::encode(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) where T: rlp::Encodable, R: Deref<Target = [u8]> {
|
fn delete<T, R>(&mut self, col: Option<u32>, key: &Key<T, Target = R>) where T: rlp::Encodable, R: AsRef<[u8]> {
|
||||||
self.delete(col, &key.key());
|
self.delete(col, key.key().as_ref());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<KVDB: KeyValueDB + ?Sized> Readable for KVDB {
|
impl<KVDB: KeyValueDB + ?Sized> Readable for KVDB {
|
||||||
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T>
|
fn read<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> Option<T>
|
||||||
where T: rlp::Decodable, R: Deref<Target = [u8]> {
|
where T: rlp::Decodable, R: AsRef<[u8]> {
|
||||||
self.get(col, &key.key())
|
self.get(col, key.key().as_ref())
|
||||||
.expect(&format!("db get failed, key: {:?}", &key.key() as &[u8]))
|
.expect(&format!("db get failed, key: {:?}", key.key().as_ref()))
|
||||||
.map(|v| rlp::decode(&v).expect("decode db value failed") )
|
.map(|v| rlp::decode(&v).expect("decode db value failed") )
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool where R: Deref<Target = [u8]> {
|
fn exists<T, R>(&self, col: Option<u32>, key: &Key<T, Target = R>) -> bool where R: AsRef<[u8]> {
|
||||||
let result = self.get(col, &key.key());
|
let result = self.get(col, key.key().as_ref());
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(v) => v.is_some(),
|
Ok(v) => v.is_some(),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
panic!("db get failed, key: {:?}, err: {:?}", &key.key() as &[u8], err);
|
panic!("db get failed, key: {:?}, err: {:?}", key.key().as_ref(), err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
//! Blockchain DB extras.
|
//! Blockchain DB extras.
|
||||||
|
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::ops;
|
use std::convert::AsRef;
|
||||||
|
|
||||||
use common_types::BlockNumber;
|
use common_types::BlockNumber;
|
||||||
use common_types::engines::epoch::Transition as EpochTransition;
|
use common_types::engines::epoch::Transition as EpochTransition;
|
||||||
@ -49,19 +49,17 @@ pub enum ExtrasIndex {
|
|||||||
|
|
||||||
fn with_index(hash: &H256, i: ExtrasIndex) -> H264 {
|
fn with_index(hash: &H256, i: ExtrasIndex) -> H264 {
|
||||||
let mut result = H264::default();
|
let mut result = H264::default();
|
||||||
result[0] = i as u8;
|
result.as_bytes_mut()[0] = i as u8;
|
||||||
(*result)[1..].clone_from_slice(hash);
|
result.as_bytes_mut()[1..].clone_from_slice(hash.as_bytes());
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wrapper for block number used as a DB key.
|
/// Wrapper for block number used as a DB key.
|
||||||
pub struct BlockNumberKey([u8; 5]);
|
pub struct BlockNumberKey([u8; 5]);
|
||||||
|
|
||||||
impl ops::Deref for BlockNumberKey {
|
impl AsRef<[u8]> for BlockNumberKey {
|
||||||
type Target = [u8];
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
&self.0[..]
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
&self.0
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -123,10 +121,8 @@ pub const EPOCH_KEY_PREFIX: &'static [u8; DB_PREFIX_LEN] = &[
|
|||||||
/// Epoch transitions key
|
/// Epoch transitions key
|
||||||
pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]);
|
pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]);
|
||||||
|
|
||||||
impl ops::Deref for EpochTransitionsKey {
|
impl AsRef<[u8]> for EpochTransitionsKey {
|
||||||
type Target = [u8];
|
fn as_ref(&self) -> &[u8] { &self.0[..] }
|
||||||
|
|
||||||
fn deref(&self) -> &[u8] { &self.0[..] }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Key<EpochTransitions> for u64 {
|
impl Key<EpochTransitions> for u64 {
|
||||||
|
@ -6,15 +6,14 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
bit-set = "0.4"
|
bit-set = "0.4"
|
||||||
parity-bytes = "0.1"
|
parity-bytes = "0.1"
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
lazy_static = "1.0"
|
lazy_static = "1.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
vm = { path = "../vm" }
|
vm = { path = "../vm" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
memory-cache = { path = "../../util/memory-cache" }
|
memory-cache = { path = "../../util/memory-cache" }
|
||||||
num-bigint = "0.2"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
|
@ -15,7 +15,7 @@
|
|||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use std::cmp;
|
use std::cmp;
|
||||||
use ethereum_types::{U256, H256};
|
use ethereum_types::{BigEndianHash, U256};
|
||||||
use super::u256_to_address;
|
use super::u256_to_address;
|
||||||
|
|
||||||
use {evm, vm};
|
use {evm, vm};
|
||||||
@ -121,12 +121,12 @@ impl<Gas: evm::CostType> Gasometer<Gas> {
|
|||||||
Request::Gas(Gas::from(1))
|
Request::Gas(Gas::from(1))
|
||||||
},
|
},
|
||||||
instructions::SSTORE => {
|
instructions::SSTORE => {
|
||||||
let address = H256::from(stack.peek(0));
|
let address = BigEndianHash::from_uint(stack.peek(0));
|
||||||
let newval = stack.peek(1);
|
let newval = stack.peek(1);
|
||||||
let val = U256::from(&*ext.storage_at(&address)?);
|
let val = ext.storage_at(&address)?.into_uint();
|
||||||
|
|
||||||
let gas = if schedule.eip1283 {
|
let gas = if schedule.eip1283 {
|
||||||
let orig = U256::from(&*ext.initial_storage_at(&address)?);
|
let orig = ext.initial_storage_at(&address)?.into_uint();
|
||||||
calculate_eip1283_sstore_gas(schedule, &orig, &val, &newval)
|
calculate_eip1283_sstore_gas(schedule, &orig, &val, &newval)
|
||||||
} else {
|
} else {
|
||||||
if val.is_zero() && !newval.is_zero() {
|
if val.is_zero() && !newval.is_zero() {
|
||||||
|
@ -26,10 +26,11 @@ mod shared_cache;
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{cmp, mem};
|
use std::{cmp, mem};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::convert::TryFrom;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use ethereum_types::{U256, H256, Address};
|
use ethereum_types::{U256, U512, H256, Address, BigEndianHash};
|
||||||
use num_bigint::BigUint;
|
|
||||||
|
|
||||||
use vm::{
|
use vm::{
|
||||||
self, ActionParams, ParamsType, ActionValue, CallType, MessageCallResult,
|
self, ActionParams, ParamsType, ActionValue, CallType, MessageCallResult,
|
||||||
@ -62,17 +63,6 @@ const TWO_POW_96: U256 = U256([0, 0x100000000, 0, 0]); //0x1 00000000 00000000 0
|
|||||||
const TWO_POW_224: U256 = U256([0, 0, 0, 0x100000000]); //0x1 00000000 00000000 00000000 00000000 00000000 00000000 00000000
|
const TWO_POW_224: U256 = U256([0, 0, 0, 0x100000000]); //0x1 00000000 00000000 00000000 00000000 00000000 00000000 00000000
|
||||||
const TWO_POW_248: U256 = U256([0, 0, 0, 0x100000000000000]); //0x1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 000000
|
const TWO_POW_248: U256 = U256([0, 0, 0, 0x100000000000000]); //0x1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 000000
|
||||||
|
|
||||||
fn to_biguint(x: U256) -> BigUint {
|
|
||||||
let mut bytes = [0u8; 32];
|
|
||||||
x.to_little_endian(&mut bytes);
|
|
||||||
BigUint::from_bytes_le(&bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_biguint(x: BigUint) -> U256 {
|
|
||||||
let bytes = x.to_bytes_le();
|
|
||||||
U256::from_little_endian(&bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Abstraction over raw vector of Bytes. Easier state management of PC.
|
/// Abstraction over raw vector of Bytes. Easier state management of PC.
|
||||||
struct CodeReader {
|
struct CodeReader {
|
||||||
position: ProgramCounter,
|
position: ProgramCounter,
|
||||||
@ -520,7 +510,7 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
let init_size = self.stack.pop_back();
|
let init_size = self.stack.pop_back();
|
||||||
let address_scheme = match instruction {
|
let address_scheme = match instruction {
|
||||||
instructions::CREATE => CreateContractAddress::FromSenderAndNonce,
|
instructions::CREATE => CreateContractAddress::FromSenderAndNonce,
|
||||||
instructions::CREATE2 => CreateContractAddress::FromSenderSaltAndCodeHash(self.stack.pop_back().into()),
|
instructions::CREATE2 => CreateContractAddress::FromSenderSaltAndCodeHash(BigEndianHash::from_uint(&self.stack.pop_back())),
|
||||||
_ => unreachable!("instruction can only be CREATE/CREATE2 checked above; qed"),
|
_ => unreachable!("instruction can only be CREATE/CREATE2 checked above; qed"),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -677,7 +667,7 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
let size = self.stack.pop_back();
|
let size = self.stack.pop_back();
|
||||||
let topics = self.stack.pop_n(no_of_topics)
|
let topics = self.stack.pop_n(no_of_topics)
|
||||||
.iter()
|
.iter()
|
||||||
.map(H256::from)
|
.map(BigEndianHash::from_uint)
|
||||||
.collect();
|
.collect();
|
||||||
ext.log(topics, self.mem.read_slice(offset, size))?;
|
ext.log(topics, self.mem.read_slice(offset, size))?;
|
||||||
},
|
},
|
||||||
@ -714,21 +704,21 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
let offset = self.stack.pop_back();
|
let offset = self.stack.pop_back();
|
||||||
let size = self.stack.pop_back();
|
let size = self.stack.pop_back();
|
||||||
let k = keccak(self.mem.read_slice(offset, size));
|
let k = keccak(self.mem.read_slice(offset, size));
|
||||||
self.stack.push(U256::from(&*k));
|
self.stack.push(k.into_uint());
|
||||||
},
|
},
|
||||||
instructions::SLOAD => {
|
instructions::SLOAD => {
|
||||||
let key = H256::from(&self.stack.pop_back());
|
let key = BigEndianHash::from_uint(&self.stack.pop_back());
|
||||||
let word = U256::from(&*ext.storage_at(&key)?);
|
let word = ext.storage_at(&key)?.into_uint();
|
||||||
self.stack.push(word);
|
self.stack.push(word);
|
||||||
},
|
},
|
||||||
instructions::SSTORE => {
|
instructions::SSTORE => {
|
||||||
let address = H256::from(&self.stack.pop_back());
|
let address = BigEndianHash::from_uint(&self.stack.pop_back());
|
||||||
let val = self.stack.pop_back();
|
let val = self.stack.pop_back();
|
||||||
|
|
||||||
let current_val = U256::from(&*ext.storage_at(&address)?);
|
let current_val = ext.storage_at(&address)?.into_uint();
|
||||||
// Increase refund for clear
|
// Increase refund for clear
|
||||||
if ext.schedule().eip1283 {
|
if ext.schedule().eip1283 {
|
||||||
let original_val = U256::from(&*ext.initial_storage_at(&address)?);
|
let original_val = ext.initial_storage_at(&address)?.into_uint();
|
||||||
gasometer::handle_eip1283_sstore_clears_refund(ext, &original_val, ¤t_val, &val);
|
gasometer::handle_eip1283_sstore_clears_refund(ext, &original_val, ¤t_val, &val);
|
||||||
} else {
|
} else {
|
||||||
if !current_val.is_zero() && val.is_zero() {
|
if !current_val.is_zero() && val.is_zero() {
|
||||||
@ -736,7 +726,7 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
ext.add_sstore_refund(sstore_clears_schedule);
|
ext.add_sstore_refund(sstore_clears_schedule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ext.set_storage(address, H256::from(&val))?;
|
ext.set_storage(address, BigEndianHash::from_uint(&val))?;
|
||||||
},
|
},
|
||||||
instructions::PC => {
|
instructions::PC => {
|
||||||
self.stack.push(U256::from(self.reader.position - 1));
|
self.stack.push(U256::from(self.reader.position - 1));
|
||||||
@ -797,7 +787,7 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
instructions::EXTCODEHASH => {
|
instructions::EXTCODEHASH => {
|
||||||
let address = u256_to_address(&self.stack.pop_back());
|
let address = u256_to_address(&self.stack.pop_back());
|
||||||
let hash = ext.extcodehash(&address)?.unwrap_or_else(H256::zero);
|
let hash = ext.extcodehash(&address)?.unwrap_or_else(H256::zero);
|
||||||
self.stack.push(U256::from(hash));
|
self.stack.push(hash.into_uint());
|
||||||
},
|
},
|
||||||
instructions::CALLDATACOPY => {
|
instructions::CALLDATACOPY => {
|
||||||
Self::copy_data_to_memory(&mut self.mem, &mut self.stack, &self.params.data.as_ref().map_or_else(|| &[] as &[u8], |d| &*d as &[u8]));
|
Self::copy_data_to_memory(&mut self.mem, &mut self.stack, &self.params.data.as_ref().map_or_else(|| &[] as &[u8], |d| &*d as &[u8]));
|
||||||
@ -831,7 +821,7 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
instructions::BLOCKHASH => {
|
instructions::BLOCKHASH => {
|
||||||
let block_number = self.stack.pop_back();
|
let block_number = self.stack.pop_back();
|
||||||
let block_hash = ext.blockhash(&block_number);
|
let block_hash = ext.blockhash(&block_number);
|
||||||
self.stack.push(U256::from(&*block_hash));
|
self.stack.push(block_hash.into_uint());
|
||||||
},
|
},
|
||||||
instructions::COINBASE => {
|
instructions::COINBASE => {
|
||||||
self.stack.push(address_to_u256(ext.env_info().author.clone()));
|
self.stack.push(address_to_u256(ext.env_info().author.clone()));
|
||||||
@ -1021,12 +1011,12 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
let c = self.stack.pop_back();
|
let c = self.stack.pop_back();
|
||||||
|
|
||||||
self.stack.push(if !c.is_zero() {
|
self.stack.push(if !c.is_zero() {
|
||||||
let a_num = to_biguint(a);
|
let a_512 = U512::from(a);
|
||||||
let b_num = to_biguint(b);
|
let b_512 = U512::from(b);
|
||||||
let c_num = to_biguint(c);
|
let c_512 = U512::from(c);
|
||||||
let res = a_num + b_num;
|
let res = a_512 + b_512;
|
||||||
let x = res % c_num;
|
let x = res % c_512;
|
||||||
from_biguint(x)
|
U256::try_from(x).expect("U512 % U256 fits U256; qed")
|
||||||
} else {
|
} else {
|
||||||
U256::zero()
|
U256::zero()
|
||||||
});
|
});
|
||||||
@ -1037,12 +1027,12 @@ impl<Cost: CostType> Interpreter<Cost> {
|
|||||||
let c = self.stack.pop_back();
|
let c = self.stack.pop_back();
|
||||||
|
|
||||||
self.stack.push(if !c.is_zero() {
|
self.stack.push(if !c.is_zero() {
|
||||||
let a_num = to_biguint(a);
|
let a_512 = U512::from(a);
|
||||||
let b_num = to_biguint(b);
|
let b_512 = U512::from(b);
|
||||||
let c_num = to_biguint(c);
|
let c_512 = U512::from(c);
|
||||||
let res = a_num * b_num;
|
let res = a_512 * b_512;
|
||||||
let x = res % c_num;
|
let x = res % c_512;
|
||||||
from_biguint(x)
|
U256::try_from(x).expect("U512 % U256 fits U256; qed")
|
||||||
} else {
|
} else {
|
||||||
U256::zero()
|
U256::zero()
|
||||||
});
|
});
|
||||||
@ -1182,12 +1172,13 @@ fn set_sign(value: U256, sign: bool) -> U256 {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn u256_to_address(value: &U256) -> Address {
|
fn u256_to_address(value: &U256) -> Address {
|
||||||
Address::from(H256::from(value))
|
let addr: H256 = BigEndianHash::from_uint(value);
|
||||||
|
Address::from(addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn address_to_u256(value: Address) -> U256 {
|
fn address_to_u256(value: Address) -> U256 {
|
||||||
U256::from(&*H256::from(value))
|
H256::from(value).into_uint()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -1198,6 +1189,7 @@ mod tests {
|
|||||||
use factory::Factory;
|
use factory::Factory;
|
||||||
use vm::{self, Exec, ActionParams, ActionValue};
|
use vm::{self, Exec, ActionParams, ActionValue};
|
||||||
use vm::tests::{FakeExt, test_finalize};
|
use vm::tests::{FakeExt, test_finalize};
|
||||||
|
use ethereum_types::Address;
|
||||||
|
|
||||||
fn interpreter(params: ActionParams, ext: &vm::Ext) -> Box<Exec> {
|
fn interpreter(params: ActionParams, ext: &vm::Ext) -> Box<Exec> {
|
||||||
Factory::new(VMType::Interpreter, 1).create(params, ext.schedule(), ext.depth())
|
Factory::new(VMType::Interpreter, 1).create(params, ext.schedule(), ext.depth())
|
||||||
@ -1208,13 +1200,13 @@ mod tests {
|
|||||||
let code = "7feeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff006000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000620f120660406000601773945304eb96065b2a98b57a48a06ae28d285a71b56101f4f1600055".from_hex().unwrap();
|
let code = "7feeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff006000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000620f120660406000601773945304eb96065b2a98b57a48a06ae28d285a71b56101f4f1600055".from_hex().unwrap();
|
||||||
|
|
||||||
let mut params = ActionParams::default();
|
let mut params = ActionParams::default();
|
||||||
params.address = 5.into();
|
params.address = Address::from_low_u64_be(5);
|
||||||
params.gas = 300_000.into();
|
params.gas = 300_000.into();
|
||||||
params.gas_price = 1.into();
|
params.gas_price = 1.into();
|
||||||
params.value = ActionValue::Transfer(100_000.into());
|
params.value = ActionValue::Transfer(100_000.into());
|
||||||
params.code = Some(Arc::new(code));
|
params.code = Some(Arc::new(code));
|
||||||
let mut ext = FakeExt::new();
|
let mut ext = FakeExt::new();
|
||||||
ext.balances.insert(5.into(), 1_000_000_000.into());
|
ext.balances.insert(Address::from_low_u64_be(5), 1_000_000_000.into());
|
||||||
ext.tracing = true;
|
ext.tracing = true;
|
||||||
|
|
||||||
let gas_left = {
|
let gas_left = {
|
||||||
@ -1231,12 +1223,12 @@ mod tests {
|
|||||||
let code = "6001600160000360003e00".from_hex().unwrap();
|
let code = "6001600160000360003e00".from_hex().unwrap();
|
||||||
|
|
||||||
let mut params = ActionParams::default();
|
let mut params = ActionParams::default();
|
||||||
params.address = 5.into();
|
params.address = Address::from_low_u64_be(5);
|
||||||
params.gas = 300_000.into();
|
params.gas = 300_000.into();
|
||||||
params.gas_price = 1.into();
|
params.gas_price = 1.into();
|
||||||
params.code = Some(Arc::new(code));
|
params.code = Some(Arc::new(code));
|
||||||
let mut ext = FakeExt::new_byzantium();
|
let mut ext = FakeExt::new_byzantium();
|
||||||
ext.balances.insert(5.into(), 1_000_000_000.into());
|
ext.balances.insert(Address::from_low_u64_be(5), 1_000_000_000.into());
|
||||||
ext.tracing = true;
|
ext.tracing = true;
|
||||||
|
|
||||||
let err = {
|
let err = {
|
||||||
|
@ -24,7 +24,6 @@ extern crate vm;
|
|||||||
extern crate keccak_hash as hash;
|
extern crate keccak_hash as hash;
|
||||||
extern crate memory_cache;
|
extern crate memory_cache;
|
||||||
extern crate parity_bytes as bytes;
|
extern crate parity_bytes as bytes;
|
||||||
extern crate num_bigint;
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
|
@ -239,7 +239,7 @@ fn test_blockhash(factory: super::Factory) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(gas_left, U256::from(79_974));
|
assert_eq!(gas_left, U256::from(79_974));
|
||||||
assert_eq!(ext.store.get(&H256::new()).unwrap(), &blockhash);
|
assert_eq!(ext.store.get(&H256::zero()).unwrap(), &blockhash);
|
||||||
}
|
}
|
||||||
|
|
||||||
evm_test!{test_calldataload: test_calldataload_int}
|
evm_test!{test_calldataload: test_calldataload_int}
|
||||||
@ -726,8 +726,8 @@ evm_test!{test_calls: test_calls_int}
|
|||||||
fn test_calls(factory: super::Factory) {
|
fn test_calls(factory: super::Factory) {
|
||||||
let code = "600054602d57600160005560006000600060006050610998610100f160006000600060006050610998610100f25b".from_hex().unwrap();
|
let code = "600054602d57600160005560006000600060006050610998610100f160006000600060006050610998610100f25b".from_hex().unwrap();
|
||||||
|
|
||||||
let address = Address::from(0x155);
|
let address = Address::from_low_u64_be(0x155);
|
||||||
let code_address = Address::from(0x998);
|
let code_address = Address::from_low_u64_be(0x998);
|
||||||
let mut params = ActionParams::default();
|
let mut params = ActionParams::default();
|
||||||
params.gas = U256::from(150_000);
|
params.gas = U256::from(150_000);
|
||||||
params.code = Some(Arc::new(code));
|
params.code = Some(Arc::new(code));
|
||||||
@ -772,7 +772,7 @@ evm_test!{test_create_in_staticcall: test_create_in_staticcall_int}
|
|||||||
fn test_create_in_staticcall(factory: super::Factory) {
|
fn test_create_in_staticcall(factory: super::Factory) {
|
||||||
let code = "600060006064f000".from_hex().unwrap();
|
let code = "600060006064f000".from_hex().unwrap();
|
||||||
|
|
||||||
let address = Address::from(0x155);
|
let address = Address::from_low_u64_be(0x155);
|
||||||
let mut params = ActionParams::default();
|
let mut params = ActionParams::default();
|
||||||
params.gas = U256::from(100_000);
|
params.gas = U256::from(100_000);
|
||||||
params.code = Some(Arc::new(code));
|
params.code = Some(Arc::new(code));
|
||||||
@ -1066,5 +1066,5 @@ fn assert_set_contains<T : Debug + Eq + PartialEq + Hash>(set: &HashSet<T>, val:
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn assert_store(ext: &FakeExt, pos: u64, val: &str) {
|
fn assert_store(ext: &FakeExt, pos: u64, val: &str) {
|
||||||
assert_eq!(ext.store.get(&H256::from(pos)).unwrap(), &H256::from_str(val).unwrap());
|
assert_eq!(ext.store.get(&H256::from_low_u64_be(pos)).unwrap(), &H256::from_str(val).unwrap());
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ common-types = { path = "../types" }
|
|||||||
ethcore = { path = ".."}
|
ethcore = { path = ".."}
|
||||||
ethcore-db = { path = "../db" }
|
ethcore-db = { path = "../db" }
|
||||||
ethcore-blockchain = { path = "../blockchain" }
|
ethcore-blockchain = { path = "../blockchain" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
memory-db = "0.11.0"
|
memory-db = "0.11.0"
|
||||||
trie-db = "0.11.0"
|
trie-db = "0.11.0"
|
||||||
patricia-trie-ethereum = { path = "../../util/patricia-trie-ethereum" }
|
patricia-trie-ethereum = { path = "../../util/patricia-trie-ethereum" }
|
||||||
@ -25,18 +25,18 @@ heapsize = "0.4"
|
|||||||
vm = { path = "../vm" }
|
vm = { path = "../vm" }
|
||||||
fastmap = { path = "../../util/fastmap" }
|
fastmap = { path = "../../util/fastmap" }
|
||||||
failsafe = { version = "0.3.0", default-features = false, features = ["parking_lot_mutex"] }
|
failsafe = { version = "0.3.0", default-features = false, features = ["parking_lot_mutex"] }
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
rlp_derive = { path = "../../util/rlp-derive" }
|
rlp_derive = { path = "../../util/rlp-derive" }
|
||||||
smallvec = "0.6"
|
smallvec = "0.6"
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
rand = "0.4"
|
rand = "0.6"
|
||||||
itertools = "0.5"
|
itertools = "0.5"
|
||||||
bincode = "0.8.0"
|
bincode = "0.8.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
stats = { path = "../../util/stats" }
|
stats = { path = "../../util/stats" }
|
||||||
keccak-hash = "0.1"
|
keccak-hash = "0.2.0"
|
||||||
keccak-hasher = { path = "../../util/keccak-hasher" }
|
keccak-hasher = { path = "../../util/keccak-hasher" }
|
||||||
triehash-ethereum = { version = "0.2", path = "../../util/triehash-ethereum" }
|
triehash-ethereum = { version = "0.2", path = "../../util/triehash-ethereum" }
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
|
@ -104,7 +104,7 @@ pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB<KeccakHashe
|
|||||||
let last_num = start_number(cht_num + 1) - 1;
|
let last_num = start_number(cht_num + 1) - 1;
|
||||||
let mut id = BlockId::Number(last_num);
|
let mut id = BlockId::Number(last_num);
|
||||||
|
|
||||||
let mut root = H256::default();
|
let mut root = H256::zero();
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut t = TrieDBMut::new(&mut db, &mut root);
|
let mut t = TrieDBMut::new(&mut db, &mut root);
|
||||||
|
@ -154,8 +154,11 @@ fn pending_transition_key(block_hash: H256) -> H264 {
|
|||||||
|
|
||||||
let mut key = H264::default();
|
let mut key = H264::default();
|
||||||
|
|
||||||
key[0] = LEADING;
|
{
|
||||||
key.0[1..].copy_from_slice(&block_hash.0[..]);
|
let bytes = key.as_bytes_mut();
|
||||||
|
bytes[0] = LEADING;
|
||||||
|
bytes[1..].copy_from_slice(block_hash.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
key
|
key
|
||||||
}
|
}
|
||||||
@ -165,8 +168,11 @@ fn transition_key(block_hash: H256) -> H264 {
|
|||||||
|
|
||||||
let mut key = H264::default();
|
let mut key = H264::default();
|
||||||
|
|
||||||
key[0] = LEADING;
|
{
|
||||||
key.0[1..].copy_from_slice(&block_hash.0[..]);
|
let bytes = key.as_bytes_mut();
|
||||||
|
bytes[0] = LEADING;
|
||||||
|
bytes[1..].copy_from_slice(block_hash.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
key
|
key
|
||||||
}
|
}
|
||||||
@ -237,7 +243,7 @@ impl HeaderChain {
|
|||||||
for c in &entry.candidates {
|
for c in &entry.candidates {
|
||||||
let key = transition_key(c.hash);
|
let key = transition_key(c.hash);
|
||||||
|
|
||||||
if let Some(proof) = db.get(col, &*key)? {
|
if let Some(proof) = db.get(col, key.as_bytes())? {
|
||||||
live_epoch_proofs.insert(c.hash, EpochTransition {
|
live_epoch_proofs.insert(c.hash, EpochTransition {
|
||||||
block_hash: c.hash,
|
block_hash: c.hash,
|
||||||
block_number: cur_number,
|
block_number: cur_number,
|
||||||
@ -431,7 +437,7 @@ impl HeaderChain {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(transition) = transition {
|
if let Some(transition) = transition {
|
||||||
transaction.put(self.col, &*transition_key(hash), &transition.proof);
|
transaction.put(self.col, transition_key(hash).as_bytes(), &transition.proof);
|
||||||
self.live_epoch_proofs.write().insert(hash, transition);
|
self.live_epoch_proofs.write().insert(hash, transition);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -508,10 +514,10 @@ impl HeaderChain {
|
|||||||
for ancient in &era_entry.candidates {
|
for ancient in &era_entry.candidates {
|
||||||
let maybe_transition = live_epoch_proofs.remove(&ancient.hash);
|
let maybe_transition = live_epoch_proofs.remove(&ancient.hash);
|
||||||
if let Some(epoch_transition) = maybe_transition {
|
if let Some(epoch_transition) = maybe_transition {
|
||||||
transaction.delete(self.col, &*transition_key(ancient.hash));
|
transaction.delete(self.col, transition_key(ancient.hash).as_bytes());
|
||||||
|
|
||||||
if ancient.hash == era_entry.canonical_hash {
|
if ancient.hash == era_entry.canonical_hash {
|
||||||
last_canonical_transition = match self.db.get(self.col, &ancient.hash) {
|
last_canonical_transition = match self.db.get(self.col, ancient.hash.as_bytes()) {
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!(target: "chain", "Error reading from DB: {}\n
|
warn!(target: "chain", "Error reading from DB: {}\n
|
||||||
", e);
|
", e);
|
||||||
@ -526,7 +532,7 @@ impl HeaderChain {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction.delete(self.col, &ancient.hash);
|
transaction.delete(self.col, ancient.hash.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
let canon = &era_entry.candidates[0];
|
let canon = &era_entry.candidates[0];
|
||||||
@ -647,7 +653,7 @@ impl HeaderChain {
|
|||||||
match cache.block_header(&hash) {
|
match cache.block_header(&hash) {
|
||||||
Some(header) => Some(header),
|
Some(header) => Some(header),
|
||||||
None => {
|
None => {
|
||||||
match self.db.get(self.col, &hash) {
|
match self.db.get(self.col, hash.as_bytes()) {
|
||||||
Ok(db_value) => {
|
Ok(db_value) => {
|
||||||
db_value.map(|x| x.into_vec()).map(encoded::Header::new)
|
db_value.map(|x| x.into_vec()).map(encoded::Header::new)
|
||||||
.and_then(|header| {
|
.and_then(|header| {
|
||||||
@ -772,7 +778,7 @@ impl HeaderChain {
|
|||||||
|
|
||||||
/// Get block status.
|
/// Get block status.
|
||||||
pub fn status(&self, hash: &H256) -> BlockStatus {
|
pub fn status(&self, hash: &H256) -> BlockStatus {
|
||||||
if self.db.get(self.col, hash).ok().map_or(false, |x| x.is_some()) {
|
if self.db.get(self.col, hash.as_bytes()).ok().map_or(false, |x| x.is_some()) {
|
||||||
BlockStatus::InChain
|
BlockStatus::InChain
|
||||||
} else {
|
} else {
|
||||||
BlockStatus::Unknown
|
BlockStatus::Unknown
|
||||||
@ -782,13 +788,13 @@ impl HeaderChain {
|
|||||||
/// Insert a pending transition.
|
/// Insert a pending transition.
|
||||||
pub fn insert_pending_transition(&self, batch: &mut DBTransaction, hash: H256, t: &PendingEpochTransition) {
|
pub fn insert_pending_transition(&self, batch: &mut DBTransaction, hash: H256, t: &PendingEpochTransition) {
|
||||||
let key = pending_transition_key(hash);
|
let key = pending_transition_key(hash);
|
||||||
batch.put(self.col, &*key, &*::rlp::encode(t));
|
batch.put(self.col, key.as_bytes(), &*::rlp::encode(t));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get pending transition for a specific block hash.
|
/// Get pending transition for a specific block hash.
|
||||||
pub fn pending_transition(&self, hash: H256) -> Option<PendingEpochTransition> {
|
pub fn pending_transition(&self, hash: H256) -> Option<PendingEpochTransition> {
|
||||||
let key = pending_transition_key(hash);
|
let key = pending_transition_key(hash);
|
||||||
match self.db.get(self.col, &*key) {
|
match self.db.get(self.col, key.as_bytes()) {
|
||||||
Ok(db_fetch) => db_fetch.map(|bytes| ::rlp::decode(&bytes).expect("decoding value from db failed")),
|
Ok(db_fetch) => db_fetch.map(|bytes| ::rlp::decode(&bytes).expect("decoding value from db failed")),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!(target: "chain", "Error reading from database: {}", e);
|
warn!(target: "chain", "Error reading from database: {}", e);
|
||||||
|
@ -382,7 +382,7 @@ mod tests {
|
|||||||
protocol_version: 1,
|
protocol_version: 1,
|
||||||
network_id: 1,
|
network_id: 1,
|
||||||
head_td: U256::default(),
|
head_td: U256::default(),
|
||||||
head_hash: H256::default(),
|
head_hash: H256::zero(),
|
||||||
head_num: 10,
|
head_num: 10,
|
||||||
genesis_hash: H256::zero(),
|
genesis_hash: H256::zero(),
|
||||||
last_head: None,
|
last_head: None,
|
||||||
@ -417,7 +417,7 @@ mod tests {
|
|||||||
protocol_version: 1,
|
protocol_version: 1,
|
||||||
network_id: 1,
|
network_id: 1,
|
||||||
head_td: U256::default(),
|
head_td: U256::default(),
|
||||||
head_hash: H256::default(),
|
head_hash: H256::zero(),
|
||||||
head_num: 10,
|
head_num: 10,
|
||||||
genesis_hash: H256::zero(),
|
genesis_hash: H256::zero(),
|
||||||
last_head: None,
|
last_head: None,
|
||||||
@ -452,7 +452,7 @@ mod tests {
|
|||||||
protocol_version: 1,
|
protocol_version: 1,
|
||||||
network_id: 1,
|
network_id: 1,
|
||||||
head_td: U256::default(),
|
head_td: U256::default(),
|
||||||
head_hash: H256::default(),
|
head_hash: H256::zero(),
|
||||||
head_num: 10,
|
head_num: 10,
|
||||||
genesis_hash: H256::zero(),
|
genesis_hash: H256::zero(),
|
||||||
last_head: None,
|
last_head: None,
|
||||||
@ -550,7 +550,7 @@ mod tests {
|
|||||||
protocol_version: 1,
|
protocol_version: 1,
|
||||||
network_id: 1,
|
network_id: 1,
|
||||||
head_td: U256::default(),
|
head_td: U256::default(),
|
||||||
head_hash: H256::default(),
|
head_hash: H256::zero(),
|
||||||
head_num: 10,
|
head_num: 10,
|
||||||
genesis_hash: H256::zero(),
|
genesis_hash: H256::zero(),
|
||||||
last_head: None,
|
last_head: None,
|
||||||
|
@ -22,7 +22,7 @@ use common_types::encoded;
|
|||||||
use common_types::ids::BlockId;
|
use common_types::ids::BlockId;
|
||||||
use common_types::transaction::{Action, PendingTransaction};
|
use common_types::transaction::{Action, PendingTransaction};
|
||||||
use ethcore::client::{EachBlockWith, TestBlockChainClient};
|
use ethcore::client::{EachBlockWith, TestBlockChainClient};
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address, BigEndianHash};
|
||||||
use net::context::IoContext;
|
use net::context::IoContext;
|
||||||
use net::load_timer::MOVING_SAMPLE_SIZE;
|
use net::load_timer::MOVING_SAMPLE_SIZE;
|
||||||
use net::status::{Capabilities, Status};
|
use net::status::{Capabilities, Status};
|
||||||
@ -158,7 +158,7 @@ impl Provider for TestProvider {
|
|||||||
|
|
||||||
fn contract_code(&self, req: request::CompleteCodeRequest) -> Option<request::CodeResponse> {
|
fn contract_code(&self, req: request::CompleteCodeRequest) -> Option<request::CodeResponse> {
|
||||||
Some(CodeResponse {
|
Some(CodeResponse {
|
||||||
code: req.block_hash.iter().chain(req.code_hash.iter()).cloned().collect(),
|
code: req.block_hash.as_bytes().iter().chain(req.code_hash.as_bytes().iter()).cloned().collect(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -261,7 +261,7 @@ fn genesis_mismatch() {
|
|||||||
let (provider, proto) = setup(capabilities);
|
let (provider, proto) = setup(capabilities);
|
||||||
|
|
||||||
let mut status = status(provider.client.chain_info());
|
let mut status = status(provider.client.chain_info());
|
||||||
status.genesis_hash = H256::default();
|
status.genesis_hash = H256::zero();
|
||||||
|
|
||||||
let packet_body = write_handshake(&status, &capabilities, &proto);
|
let packet_body = write_handshake(&status, &capabilities, &proto);
|
||||||
|
|
||||||
@ -472,16 +472,16 @@ fn get_state_proofs() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let req_id = 112;
|
let req_id = 112;
|
||||||
let key1: H256 = U256::from(11223344).into();
|
let key1: H256 = BigEndianHash::from_uint(&U256::from(11223344));
|
||||||
let key2: H256 = U256::from(99988887).into();
|
let key2: H256 = BigEndianHash::from_uint(&U256::from(99988887));
|
||||||
|
|
||||||
let mut builder = Builder::default();
|
let mut builder = Builder::default();
|
||||||
builder.push(Request::Account(IncompleteAccountRequest {
|
builder.push(Request::Account(IncompleteAccountRequest {
|
||||||
block_hash: H256::default().into(),
|
block_hash: H256::zero().into(),
|
||||||
address_hash: key1.into(),
|
address_hash: key1.into(),
|
||||||
})).unwrap();
|
})).unwrap();
|
||||||
builder.push(Request::Storage(IncompleteStorageRequest {
|
builder.push(Request::Storage(IncompleteStorageRequest {
|
||||||
block_hash: H256::default().into(),
|
block_hash: H256::zero().into(),
|
||||||
address_hash: key1.into(),
|
address_hash: key1.into(),
|
||||||
key_hash: key2.into(),
|
key_hash: key2.into(),
|
||||||
})).unwrap();
|
})).unwrap();
|
||||||
@ -492,11 +492,11 @@ fn get_state_proofs() {
|
|||||||
let response = {
|
let response = {
|
||||||
let responses = vec![
|
let responses = vec![
|
||||||
Response::Account(provider.account_proof(CompleteAccountRequest {
|
Response::Account(provider.account_proof(CompleteAccountRequest {
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
address_hash: key1,
|
address_hash: key1,
|
||||||
}).unwrap()),
|
}).unwrap()),
|
||||||
Response::Storage(provider.storage_proof(CompleteStorageRequest {
|
Response::Storage(provider.storage_proof(CompleteStorageRequest {
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
address_hash: key1,
|
address_hash: key1,
|
||||||
key_hash: key2,
|
key_hash: key2,
|
||||||
}).unwrap()),
|
}).unwrap()),
|
||||||
@ -529,8 +529,8 @@ fn get_contract_code() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let req_id = 112;
|
let req_id = 112;
|
||||||
let key1: H256 = U256::from(11223344).into();
|
let key1: H256 = BigEndianHash::from_uint(&U256::from(11223344));
|
||||||
let key2: H256 = U256::from(99988887).into();
|
let key2: H256 = BigEndianHash::from_uint(&U256::from(99988887));
|
||||||
|
|
||||||
let request = Request::Code(IncompleteCodeRequest {
|
let request = Request::Code(IncompleteCodeRequest {
|
||||||
block_hash: key1.into(),
|
block_hash: key1.into(),
|
||||||
@ -541,7 +541,7 @@ fn get_contract_code() {
|
|||||||
let request_body = make_packet(req_id, &requests);
|
let request_body = make_packet(req_id, &requests);
|
||||||
let response = {
|
let response = {
|
||||||
let response = vec![Response::Code(CodeResponse {
|
let response = vec![Response::Code(CodeResponse {
|
||||||
code: key1.iter().chain(key2.iter()).cloned().collect(),
|
code: key1.as_bytes().iter().chain(key2.as_bytes().iter()).cloned().collect(),
|
||||||
})];
|
})];
|
||||||
|
|
||||||
let new_creds = *flow_params.limit() - flow_params.compute_cost_multi(requests.requests()).unwrap();
|
let new_creds = *flow_params.limit() - flow_params.compute_cost_multi(requests.requests()).unwrap();
|
||||||
@ -616,9 +616,9 @@ fn proof_of_execution() {
|
|||||||
|
|
||||||
let req_id = 112;
|
let req_id = 112;
|
||||||
let mut request = Request::Execution(request::IncompleteExecutionRequest {
|
let mut request = Request::Execution(request::IncompleteExecutionRequest {
|
||||||
block_hash: H256::default().into(),
|
block_hash: H256::zero().into(),
|
||||||
from: Address::default(),
|
from: Address::zero(),
|
||||||
action: Action::Call(Address::default()),
|
action: Action::Call(Address::zero()),
|
||||||
gas: 100.into(),
|
gas: 100.into(),
|
||||||
gas_price: 0.into(),
|
gas_price: 0.into(),
|
||||||
value: 0.into(),
|
value: 0.into(),
|
||||||
@ -755,7 +755,7 @@ fn get_transaction_index() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let req_id = 112;
|
let req_id = 112;
|
||||||
let key1: H256 = U256::from(11223344).into();
|
let key1: H256 = BigEndianHash::from_uint(&U256::from(11223344));
|
||||||
|
|
||||||
let request = Request::TransactionIndex(IncompleteTransactionIndexRequest {
|
let request = Request::TransactionIndex(IncompleteTransactionIndexRequest {
|
||||||
hash: key1.into(),
|
hash: key1.into(),
|
||||||
|
@ -983,7 +983,7 @@ impl Account {
|
|||||||
let mut db = journaldb::new_memory_db();
|
let mut db = journaldb::new_memory_db();
|
||||||
for node in proof { db.insert(&node[..]); }
|
for node in proof { db.insert(&node[..]); }
|
||||||
|
|
||||||
match TrieDB::new(&db, &state_root).and_then(|t| t.get(&keccak(&self.address)))? {
|
match TrieDB::new(&db, &state_root).and_then(|t| t.get(keccak(&self.address).as_bytes()))? {
|
||||||
Some(val) => {
|
Some(val) => {
|
||||||
let rlp = Rlp::new(&val);
|
let rlp = Rlp::new(&val);
|
||||||
Ok(Some(BasicAccount {
|
Ok(Some(BasicAccount {
|
||||||
@ -1162,7 +1162,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn check_header_with_ancestors() {
|
fn check_header_with_ancestors() {
|
||||||
let mut last_header_hash = H256::default();
|
let mut last_header_hash = H256::zero();
|
||||||
let mut headers = (0..11).map(|num| {
|
let mut headers = (0..11).map(|num| {
|
||||||
let mut header = Header::new();
|
let mut header = Header::new();
|
||||||
header.set_number(num);
|
header.set_number(num);
|
||||||
@ -1278,7 +1278,7 @@ mod tests {
|
|||||||
fn check_state_proof() {
|
fn check_state_proof() {
|
||||||
use rlp::RlpStream;
|
use rlp::RlpStream;
|
||||||
|
|
||||||
let mut root = H256::default();
|
let mut root = H256::zero();
|
||||||
let mut db = journaldb::new_memory_db();
|
let mut db = journaldb::new_memory_db();
|
||||||
let mut header = Header::new();
|
let mut header = Header::new();
|
||||||
header.set_number(123_456);
|
header.set_number(123_456);
|
||||||
@ -1298,17 +1298,17 @@ mod tests {
|
|||||||
let mut trie = SecTrieDBMut::new(&mut db, &mut root);
|
let mut trie = SecTrieDBMut::new(&mut db, &mut root);
|
||||||
for _ in 0..100 {
|
for _ in 0..100 {
|
||||||
let address = Address::random();
|
let address = Address::random();
|
||||||
trie.insert(&*address, &rand_acc()).unwrap();
|
trie.insert(address.as_bytes(), &rand_acc()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
trie.insert(&*addr, &rand_acc()).unwrap();
|
trie.insert(addr.as_bytes(), &rand_acc()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
let proof = {
|
let proof = {
|
||||||
let trie = SecTrieDB::new(&db, &root).unwrap();
|
let trie = SecTrieDB::new(&db, &root).unwrap();
|
||||||
let mut recorder = Recorder::new();
|
let mut recorder = Recorder::new();
|
||||||
|
|
||||||
trie.get_with(&*addr, &mut recorder).unwrap().unwrap();
|
trie.get_with(addr.as_bytes(), &mut recorder).unwrap().unwrap();
|
||||||
|
|
||||||
recorder.drain().into_iter().map(|r| r.data).collect::<Vec<_>>()
|
recorder.drain().into_iter().map(|r| r.data).collect::<Vec<_>>()
|
||||||
};
|
};
|
||||||
|
@ -117,9 +117,9 @@ fn dummy_status() -> Status {
|
|||||||
protocol_version: 1,
|
protocol_version: 1,
|
||||||
network_id: 999,
|
network_id: 999,
|
||||||
head_td: 1.into(),
|
head_td: 1.into(),
|
||||||
head_hash: H256::default(),
|
head_hash: H256::zero(),
|
||||||
head_num: 1359,
|
head_num: 1359,
|
||||||
genesis_hash: H256::default(),
|
genesis_hash: H256::zero(),
|
||||||
last_head: None,
|
last_head: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -138,7 +138,7 @@ fn detects_hangup() {
|
|||||||
let on_demand = Harness::create().service;
|
let on_demand = Harness::create().service;
|
||||||
let result = on_demand.request_raw(
|
let result = on_demand.request_raw(
|
||||||
&Context::NoOp,
|
&Context::NoOp,
|
||||||
vec![request::HeaderByHash(H256::default().into()).into()],
|
vec![request::HeaderByHash(H256::zero().into()).into()],
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(on_demand.pending.read().len(), 1);
|
assert_eq!(on_demand.pending.read().len(), 1);
|
||||||
@ -199,7 +199,7 @@ fn no_capabilities() {
|
|||||||
|
|
||||||
let _recv = harness.service.request_raw(
|
let _recv = harness.service.request_raw(
|
||||||
&Context::NoOp,
|
&Context::NoOp,
|
||||||
vec![request::HeaderByHash(H256::default().into()).into()]
|
vec![request::HeaderByHash(H256::zero().into()).into()]
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
assert_eq!(harness.service.pending.read().len(), 1);
|
assert_eq!(harness.service.pending.read().len(), 1);
|
||||||
@ -395,7 +395,7 @@ fn wrong_kind() {
|
|||||||
|
|
||||||
let _recv = harness.service.request_raw(
|
let _recv = harness.service.request_raw(
|
||||||
&Context::NoOp,
|
&Context::NoOp,
|
||||||
vec![request::HeaderByHash(H256::default().into()).into()]
|
vec![request::HeaderByHash(H256::zero().into()).into()]
|
||||||
).unwrap();
|
).unwrap();
|
||||||
|
|
||||||
assert_eq!(harness.service.pending.read().len(), 1);
|
assert_eq!(harness.service.pending.read().len(), 1);
|
||||||
|
@ -395,7 +395,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn queued_senders() {
|
fn queued_senders() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
let tx = Transaction::default().fake_sign(sender);
|
let tx = Transaction::default().fake_sign(sender);
|
||||||
|
|
||||||
@ -411,7 +411,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn next_nonce() {
|
fn next_nonce() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
for i in (0..5).chain(10..15) {
|
for i in (0..5).chain(10..15) {
|
||||||
@ -442,7 +442,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn current_to_future() {
|
fn current_to_future() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
for i in 5..10 {
|
for i in 5..10 {
|
||||||
@ -485,7 +485,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn conditional() {
|
fn conditional() {
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
|
|
||||||
for i in 0..5 {
|
for i in 0..5 {
|
||||||
let mut tx = Transaction::default();
|
let mut tx = Transaction::default();
|
||||||
@ -507,7 +507,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cull_from_future() {
|
fn cull_from_future() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
for i in (0..1).chain(3..10) {
|
for i in (0..1).chain(3..10) {
|
||||||
@ -527,7 +527,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn import_old() {
|
fn import_old() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
let mut tx_a = Transaction::default();
|
let mut tx_a = Transaction::default();
|
||||||
@ -544,7 +544,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn replace_is_removed() {
|
fn replace_is_removed() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
let tx_b: PendingTransaction = Transaction::default().fake_sign(sender).into();
|
let tx_b: PendingTransaction = Transaction::default().fake_sign(sender).into();
|
||||||
@ -564,7 +564,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn future_transactions() {
|
fn future_transactions() {
|
||||||
let sender = Address::default();
|
let sender = Address::zero();
|
||||||
let mut txq = TransactionQueue::default();
|
let mut txq = TransactionQueue::default();
|
||||||
|
|
||||||
for i in (0..1).chain(3..10) {
|
for i in (0..1).chain(3..10) {
|
||||||
|
@ -220,7 +220,7 @@ mod tests {
|
|||||||
num: 100.into(),
|
num: 100.into(),
|
||||||
})).unwrap();
|
})).unwrap();
|
||||||
builder.push(Request::Receipts(IncompleteReceiptsRequest {
|
builder.push(Request::Receipts(IncompleteReceiptsRequest {
|
||||||
hash: H256::default().into(),
|
hash: H256::zero().into(),
|
||||||
})).unwrap();
|
})).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -267,7 +267,7 @@ mod tests {
|
|||||||
})).unwrap();
|
})).unwrap();
|
||||||
|
|
||||||
let mut batch = builder.build();
|
let mut batch = builder.build();
|
||||||
batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(42.into())));
|
batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(H256::from_low_u64_be(42))));
|
||||||
|
|
||||||
assert!(batch.next_complete().is_some());
|
assert!(batch.next_complete().is_some());
|
||||||
batch.answered += 1;
|
batch.answered += 1;
|
||||||
@ -289,7 +289,7 @@ mod tests {
|
|||||||
assert!(batch.next_complete().is_some());
|
assert!(batch.next_complete().is_some());
|
||||||
let hdr_proof_res = header_proof::Response {
|
let hdr_proof_res = header_proof::Response {
|
||||||
proof: vec![],
|
proof: vec![],
|
||||||
hash: 12.into(),
|
hash: H256::from_low_u64_be(12),
|
||||||
td: 21.into(),
|
td: 21.into(),
|
||||||
};
|
};
|
||||||
batch.supply_response_unchecked(&hdr_proof_res);
|
batch.supply_response_unchecked(&hdr_proof_res);
|
||||||
@ -308,7 +308,7 @@ mod tests {
|
|||||||
})).unwrap();
|
})).unwrap();
|
||||||
|
|
||||||
let mut batch = builder.build();
|
let mut batch = builder.build();
|
||||||
batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(42.into())));
|
batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(H256::from_low_u64_be(42))));
|
||||||
|
|
||||||
assert!(batch.next_complete().is_some());
|
assert!(batch.next_complete().is_some());
|
||||||
batch.answered += 1;
|
batch.answered += 1;
|
||||||
|
@ -1648,7 +1648,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hash_or_number_roundtrip() {
|
fn hash_or_number_roundtrip() {
|
||||||
let hash = HashOrNumber::Hash(H256::default());
|
let hash = HashOrNumber::Hash(H256::zero());
|
||||||
let number = HashOrNumber::Number(5);
|
let number = HashOrNumber::Number(5);
|
||||||
|
|
||||||
check_roundtrip(hash);
|
check_roundtrip(hash);
|
||||||
@ -1808,7 +1808,7 @@ mod tests {
|
|||||||
let full_req = Request::Storage(req.clone());
|
let full_req = Request::Storage(req.clone());
|
||||||
let res = StorageResponse {
|
let res = StorageResponse {
|
||||||
proof: vec![vec![1, 2, 3], vec![4, 5, 6]],
|
proof: vec![vec![1, 2, 3], vec![4, 5, 6]],
|
||||||
value: H256::default(),
|
value: H256::zero(),
|
||||||
};
|
};
|
||||||
let full_res = Response::Storage(res.clone());
|
let full_res = Response::Storage(res.clone());
|
||||||
|
|
||||||
@ -1909,7 +1909,7 @@ mod tests {
|
|||||||
code_hash: Default::default(),
|
code_hash: Default::default(),
|
||||||
storage_root: Default::default()
|
storage_root: Default::default()
|
||||||
}),
|
}),
|
||||||
Response::Storage(StorageResponse { proof: vec![], value: H256::default() }),
|
Response::Storage(StorageResponse { proof: vec![], value: H256::zero() }),
|
||||||
Response::Code(CodeResponse { code: vec![1, 2, 3, 4, 5] }),
|
Response::Code(CodeResponse { code: vec![1, 2, 3, 4, 5] }),
|
||||||
Response::Execution(ExecutionResponse { items: vec![] }),
|
Response::Execution(ExecutionResponse { items: vec![] }),
|
||||||
];
|
];
|
||||||
|
@ -10,12 +10,12 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
ethcore = { path = ".."}
|
ethcore = { path = ".."}
|
||||||
ethcore-network = { path = "../../util/network" }
|
ethcore-network = { path = "../../util/network" }
|
||||||
ethcore-network-devp2p = { path = "../../util/network-devp2p" }
|
ethcore-network-devp2p = { path = "../../util/network-devp2p" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
parking_lot = "0.7"
|
parking_lot = "0.7"
|
||||||
ethabi = "6.0"
|
ethabi = "8.0"
|
||||||
ethabi-derive = "6.0"
|
ethabi-derive = "8.0"
|
||||||
ethabi-contract = "6.0"
|
ethabi-contract = "8.0"
|
||||||
lru-cache = "0.1"
|
lru-cache = "0.1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
@ -135,11 +135,13 @@ mod test {
|
|||||||
use io::IoChannel;
|
use io::IoChannel;
|
||||||
use super::NodeFilter;
|
use super::NodeFilter;
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
use ethereum_types::Address;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
/// Contract code: https://gist.github.com/arkpar/467dbcc73cbb85b0997a7a10ffa0695f
|
/// Contract code: https://gist.github.com/arkpar/467dbcc73cbb85b0997a7a10ffa0695f
|
||||||
#[test]
|
#[test]
|
||||||
fn node_filter() {
|
fn node_filter() {
|
||||||
let contract_addr = "0000000000000000000000000000000000000005".into();
|
let contract_addr = Address::from_str("0000000000000000000000000000000000000005").unwrap();
|
||||||
let data = include_bytes!("../res/node_filter.json");
|
let data = include_bytes!("../res/node_filter.json");
|
||||||
let tempdir = TempDir::new("").unwrap();
|
let tempdir = TempDir::new("").unwrap();
|
||||||
let spec = Spec::load(&tempdir.path(), &data[..]).unwrap();
|
let spec = Spec::load(&tempdir.path(), &data[..]).unwrap();
|
||||||
@ -153,11 +155,11 @@ mod test {
|
|||||||
IoChannel::disconnected(),
|
IoChannel::disconnected(),
|
||||||
).unwrap();
|
).unwrap();
|
||||||
let filter = NodeFilter::new(Arc::downgrade(&client) as Weak<BlockChainClient>, contract_addr);
|
let filter = NodeFilter::new(Arc::downgrade(&client) as Weak<BlockChainClient>, contract_addr);
|
||||||
let self1: NodeId = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002".into();
|
let self1 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002").unwrap();
|
||||||
let self2: NodeId = "00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003".into();
|
let self2 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003").unwrap();
|
||||||
let node1: NodeId = "00000000000000000000000000000000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000012".into();
|
let node1 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000012").unwrap();
|
||||||
let node2: NodeId = "00000000000000000000000000000000000000000000000000000000000000210000000000000000000000000000000000000000000000000000000000000022".into();
|
let node2 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000210000000000000000000000000000000000000000000000000000000000000022").unwrap();
|
||||||
let nodex: NodeId = "77000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into();
|
let nodex = NodeId::from_str("77000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap();
|
||||||
|
|
||||||
assert!(filter.connection_allowed(&self1, &node1, ConnectionDirection::Inbound));
|
assert!(filter.connection_allowed(&self1, &node1, ConnectionDirection::Inbound));
|
||||||
assert!(filter.connection_allowed(&self1, &nodex, ConnectionDirection::Inbound));
|
assert!(filter.connection_allowed(&self1, &nodex, ConnectionDirection::Inbound));
|
||||||
|
@ -8,20 +8,20 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
common-types = { path = "../types" }
|
common-types = { path = "../types" }
|
||||||
derive_more = "0.14.0"
|
derive_more = "0.14.0"
|
||||||
ethabi = "6.0"
|
ethabi = "8.0"
|
||||||
ethabi-contract = "6.0"
|
ethabi-contract = "8.0"
|
||||||
ethabi-derive = "6.0"
|
ethabi-derive = "8.0"
|
||||||
ethcore = { path = ".." }
|
ethcore = { path = ".." }
|
||||||
ethcore-call-contract = { path = "../call-contract" }
|
ethcore-call-contract = { path = "../call-contract" }
|
||||||
ethcore-io = { path = "../../util/io" }
|
ethcore-io = { path = "../../util/io" }
|
||||||
ethcore-miner = { path = "../../miner" }
|
ethcore-miner = { path = "../../miner" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
ethjson = { path = "../../json" }
|
ethjson = { path = "../../json" }
|
||||||
ethkey = { path = "../../accounts/ethkey" }
|
ethkey = { path = "../../accounts/ethkey" }
|
||||||
fetch = { path = "../../util/fetch" }
|
fetch = { path = "../../util/fetch" }
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
keccak-hash = "0.1.2"
|
keccak-hash = "0.2.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
parity-bytes = "0.1"
|
parity-bytes = "0.1"
|
||||||
parity-crypto = "0.4.0"
|
parity-crypto = "0.4.0"
|
||||||
@ -29,7 +29,7 @@ parking_lot = "0.7"
|
|||||||
trie-db = "0.11.0"
|
trie-db = "0.11.0"
|
||||||
patricia-trie-ethereum = { path = "../../util/patricia-trie-ethereum" }
|
patricia-trie-ethereum = { path = "../../util/patricia-trie-ethereum" }
|
||||||
rand = "0.3"
|
rand = "0.3"
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = "0.4.0"
|
||||||
rlp_derive = { path = "../../util/rlp-derive" }
|
rlp_derive = { path = "../../util/rlp-derive" }
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
|
@ -114,7 +114,7 @@ impl SecretStoreEncryptor {
|
|||||||
let requester = self.config.key_server_account.ok_or_else(|| Error::KeyServerAccountNotSet)?;
|
let requester = self.config.key_server_account.ok_or_else(|| Error::KeyServerAccountNotSet)?;
|
||||||
|
|
||||||
// key id in SS is H256 && we have H160 here => expand with assitional zeros
|
// key id in SS is H256 && we have H160 here => expand with assitional zeros
|
||||||
let contract_address_extended: H256 = contract_address.into();
|
let contract_address_extended: H256 = (*contract_address).into();
|
||||||
let base_url = self.config.base_url.clone().ok_or_else(|| Error::KeyServerNotSet)?;
|
let base_url = self.config.base_url.clone().ok_or_else(|| Error::KeyServerNotSet)?;
|
||||||
|
|
||||||
// prepare request url
|
// prepare request url
|
||||||
@ -156,7 +156,7 @@ impl SecretStoreEncryptor {
|
|||||||
let decrypted_key = Public::from_slice(&decrypted_bytes);
|
let decrypted_key = Public::from_slice(&decrypted_bytes);
|
||||||
|
|
||||||
// and now take x coordinate of Public as a key
|
// and now take x coordinate of Public as a key
|
||||||
let key: Bytes = (*decrypted_key)[..INIT_VEC_LEN].into();
|
let key: Bytes = decrypted_key.as_bytes()[..INIT_VEC_LEN].into();
|
||||||
|
|
||||||
// cache the key in the session and clear expired sessions
|
// cache the key in the session and clear expired sessions
|
||||||
self.sessions.lock().insert(*contract_address, EncryptionSession{
|
self.sessions.lock().insert(*contract_address, EncryptionSession{
|
||||||
@ -212,11 +212,11 @@ impl Encryptor for SecretStoreEncryptor {
|
|||||||
}?;
|
}?;
|
||||||
|
|
||||||
// encrypt data
|
// encrypt data
|
||||||
let mut cypher = Vec::with_capacity(plain_data.len() + initialisation_vector.len());
|
let mut cypher = Vec::with_capacity(plain_data.len() + initialisation_vector.as_bytes().len());
|
||||||
cypher.extend(repeat(0).take(plain_data.len()));
|
cypher.extend(repeat(0).take(plain_data.len()));
|
||||||
crypto::aes::encrypt_128_ctr(&key, initialisation_vector, plain_data, &mut cypher)
|
crypto::aes::encrypt_128_ctr(&key, initialisation_vector.as_bytes(), plain_data, &mut cypher)
|
||||||
.map_err(|e| Error::Encrypt(e.to_string()))?;
|
.map_err(|e| Error::Encrypt(e.to_string()))?;
|
||||||
cypher.extend_from_slice(&initialisation_vector);
|
cypher.extend_from_slice(&initialisation_vector.as_bytes());
|
||||||
|
|
||||||
Ok(cypher)
|
Ok(cypher)
|
||||||
}
|
}
|
||||||
|
@ -29,15 +29,15 @@ use_contract!(keys_acl_contract, "res/keys_acl.json");
|
|||||||
|
|
||||||
/// Returns the address (of the contract), that corresponds to the key
|
/// Returns the address (of the contract), that corresponds to the key
|
||||||
pub fn key_to_address(key: &H256) -> Address {
|
pub fn key_to_address(key: &H256) -> Address {
|
||||||
Address::from_slice(&key.to_vec()[..10])
|
Address::from_slice(&key.as_bytes()[..10])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the key from the key server associated with the contract
|
/// Returns the key from the key server associated with the contract
|
||||||
pub fn address_to_key(contract_address: &Address) -> H256 {
|
pub fn address_to_key(contract_address: &Address) -> H256 {
|
||||||
// Current solution uses contract address extended with 0 as id
|
// Current solution uses contract address extended with 0 as id
|
||||||
let contract_address_extended: H256 = contract_address.into();
|
let contract_address_extended: H256 = (*contract_address).into();
|
||||||
|
|
||||||
H256::from_slice(&contract_address_extended)
|
H256::from_slice(contract_address_extended.as_bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Trait for keys server keys provider.
|
/// Trait for keys server keys provider.
|
||||||
@ -118,7 +118,7 @@ impl Default for StoringKeyProvider {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
StoringKeyProvider {
|
StoringKeyProvider {
|
||||||
available_keys: RwLock::new(None),
|
available_keys: RwLock::new(None),
|
||||||
key_server_account: Some(Address::default()),
|
key_server_account: Some(Address::zero()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -170,4 +170,4 @@ mod tests {
|
|||||||
keys_data.update_acl_contract();
|
keys_data.update_acl_contract();
|
||||||
assert_eq!(keys_data.keys_acl_contract.read().unwrap(), key.address());
|
assert_eq!(keys_data.keys_acl_contract.read().unwrap(), key.address());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -80,7 +80,7 @@ pub use log::{Logging, TransactionLog, ValidatorLog, PrivateTxStatus, FileLogsSe
|
|||||||
|
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
use std::collections::{HashMap, HashSet, BTreeMap};
|
use std::collections::{HashMap, HashSet, BTreeMap};
|
||||||
use ethereum_types::{H128, H256, U256, Address};
|
use ethereum_types::{H128, H256, U256, Address, BigEndianHash};
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use rlp::*;
|
use rlp::*;
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
@ -285,9 +285,10 @@ impl Provider {
|
|||||||
/// Calculate hash from united private state and contract nonce
|
/// Calculate hash from united private state and contract nonce
|
||||||
pub fn calculate_state_hash(&self, state: &Bytes, nonce: U256) -> H256 {
|
pub fn calculate_state_hash(&self, state: &Bytes, nonce: U256) -> H256 {
|
||||||
let state_hash = keccak(state);
|
let state_hash = keccak(state);
|
||||||
|
let nonce_h256: H256 = BigEndianHash::from_uint(&nonce);
|
||||||
let mut state_buf = [0u8; 64];
|
let mut state_buf = [0u8; 64];
|
||||||
state_buf[..32].clone_from_slice(&state_hash);
|
state_buf[..32].clone_from_slice(state_hash.as_bytes());
|
||||||
state_buf[32..].clone_from_slice(&H256::from(nonce));
|
state_buf[32..].clone_from_slice(nonce_h256.as_bytes());
|
||||||
keccak(&state_buf.as_ref())
|
keccak(&state_buf.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -481,13 +482,13 @@ impl Provider {
|
|||||||
|
|
||||||
fn iv_from_transaction(transaction: &SignedTransaction) -> H128 {
|
fn iv_from_transaction(transaction: &SignedTransaction) -> H128 {
|
||||||
let nonce = keccak(&transaction.nonce.rlp_bytes());
|
let nonce = keccak(&transaction.nonce.rlp_bytes());
|
||||||
let (iv, _) = nonce.split_at(INIT_VEC_LEN);
|
let (iv, _) = nonce.as_bytes().split_at(INIT_VEC_LEN);
|
||||||
H128::from_slice(iv)
|
H128::from_slice(iv)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn iv_from_address(contract_address: &Address) -> H128 {
|
fn iv_from_address(contract_address: &Address) -> H128 {
|
||||||
let address = keccak(&contract_address.rlp_bytes());
|
let address = keccak(&contract_address.rlp_bytes());
|
||||||
let (iv, _) = address.split_at(INIT_VEC_LEN);
|
let (iv, _) = address.as_bytes().split_at(INIT_VEC_LEN);
|
||||||
H128::from_slice(iv)
|
H128::from_slice(iv)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -536,8 +537,8 @@ impl Provider {
|
|||||||
// Sort the storage to guarantee the order for all parties
|
// Sort the storage to guarantee the order for all parties
|
||||||
let sorted_storage: BTreeMap<&H256, &H256> = storage.iter().collect();
|
let sorted_storage: BTreeMap<&H256, &H256> = storage.iter().collect();
|
||||||
for (key, value) in sorted_storage {
|
for (key, value) in sorted_storage {
|
||||||
raw.extend_from_slice(key);
|
raw.extend_from_slice(key.as_bytes());
|
||||||
raw.extend_from_slice(value);
|
raw.extend_from_slice(value.as_bytes());
|
||||||
};
|
};
|
||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
@ -621,8 +622,8 @@ impl Provider {
|
|||||||
v[31] = s.v();
|
v[31] = s.v();
|
||||||
v
|
v
|
||||||
}).collect::<Vec<[u8; 32]>>(),
|
}).collect::<Vec<[u8; 32]>>(),
|
||||||
signatures.iter().map(|s| s.r()).collect::<Vec<&[u8]>>(),
|
signatures.iter().map(|s| H256::from_slice(s.r())).collect::<Vec<H256>>(),
|
||||||
signatures.iter().map(|s| s.s()).collect::<Vec<&[u8]>>()
|
signatures.iter().map(|s| H256::from_slice(s.s())).collect::<Vec<H256>>(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -292,10 +292,11 @@ impl Drop for Logging {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use serde_json;
|
use serde_json;
|
||||||
use error::Error;
|
use error::Error;
|
||||||
use ethereum_types::H256;
|
use ethereum_types::{H256, Address};
|
||||||
use std::collections::{HashMap, BTreeMap};
|
use std::collections::{HashMap, BTreeMap};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{SystemTime, Duration};
|
use std::time::{SystemTime, Duration};
|
||||||
|
use std::str::FromStr;
|
||||||
use types::transaction::Transaction;
|
use types::transaction::Transaction;
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
use super::{TransactionLog, Logging, PrivateTxStatus, LogsSerializer, ValidatorLog};
|
use super::{TransactionLog, Logging, PrivateTxStatus, LogsSerializer, ValidatorLog};
|
||||||
@ -360,8 +361,8 @@ mod tests {
|
|||||||
let logger = Logging::new(Arc::new(StringLogSerializer::new("".into())));
|
let logger = Logging::new(Arc::new(StringLogSerializer::new("".into())));
|
||||||
let private_tx = Transaction::default();
|
let private_tx = Transaction::default();
|
||||||
let hash = private_tx.hash(None);
|
let hash = private_tx.hash(None);
|
||||||
logger.private_tx_created(&hash, &vec!["0x82a978b3f5962a5b0957d9ee9eef472ee55b42f1".into()]);
|
logger.private_tx_created(&hash, &vec![Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap()]);
|
||||||
logger.signature_added(&hash, &"0x82a978b3f5962a5b0957d9ee9eef472ee55b42f1".into());
|
logger.signature_added(&hash, &Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap());
|
||||||
logger.tx_deployed(&hash, &hash);
|
logger.tx_deployed(&hash, &hash);
|
||||||
let tx_log = logger.tx_log(&hash).unwrap();
|
let tx_log = logger.tx_log(&hash).unwrap();
|
||||||
assert_eq!(tx_log.status, PrivateTxStatus::Deployed);
|
assert_eq!(tx_log.status, PrivateTxStatus::Deployed);
|
||||||
@ -371,38 +372,38 @@ mod tests {
|
|||||||
fn serialization() {
|
fn serialization() {
|
||||||
let current_timestamp = SystemTime::now();
|
let current_timestamp = SystemTime::now();
|
||||||
let initial_validator_log = ValidatorLog {
|
let initial_validator_log = ValidatorLog {
|
||||||
account: "0x82a978b3f5962a5b0957d9ee9eef472ee55b42f1".into(),
|
account: Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap(),
|
||||||
validation_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(1)).unwrap()),
|
validation_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(1)).unwrap()),
|
||||||
};
|
};
|
||||||
let initial_log = TransactionLog {
|
let initial_log = TransactionLog {
|
||||||
tx_hash: "0x64f648ca7ae7f4138014f860ae56164d8d5732969b1cea54d8be9d144d8aa6f6".into(),
|
tx_hash: H256::from_str("64f648ca7ae7f4138014f860ae56164d8d5732969b1cea54d8be9d144d8aa6f6").unwrap(),
|
||||||
status: PrivateTxStatus::Deployed,
|
status: PrivateTxStatus::Deployed,
|
||||||
creation_timestamp: current_timestamp,
|
creation_timestamp: current_timestamp,
|
||||||
validators: vec![initial_validator_log],
|
validators: vec![initial_validator_log],
|
||||||
deployment_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(2)).unwrap()),
|
deployment_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(2)).unwrap()),
|
||||||
public_tx_hash: Some("0x69b9c691ede7993effbcc88911c309af1c82be67b04b3882dd446b808ae146da".into()),
|
public_tx_hash: Some(H256::from_str("69b9c691ede7993effbcc88911c309af1c82be67b04b3882dd446b808ae146da").unwrap()),
|
||||||
};
|
};
|
||||||
let serializer = Arc::new(StringLogSerializer::new(serde_json::to_string(&vec![initial_log.clone()]).unwrap()));
|
let serializer = Arc::new(StringLogSerializer::new(serde_json::to_string(&vec![initial_log.clone()]).unwrap()));
|
||||||
let logger = Logging::new(serializer.clone());
|
let logger = Logging::new(serializer.clone());
|
||||||
let hash: H256 = "0x63c715e88f7291e66069302f6fcbb4f28a19ef5d7cbd1832d0c01e221c0061c6".into();
|
let hash = H256::from_str("63c715e88f7291e66069302f6fcbb4f28a19ef5d7cbd1832d0c01e221c0061c6").unwrap();
|
||||||
logger.private_tx_created(&hash, &vec!["0x7ffbe3512782069be388f41be4d8eb350672d3a5".into()]);
|
logger.private_tx_created(&hash, &vec![Address::from_str("7ffbe3512782069be388f41be4d8eb350672d3a5").unwrap()]);
|
||||||
logger.signature_added(&hash, &"0x7ffbe3512782069be388f41be4d8eb350672d3a5".into());
|
logger.signature_added(&hash, &Address::from_str("7ffbe3512782069be388f41be4d8eb350672d3a5").unwrap());
|
||||||
logger.tx_deployed(&hash, &"0xde2209a8635b9cab9eceb67928b217c70ab53f6498e5144492ec01e6f43547d7".into());
|
logger.tx_deployed(&hash, &H256::from_str("de2209a8635b9cab9eceb67928b217c70ab53f6498e5144492ec01e6f43547d7").unwrap());
|
||||||
drop(logger);
|
drop(logger);
|
||||||
let added_validator_log = ValidatorLog {
|
let added_validator_log = ValidatorLog {
|
||||||
account: "0x7ffbe3512782069be388f41be4d8eb350672d3a5".into(),
|
account: Address::from_str("7ffbe3512782069be388f41be4d8eb350672d3a5").unwrap(),
|
||||||
validation_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(7)).unwrap()),
|
validation_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(7)).unwrap()),
|
||||||
};
|
};
|
||||||
let added_log = TransactionLog {
|
let added_log = TransactionLog {
|
||||||
tx_hash: "0x63c715e88f7291e66069302f6fcbb4f28a19ef5d7cbd1832d0c01e221c0061c6".into(),
|
tx_hash: H256::from_str("63c715e88f7291e66069302f6fcbb4f28a19ef5d7cbd1832d0c01e221c0061c6").unwrap(),
|
||||||
status: PrivateTxStatus::Deployed,
|
status: PrivateTxStatus::Deployed,
|
||||||
creation_timestamp: current_timestamp.checked_add(Duration::from_secs(6)).unwrap(),
|
creation_timestamp: current_timestamp.checked_add(Duration::from_secs(6)).unwrap(),
|
||||||
validators: vec![added_validator_log],
|
validators: vec![added_validator_log],
|
||||||
deployment_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(8)).unwrap()),
|
deployment_timestamp: Some(current_timestamp.checked_add(Duration::from_secs(8)).unwrap()),
|
||||||
public_tx_hash: Some("0xde2209a8635b9cab9eceb67928b217c70ab53f6498e5144492ec01e6f43547d7".into()),
|
public_tx_hash: Some(H256::from_str("de2209a8635b9cab9eceb67928b217c70ab53f6498e5144492ec01e6f43547d7").unwrap()),
|
||||||
};
|
};
|
||||||
let should_be_final = vec![added_log, initial_log];
|
let should_be_final = vec![added_log, initial_log];
|
||||||
let deserialized_logs: Vec<TransactionLog> = serde_json::from_str(&serializer.log()).unwrap();
|
let deserialized_logs: Vec<TransactionLog> = serde_json::from_str(&serializer.log()).unwrap();
|
||||||
assert_eq!(deserialized_logs, should_be_final);
|
assert_eq!(deserialized_logs, should_be_final);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address, BigEndianHash};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use rlp::Encodable;
|
use rlp::Encodable;
|
||||||
@ -38,7 +38,7 @@ impl PrivateTransaction {
|
|||||||
PrivateTransaction {
|
PrivateTransaction {
|
||||||
encrypted,
|
encrypted,
|
||||||
contract,
|
contract,
|
||||||
hash: 0.into(),
|
hash: H256::zero(),
|
||||||
}.compute_hash()
|
}.compute_hash()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -87,7 +87,7 @@ impl SignedPrivateTransaction {
|
|||||||
r: sig.r().into(),
|
r: sig.r().into(),
|
||||||
s: sig.s().into(),
|
s: sig.s().into(),
|
||||||
v: add_chain_replay_protection(sig.v() as u64, chain_id),
|
v: add_chain_replay_protection(sig.v() as u64, chain_id),
|
||||||
hash: 0.into(),
|
hash: H256::zero(),
|
||||||
}.compute_hash()
|
}.compute_hash()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,7 +100,11 @@ impl SignedPrivateTransaction {
|
|||||||
|
|
||||||
/// Construct a signature object from the sig.
|
/// Construct a signature object from the sig.
|
||||||
pub fn signature(&self) -> Signature {
|
pub fn signature(&self) -> Signature {
|
||||||
Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v())
|
Signature::from_rsv(
|
||||||
|
&BigEndianHash::from_uint(&self.r),
|
||||||
|
&BigEndianHash::from_uint(&self.s),
|
||||||
|
self.standard_v(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the hash of of the original transaction.
|
/// Get the hash of of the original transaction.
|
||||||
|
@ -231,7 +231,7 @@ fn call_other_private_contract() {
|
|||||||
trace!("Creating private contract B");
|
trace!("Creating private contract B");
|
||||||
// Build constructor data
|
// Build constructor data
|
||||||
let mut deploy_data = "6060604052341561000f57600080fd5b6040516020806101c583398101604052808051906020019091905050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505061014a8061007b6000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635197c7aa14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630c55699c6000604051602001526040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156100fe57600080fd5b6102c65a03f1151561010f57600080fd5b505050604051805190509050905600a165627a7a723058207f8994e02725b47d76ec73e5c54a338d27b306dd1c830276bff2d75fcd1a5c920029000000000000000000000000".to_string();
|
let mut deploy_data = "6060604052341561000f57600080fd5b6040516020806101c583398101604052808051906020019091905050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505061014a8061007b6000396000f300606060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635197c7aa14610046575b600080fd5b341561005157600080fd5b61005961006f565b6040518082815260200191505060405180910390f35b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16630c55699c6000604051602001526040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156100fe57600080fd5b6102c65a03f1151561010f57600080fd5b505050604051805190509050905600a165627a7a723058207f8994e02725b47d76ec73e5c54a338d27b306dd1c830276bff2d75fcd1a5c920029000000000000000000000000".to_string();
|
||||||
deploy_data.push_str(&address_a.to_vec().to_hex());
|
deploy_data.push_str(&address_a.as_bytes().to_vec().to_hex());
|
||||||
let private_contract_b_test = deploy_data.from_hex().unwrap();
|
let private_contract_b_test = deploy_data.from_hex().unwrap();
|
||||||
let mut private_create_tx2 = Transaction::default();
|
let mut private_create_tx2 = Transaction::default();
|
||||||
private_create_tx2.action = Action::Create;
|
private_create_tx2.action = Action::Create;
|
||||||
|
@ -11,7 +11,7 @@ ethcore-blockchain = { path = "../blockchain" }
|
|||||||
ethcore-io = { path = "../../util/io" }
|
ethcore-io = { path = "../../util/io" }
|
||||||
ethcore-private-tx = { path = "../private-tx" }
|
ethcore-private-tx = { path = "../private-tx" }
|
||||||
ethcore-sync = { path = "../sync" }
|
ethcore-sync = { path = "../sync" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.6.0"
|
||||||
kvdb = "0.1"
|
kvdb = "0.1"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
trace-time = "0.1"
|
trace-time = "0.1"
|
||||||
|
@ -31,8 +31,8 @@ use ethereum_types::Address;
|
|||||||
fn combine_key<'a>(address_hash: &'a H256, key: &'a H256) -> H256 {
|
fn combine_key<'a>(address_hash: &'a H256, key: &'a H256) -> H256 {
|
||||||
let mut dst = key.clone();
|
let mut dst = key.clone();
|
||||||
{
|
{
|
||||||
let last_src: &[u8] = &*address_hash;
|
let last_src: &[u8] = address_hash.as_bytes();
|
||||||
let last_dst: &mut [u8] = &mut *dst;
|
let last_dst: &mut [u8] = dst.as_bytes_mut();
|
||||||
for (k, a) in last_dst[12..].iter_mut().zip(&last_src[12..]) {
|
for (k, a) in last_dst[12..].iter_mut().zip(&last_src[12..]) {
|
||||||
*k ^= *a
|
*k ^= *a
|
||||||
}
|
}
|
||||||
|
@ -603,7 +603,7 @@ mod tests {
|
|||||||
db,
|
db,
|
||||||
parent,
|
parent,
|
||||||
last_hashes,
|
last_hashes,
|
||||||
Address::new(),
|
Address::zero(),
|
||||||
(3141562.into(), 31415620.into()),
|
(3141562.into(), 31415620.into()),
|
||||||
vec![],
|
vec![],
|
||||||
false,
|
false,
|
||||||
|
@ -95,7 +95,7 @@ impl Pricer for ModexpPricer {
|
|||||||
// read lengths as U256 here for accurate gas calculation.
|
// read lengths as U256 here for accurate gas calculation.
|
||||||
let mut read_len = || {
|
let mut read_len = || {
|
||||||
reader.read_exact(&mut buf[..]).expect("reading from zero-extended memory cannot fail; qed");
|
reader.read_exact(&mut buf[..]).expect("reading from zero-extended memory cannot fail; qed");
|
||||||
U256::from(H256::from_slice(&buf[..]))
|
U256::from_big_endian(&buf[..])
|
||||||
};
|
};
|
||||||
let base_len = read_len();
|
let base_len = read_len();
|
||||||
let exp_len = read_len();
|
let exp_len = read_len();
|
||||||
@ -118,7 +118,7 @@ impl Pricer for ModexpPricer {
|
|||||||
let mut reader = input[(96 + base_len as usize)..].chain(io::repeat(0));
|
let mut reader = input[(96 + base_len as usize)..].chain(io::repeat(0));
|
||||||
let len = min(exp_len, 32) as usize;
|
let len = min(exp_len, 32) as usize;
|
||||||
reader.read_exact(&mut buf[(32 - len)..]).expect("reading from zero-extended memory cannot fail; qed");
|
reader.read_exact(&mut buf[(32 - len)..]).expect("reading from zero-extended memory cannot fail; qed");
|
||||||
U256::from(H256::from_slice(&buf[..]))
|
U256::from_big_endian(&buf[..])
|
||||||
};
|
};
|
||||||
|
|
||||||
let adjusted_exp_len = Self::adjusted_exp_len(exp_len, exp_low);
|
let adjusted_exp_len = Self::adjusted_exp_len(exp_len, exp_low);
|
||||||
@ -286,7 +286,7 @@ impl Impl for EcRecover {
|
|||||||
if let Ok(p) = ec_recover(&s, &hash) {
|
if let Ok(p) = ec_recover(&s, &hash) {
|
||||||
let r = keccak(p);
|
let r = keccak(p);
|
||||||
output.write(0, &[0; 12]);
|
output.write(0, &[0; 12]);
|
||||||
output.write(12, &r[12..r.len()]);
|
output.write(12, &r.as_bytes()[12..]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -33,7 +33,7 @@ use itertools::Itertools;
|
|||||||
use journaldb;
|
use journaldb;
|
||||||
use kvdb::{DBValue, KeyValueDB, DBTransaction};
|
use kvdb::{DBValue, KeyValueDB, DBTransaction};
|
||||||
use parking_lot::{Mutex, RwLock};
|
use parking_lot::{Mutex, RwLock};
|
||||||
use rand::OsRng;
|
use rand::rngs::OsRng;
|
||||||
use types::transaction::{self, LocalizedTransaction, UnverifiedTransaction, SignedTransaction, Action};
|
use types::transaction::{self, LocalizedTransaction, UnverifiedTransaction, SignedTransaction, Action};
|
||||||
use trie::{TrieSpec, TrieFactory, Trie};
|
use trie::{TrieSpec, TrieFactory, Trie};
|
||||||
use types::ancestry_action::AncestryAction;
|
use types::ancestry_action::AncestryAction;
|
||||||
@ -456,7 +456,7 @@ impl Importer {
|
|||||||
{
|
{
|
||||||
trace_time!("import_old_block");
|
trace_time!("import_old_block");
|
||||||
// verify the block, passing the chain for updating the epoch verifier.
|
// verify the block, passing the chain for updating the epoch verifier.
|
||||||
let mut rng = OsRng::new()?;
|
let mut rng = OsRng::new().map_err(|e| format!("{}", e))?;
|
||||||
self.ancient_verifier.verify(&mut rng, &unverified.header, &chain)?;
|
self.ancient_verifier.verify(&mut rng, &unverified.header, &chain)?;
|
||||||
|
|
||||||
// Commit results
|
// Commit results
|
||||||
@ -908,12 +908,12 @@ impl Client {
|
|||||||
let hashes = self.last_hashes.read();
|
let hashes = self.last_hashes.read();
|
||||||
if hashes.front().map_or(false, |h| h == parent_hash) {
|
if hashes.front().map_or(false, |h| h == parent_hash) {
|
||||||
let mut res = Vec::from(hashes.clone());
|
let mut res = Vec::from(hashes.clone());
|
||||||
res.resize(256, H256::default());
|
res.resize(256, H256::zero());
|
||||||
return Arc::new(res);
|
return Arc::new(res);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut last_hashes = LastHashes::new();
|
let mut last_hashes = LastHashes::new();
|
||||||
last_hashes.resize(256, H256::default());
|
last_hashes.resize(256, H256::zero());
|
||||||
last_hashes[0] = parent_hash.clone();
|
last_hashes[0] = parent_hash.clone();
|
||||||
let chain = self.chain.read();
|
let chain = self.chain.read();
|
||||||
for i in 0..255 {
|
for i in 0..255 {
|
||||||
@ -1223,7 +1223,7 @@ impl Client {
|
|||||||
// transaction for calling contracts from services like engine.
|
// transaction for calling contracts from services like engine.
|
||||||
// from the null sender, with 50M gas.
|
// from the null sender, with 50M gas.
|
||||||
fn contract_call_tx(&self, block_id: BlockId, address: Address, data: Bytes) -> SignedTransaction {
|
fn contract_call_tx(&self, block_id: BlockId, address: Address, data: Bytes) -> SignedTransaction {
|
||||||
let from = Address::default();
|
let from = Address::zero();
|
||||||
transaction::Transaction {
|
transaction::Transaction {
|
||||||
nonce: self.nonce(&from, block_id).unwrap_or_else(|| self.engine.account_start_nonce(0)),
|
nonce: self.nonce(&from, block_id).unwrap_or_else(|| self.engine.account_start_nonce(0)),
|
||||||
action: Action::Call(address),
|
action: Action::Call(address),
|
||||||
@ -1341,8 +1341,8 @@ impl BlockChainReset for Client {
|
|||||||
best_block_hash = current_header.parent_hash();
|
best_block_hash = current_header.parent_hash();
|
||||||
|
|
||||||
let (number, hash) = (current_header.number(), current_header.hash());
|
let (number, hash) = (current_header.number(), current_header.hash());
|
||||||
batch.delete(::db::COL_HEADERS, &hash);
|
batch.delete(::db::COL_HEADERS, hash.as_bytes());
|
||||||
batch.delete(::db::COL_BODIES, &hash);
|
batch.delete(::db::COL_BODIES, hash.as_bytes());
|
||||||
Writable::delete::<BlockDetails, H264>
|
Writable::delete::<BlockDetails, H264>
|
||||||
(&mut batch, ::db::COL_EXTRA, &hash);
|
(&mut batch, ::db::COL_EXTRA, &hash);
|
||||||
Writable::delete::<H256, BlockNumberKey>
|
Writable::delete::<H256, BlockNumberKey>
|
||||||
@ -1375,7 +1375,7 @@ impl BlockChainReset for Client {
|
|||||||
&best_block_details
|
&best_block_details
|
||||||
);
|
);
|
||||||
// update the new best block hash
|
// update the new best block hash
|
||||||
batch.put(::db::COL_EXTRA, b"best", &best_block_hash);
|
batch.put(::db::COL_EXTRA, b"best", best_block_hash.as_bytes());
|
||||||
|
|
||||||
self.db.read()
|
self.db.read()
|
||||||
.key_value()
|
.key_value()
|
||||||
@ -1822,7 +1822,7 @@ impl BlockChainClient for Client {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(after) = after {
|
if let Some(after) = after {
|
||||||
if let Err(e) = iter.seek(after) {
|
if let Err(e) = iter.seek(after.as_bytes()) {
|
||||||
trace!(target: "fatdb", "list_accounts: Couldn't seek the DB: {:?}", e);
|
trace!(target: "fatdb", "list_accounts: Couldn't seek the DB: {:?}", e);
|
||||||
} else {
|
} else {
|
||||||
// Position the iterator after the `after` element
|
// Position the iterator after the `after` element
|
||||||
@ -1870,7 +1870,7 @@ impl BlockChainClient for Client {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(after) = after {
|
if let Some(after) = after {
|
||||||
if let Err(e) = iter.seek(after) {
|
if let Err(e) = iter.seek(after.as_bytes()) {
|
||||||
trace!(target: "fatdb", "list_storage: Couldn't seek the DB: {:?}", e);
|
trace!(target: "fatdb", "list_storage: Couldn't seek the DB: {:?}", e);
|
||||||
} else {
|
} else {
|
||||||
// Position the iterator after the `after` element
|
// Position the iterator after the `after` element
|
||||||
@ -2592,6 +2592,7 @@ fn transaction_receipt(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use ethereum_types::{H256, Address};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_not_cache_details_before_commit() {
|
fn should_not_cache_details_before_commit() {
|
||||||
@ -2667,19 +2668,19 @@ mod tests {
|
|||||||
use types::transaction::{Transaction, LocalizedTransaction, Action};
|
use types::transaction::{Transaction, LocalizedTransaction, Action};
|
||||||
|
|
||||||
// given
|
// given
|
||||||
let key = KeyPair::from_secret_slice(&keccak("test")).unwrap();
|
let key = KeyPair::from_secret_slice(keccak("test").as_bytes()).unwrap();
|
||||||
let secret = key.secret();
|
let secret = key.secret();
|
||||||
let machine = ::ethereum::new_frontier_test_machine();
|
let machine = ::ethereum::new_frontier_test_machine();
|
||||||
|
|
||||||
let block_number = 1;
|
let block_number = 1;
|
||||||
let block_hash = 5.into();
|
let block_hash = H256::from_low_u64_be(5);
|
||||||
let state_root = 99.into();
|
let state_root = H256::from_low_u64_be(99);
|
||||||
let gas_used = 10.into();
|
let gas_used = 10.into();
|
||||||
let raw_tx = Transaction {
|
let raw_tx = Transaction {
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
gas_price: 0.into(),
|
gas_price: 0.into(),
|
||||||
gas: 21000.into(),
|
gas: 21000.into(),
|
||||||
action: Action::Call(10.into()),
|
action: Action::Call(Address::from_low_u64_be(10)),
|
||||||
value: 0.into(),
|
value: 0.into(),
|
||||||
data: vec![],
|
data: vec![],
|
||||||
};
|
};
|
||||||
@ -2692,11 +2693,11 @@ mod tests {
|
|||||||
cached_sender: Some(tx1.sender()),
|
cached_sender: Some(tx1.sender()),
|
||||||
};
|
};
|
||||||
let logs = vec![LogEntry {
|
let logs = vec![LogEntry {
|
||||||
address: 5.into(),
|
address: Address::from_low_u64_be(5),
|
||||||
topics: vec![],
|
topics: vec![],
|
||||||
data: vec![],
|
data: vec![],
|
||||||
}, LogEntry {
|
}, LogEntry {
|
||||||
address: 15.into(),
|
address: Address::from_low_u64_be(15),
|
||||||
topics: vec![],
|
topics: vec![],
|
||||||
data: vec![],
|
data: vec![],
|
||||||
}];
|
}];
|
||||||
|
@ -204,7 +204,7 @@ impl<'a> EvmTestClient<'a> {
|
|||||||
author: *genesis.author(),
|
author: *genesis.author(),
|
||||||
timestamp: genesis.timestamp(),
|
timestamp: genesis.timestamp(),
|
||||||
difficulty: *genesis.difficulty(),
|
difficulty: *genesis.difficulty(),
|
||||||
last_hashes: Arc::new([H256::default(); 256].to_vec()),
|
last_hashes: Arc::new([H256::zero(); 256].to_vec()),
|
||||||
gas_used: 0.into(),
|
gas_used: 0.into(),
|
||||||
gas_limit: *genesis.gas_limit(),
|
gas_limit: *genesis.gas_limit(),
|
||||||
};
|
};
|
||||||
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
//! Test client.
|
//! Test client.
|
||||||
|
|
||||||
|
use std::str::FromStr;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrder};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrder};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::collections::{HashMap, BTreeMap};
|
use std::collections::{HashMap, BTreeMap};
|
||||||
@ -167,9 +168,9 @@ impl TestBlockChainClient {
|
|||||||
let mut client = TestBlockChainClient {
|
let mut client = TestBlockChainClient {
|
||||||
blocks: RwLock::new(HashMap::new()),
|
blocks: RwLock::new(HashMap::new()),
|
||||||
numbers: RwLock::new(HashMap::new()),
|
numbers: RwLock::new(HashMap::new()),
|
||||||
genesis_hash: H256::new(),
|
genesis_hash: H256::zero(),
|
||||||
extra_data: extra_data,
|
extra_data: extra_data,
|
||||||
last_hash: RwLock::new(H256::new()),
|
last_hash: RwLock::new(H256::zero()),
|
||||||
difficulty: RwLock::new(spec.genesis_header().difficulty().clone()),
|
difficulty: RwLock::new(spec.genesis_header().difficulty().clone()),
|
||||||
balances: RwLock::new(HashMap::new()),
|
balances: RwLock::new(HashMap::new()),
|
||||||
nonces: RwLock::new(HashMap::new()),
|
nonces: RwLock::new(HashMap::new()),
|
||||||
@ -326,7 +327,7 @@ impl TestBlockChainClient {
|
|||||||
pub fn corrupt_block_parent(&self, n: BlockNumber) {
|
pub fn corrupt_block_parent(&self, n: BlockNumber) {
|
||||||
let hash = self.block_hash(BlockId::Number(n)).unwrap();
|
let hash = self.block_hash(BlockId::Number(n)).unwrap();
|
||||||
let mut header: Header = self.block_header(BlockId::Number(n)).unwrap().decode().expect("decoding failed");
|
let mut header: Header = self.block_header(BlockId::Number(n)).unwrap().decode().expect("decoding failed");
|
||||||
header.set_parent_hash(H256::from(42));
|
header.set_parent_hash(H256::from_low_u64_be(42));
|
||||||
let mut rlp = RlpStream::new_list(3);
|
let mut rlp = RlpStream::new_list(3);
|
||||||
rlp.append(&header);
|
rlp.append(&header);
|
||||||
rlp.append_raw(&::rlp::NULL_RLP, 1);
|
rlp.append_raw(&::rlp::NULL_RLP, 1);
|
||||||
@ -432,7 +433,7 @@ impl ScheduleInfo for TestBlockChainClient {
|
|||||||
|
|
||||||
impl ImportSealedBlock for TestBlockChainClient {
|
impl ImportSealedBlock for TestBlockChainClient {
|
||||||
fn import_sealed_block(&self, _block: SealedBlock) -> EthcoreResult<H256> {
|
fn import_sealed_block(&self, _block: SealedBlock) -> EthcoreResult<H256> {
|
||||||
Ok(H256::default())
|
Ok(H256::zero())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -661,7 +662,15 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn replay_block_transactions(&self, _block: BlockId, _analytics: CallAnalytics) -> Result<Box<Iterator<Item = (H256, Executed)>>, CallError> {
|
fn replay_block_transactions(&self, _block: BlockId, _analytics: CallAnalytics) -> Result<Box<Iterator<Item = (H256, Executed)>>, CallError> {
|
||||||
Ok(Box::new(self.traces.read().clone().unwrap().into_iter().map(|t| t.transaction_hash.unwrap_or(H256::new())).zip(self.execution_result.read().clone().unwrap().into_iter())))
|
Ok(Box::new(
|
||||||
|
self.traces
|
||||||
|
.read()
|
||||||
|
.clone()
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| t.transaction_hash.unwrap_or_default())
|
||||||
|
.zip(self.execution_result.read().clone().unwrap().into_iter())
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> {
|
fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> {
|
||||||
@ -685,7 +694,8 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
|
|
||||||
fn storage_at(&self, address: &Address, position: &H256, state: StateOrBlock) -> Option<H256> {
|
fn storage_at(&self, address: &Address, position: &H256, state: StateOrBlock) -> Option<H256> {
|
||||||
match state {
|
match state {
|
||||||
StateOrBlock::Block(BlockId::Latest) => Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_else(H256::new)),
|
StateOrBlock::Block(BlockId::Latest) =>
|
||||||
|
Some(self.storage.read().get(&(address.clone(), position.clone())).cloned().unwrap_or_default()),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -773,7 +783,7 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
// works only if blocks are one after another 1 -> 2 -> 3
|
// works only if blocks are one after another 1 -> 2 -> 3
|
||||||
fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> {
|
fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> {
|
||||||
Some(TreeRoute {
|
Some(TreeRoute {
|
||||||
ancestor: H256::new(),
|
ancestor: H256::zero(),
|
||||||
index: 0,
|
index: 0,
|
||||||
blocks: {
|
blocks: {
|
||||||
let numbers_read = self.numbers.read();
|
let numbers_read = self.numbers.read();
|
||||||
@ -808,7 +818,7 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
// TODO: returns just hashes instead of node state rlp(?)
|
// TODO: returns just hashes instead of node state rlp(?)
|
||||||
fn state_data(&self, hash: &H256) -> Option<Bytes> {
|
fn state_data(&self, hash: &H256) -> Option<Bytes> {
|
||||||
// starts with 'f' ?
|
// starts with 'f' ?
|
||||||
if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") {
|
if *hash > H256::from_str("f000000000000000000000000000000000000000000000000000000000000000").unwrap() {
|
||||||
let mut rlp = RlpStream::new();
|
let mut rlp = RlpStream::new();
|
||||||
rlp.append(&hash.clone());
|
rlp.append(&hash.clone());
|
||||||
return Some(rlp.out());
|
return Some(rlp.out());
|
||||||
@ -818,7 +828,7 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
|
|
||||||
fn block_receipts(&self, hash: &H256) -> Option<BlockReceipts> {
|
fn block_receipts(&self, hash: &H256) -> Option<BlockReceipts> {
|
||||||
// starts with 'f' ?
|
// starts with 'f' ?
|
||||||
if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") {
|
if *hash > H256::from_str("f000000000000000000000000000000000000000000000000000000000000000").unwrap() {
|
||||||
let receipt = BlockReceipts::new(vec![Receipt::new(
|
let receipt = BlockReceipts::new(vec![Receipt::new(
|
||||||
TransactionOutcome::StateRoot(H256::zero()),
|
TransactionOutcome::StateRoot(H256::zero()),
|
||||||
U256::zero(),
|
U256::zero(),
|
||||||
|
@ -212,7 +212,7 @@ struct EpochManager {
|
|||||||
impl EpochManager {
|
impl EpochManager {
|
||||||
fn blank() -> Self {
|
fn blank() -> Self {
|
||||||
EpochManager {
|
EpochManager {
|
||||||
epoch_transition_hash: H256::default(),
|
epoch_transition_hash: H256::zero(),
|
||||||
epoch_transition_number: 0,
|
epoch_transition_number: 0,
|
||||||
finality_checker: RollingFinality::blank(Vec::new()),
|
finality_checker: RollingFinality::blank(Vec::new()),
|
||||||
force: true,
|
force: true,
|
||||||
@ -502,7 +502,7 @@ impl super::EpochVerifier<EthereumMachine> for EpochVerifier {
|
|||||||
fn header_seal_hash(header: &Header, empty_steps_rlp: Option<&[u8]>) -> H256 {
|
fn header_seal_hash(header: &Header, empty_steps_rlp: Option<&[u8]>) -> H256 {
|
||||||
match empty_steps_rlp {
|
match empty_steps_rlp {
|
||||||
Some(empty_steps_rlp) => {
|
Some(empty_steps_rlp) => {
|
||||||
let mut message = header.bare_hash().to_vec();
|
let mut message = header.bare_hash().as_bytes().to_vec();
|
||||||
message.extend_from_slice(empty_steps_rlp);
|
message.extend_from_slice(empty_steps_rlp);
|
||||||
keccak(message)
|
keccak(message)
|
||||||
},
|
},
|
||||||
@ -1170,7 +1170,7 @@ impl Engine<EthereumMachine> for AuthorityRound {
|
|||||||
|
|
||||||
let mut fields = vec![
|
let mut fields = vec![
|
||||||
encode(&step),
|
encode(&step),
|
||||||
encode(&(&H520::from(signature) as &[u8])),
|
encode(&(H520::from(signature).as_bytes())),
|
||||||
];
|
];
|
||||||
|
|
||||||
if let Some(empty_steps_rlp) = empty_steps_rlp {
|
if let Some(empty_steps_rlp) = empty_steps_rlp {
|
||||||
@ -2138,7 +2138,7 @@ mod tests {
|
|||||||
let signature = tap.sign(addr1, Some("1".into()), header.bare_hash()).unwrap();
|
let signature = tap.sign(addr1, Some("1".into()), header.bare_hash()).unwrap();
|
||||||
|
|
||||||
// empty step with invalid step
|
// empty step with invalid step
|
||||||
let empty_steps = vec![SealedEmptyStep { signature: 0.into(), step: 2 }];
|
let empty_steps = vec![SealedEmptyStep { signature: H520::zero(), step: 2 }];
|
||||||
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
||||||
|
|
||||||
assert_insufficient_proof(
|
assert_insufficient_proof(
|
||||||
@ -2147,7 +2147,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// empty step with invalid signature
|
// empty step with invalid signature
|
||||||
let empty_steps = vec![SealedEmptyStep { signature: 0.into(), step: 1 }];
|
let empty_steps = vec![SealedEmptyStep { signature: H520::zero(), step: 1 }];
|
||||||
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
||||||
|
|
||||||
assert_insufficient_proof(
|
assert_insufficient_proof(
|
||||||
@ -2289,7 +2289,7 @@ mod tests {
|
|||||||
p.maximum_empty_steps = 0;
|
p.maximum_empty_steps = 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
let parent_hash: H256 = 1.into();
|
let parent_hash = H256::from_low_u64_be(1);
|
||||||
let signature = H520::default();
|
let signature = H520::default();
|
||||||
let step = |step: u64| EmptyStep {
|
let step = |step: u64| EmptyStep {
|
||||||
step,
|
step,
|
||||||
|
@ -113,7 +113,7 @@ impl Engine<EthereumMachine> for BasicAuthority {
|
|||||||
if self.validators.contains(header.parent_hash(), author) {
|
if self.validators.contains(header.parent_hash(), author) {
|
||||||
// account should be pernamently unlocked, otherwise sealing will fail
|
// account should be pernamently unlocked, otherwise sealing will fail
|
||||||
if let Ok(signature) = self.sign(header.bare_hash()) {
|
if let Ok(signature) = self.sign(header.bare_hash()) {
|
||||||
return Seal::Regular(vec![::rlp::encode(&(&H520::from(signature) as &[u8]))]);
|
return Seal::Regular(vec![::rlp::encode(&(H520::from(signature).as_bytes()))]);
|
||||||
} else {
|
} else {
|
||||||
trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable");
|
trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable");
|
||||||
}
|
}
|
||||||
|
@ -177,8 +177,9 @@ pub fn apply_block_rewards<M: Machine>(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
|
use std::str::FromStr;
|
||||||
use client::PrepareOpenBlock;
|
use client::PrepareOpenBlock;
|
||||||
use ethereum_types::U256;
|
use ethereum_types::{U256, Address};
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use test_helpers::generate_dummy_client_with_spec;
|
use test_helpers::generate_dummy_client_with_spec;
|
||||||
|
|
||||||
@ -193,12 +194,12 @@ mod test {
|
|||||||
|
|
||||||
// the spec has a block reward contract defined at the given address
|
// the spec has a block reward contract defined at the given address
|
||||||
let block_reward_contract = BlockRewardContract::new_from_address(
|
let block_reward_contract = BlockRewardContract::new_from_address(
|
||||||
"0000000000000000000000000000000000000042".into(),
|
Address::from_str("0000000000000000000000000000000000000042").unwrap(),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut call = |to, data| {
|
let mut call = |to, data| {
|
||||||
let mut block = client.prepare_open_block(
|
let mut block = client.prepare_open_block(
|
||||||
"0000000000000000000000000000000000000001".into(),
|
Address::from_str("0000000000000000000000000000000000000001").unwrap(),
|
||||||
(3141562.into(), 31415620.into()),
|
(3141562.into(), 31415620.into()),
|
||||||
vec![],
|
vec![],
|
||||||
).unwrap();
|
).unwrap();
|
||||||
@ -223,16 +224,16 @@ mod test {
|
|||||||
|
|
||||||
// the contract rewards (1000 + kind) for each benefactor
|
// the contract rewards (1000 + kind) for each benefactor
|
||||||
let beneficiaries = vec![
|
let beneficiaries = vec![
|
||||||
("0000000000000000000000000000000000000033".into(), RewardKind::Author),
|
(Address::from_str("0000000000000000000000000000000000000033").unwrap(), RewardKind::Author),
|
||||||
("0000000000000000000000000000000000000034".into(), RewardKind::Uncle(1)),
|
(Address::from_str("0000000000000000000000000000000000000034").unwrap(), RewardKind::Uncle(1)),
|
||||||
("0000000000000000000000000000000000000035".into(), RewardKind::EmptyStep),
|
(Address::from_str("0000000000000000000000000000000000000035").unwrap(), RewardKind::EmptyStep),
|
||||||
];
|
];
|
||||||
|
|
||||||
let rewards = block_reward_contract.reward(&beneficiaries, &mut call).unwrap();
|
let rewards = block_reward_contract.reward(&beneficiaries, &mut call).unwrap();
|
||||||
let expected = vec![
|
let expected = vec![
|
||||||
("0000000000000000000000000000000000000033".into(), U256::from(1000)),
|
(Address::from_str("0000000000000000000000000000000000000033").unwrap(), U256::from(1000)),
|
||||||
("0000000000000000000000000000000000000034".into(), U256::from(1000 + 101)),
|
(Address::from_str("0000000000000000000000000000000000000034").unwrap(), U256::from(1000 + 101)),
|
||||||
("0000000000000000000000000000000000000035".into(), U256::from(1000 + 2)),
|
(Address::from_str("0000000000000000000000000000000000000035").unwrap(), U256::from(1000 + 2)),
|
||||||
];
|
];
|
||||||
|
|
||||||
assert_eq!(expected, rewards);
|
assert_eq!(expected, rewards);
|
||||||
|
@ -194,7 +194,7 @@ impl CliqueBlockState {
|
|||||||
Err(BlockError::InvalidSealArity(Mismatch { expected: 2, found: decoded_seal.len() }))?
|
Err(BlockError::InvalidSealArity(Mismatch { expected: 2, found: decoded_seal.len() }))?
|
||||||
}
|
}
|
||||||
|
|
||||||
let nonce: H64 = decoded_seal[1].into();
|
let nonce = H64::from_slice(decoded_seal[1]);
|
||||||
self.update_signers_on_vote(VoteType::from_nonce(nonce)?, creator, *header.author(), header.number())?;
|
self.update_signers_on_vote(VoteType::from_nonce(nonce)?, creator, *header.author(), header.number())?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -570,7 +570,7 @@ impl Engine<EthereumMachine> for Clique {
|
|||||||
|
|
||||||
if is_checkpoint && *header.author() != NULL_AUTHOR {
|
if is_checkpoint && *header.author() != NULL_AUTHOR {
|
||||||
return Err(EngineError::CliqueWrongAuthorCheckpoint(Mismatch {
|
return Err(EngineError::CliqueWrongAuthorCheckpoint(Mismatch {
|
||||||
expected: 0.into(),
|
expected: H160::zero(),
|
||||||
found: *header.author(),
|
found: *header.author(),
|
||||||
}))?;
|
}))?;
|
||||||
}
|
}
|
||||||
@ -583,8 +583,8 @@ impl Engine<EthereumMachine> for Clique {
|
|||||||
}))?
|
}))?
|
||||||
}
|
}
|
||||||
|
|
||||||
let mixhash: H256 = seal_fields[0].into();
|
let mixhash = H256::from_slice(seal_fields[0]);
|
||||||
let nonce: H64 = seal_fields[1].into();
|
let nonce = H64::from_slice(seal_fields[1]);
|
||||||
|
|
||||||
// Nonce must be 0x00..0 or 0xff..f
|
// Nonce must be 0x00..0 or 0xff..f
|
||||||
if nonce != NONCE_DROP_VOTE && nonce != NONCE_AUTH_VOTE {
|
if nonce != NONCE_DROP_VOTE && nonce != NONCE_AUTH_VOTE {
|
||||||
|
@ -70,10 +70,10 @@ impl CliqueTester {
|
|||||||
let mut extra_data = vec![0; VANITY_LENGTH];
|
let mut extra_data = vec![0; VANITY_LENGTH];
|
||||||
|
|
||||||
for &signer in SIGNER_TAGS.iter() {
|
for &signer in SIGNER_TAGS.iter() {
|
||||||
let secret = Secret::from(H256::from(signer as u64));
|
let secret = Secret::from(H256::from_low_u64_be(signer as u64));
|
||||||
let keypair = KeyPair::from_secret(secret).unwrap();
|
let keypair = KeyPair::from_secret(secret).unwrap();
|
||||||
if initial_signers.contains(&signer) {
|
if initial_signers.contains(&signer) {
|
||||||
extra_data.extend(&*keypair.address());
|
extra_data.extend(keypair.address().as_bytes());
|
||||||
}
|
}
|
||||||
signers.insert(signer, keypair);
|
signers.insert(signer, keypair);
|
||||||
}
|
}
|
||||||
@ -151,7 +151,7 @@ impl CliqueTester {
|
|||||||
CliqueBlockType::Checkpoint => {
|
CliqueBlockType::Checkpoint => {
|
||||||
let signers = self.clique.state(&last_header).unwrap().signers().clone();
|
let signers = self.clique.state(&last_header).unwrap().signers().clone();
|
||||||
for signer in signers {
|
for signer in signers {
|
||||||
extra_data.extend(&*signer);
|
extra_data.extend(signer.as_bytes());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
CliqueBlockType::Vote(v) => seal = v.as_rlp(),
|
CliqueBlockType::Vote(v) => seal = v.as_rlp(),
|
||||||
|
@ -102,7 +102,7 @@ pub fn extract_signers(header: &Header) -> Result<BTreeSet<Address>, Error> {
|
|||||||
.map(|i| {
|
.map(|i| {
|
||||||
let start = i * ADDRESS_LENGTH;
|
let start = i * ADDRESS_LENGTH;
|
||||||
let end = start + ADDRESS_LENGTH;
|
let end = start + ADDRESS_LENGTH;
|
||||||
signers_raw[start..end].into()
|
Address::from_slice(&signers_raw[start..end])
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@ -111,5 +111,5 @@ pub fn extract_signers(header: &Header) -> Result<BTreeSet<Address>, Error> {
|
|||||||
|
|
||||||
/// Retrieve `null_seal`
|
/// Retrieve `null_seal`
|
||||||
pub fn null_seal() -> Vec<Vec<u8>> {
|
pub fn null_seal() -> Vec<Vec<u8>> {
|
||||||
vec![encode(&NULL_MIXHASH.to_vec()), encode(&NULL_NONCE.to_vec())]
|
vec![encode(&NULL_MIXHASH.as_bytes().to_vec()), encode(&NULL_NONCE.as_bytes().to_vec())]
|
||||||
}
|
}
|
||||||
|
@ -108,7 +108,7 @@ mod tests {
|
|||||||
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
||||||
let genesis_header = spec.genesis_header();
|
let genesis_header = spec.genesis_header();
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::default(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
||||||
let b = b.close_and_lock().unwrap();
|
let b = b.close_and_lock().unwrap();
|
||||||
if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) {
|
if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) {
|
||||||
assert!(b.try_seal(engine, seal).is_ok());
|
assert!(b.try_seal(engine, seal).is_ok());
|
||||||
|
@ -175,7 +175,7 @@ mod tests {
|
|||||||
|
|
||||||
// Check a block that is a bit in future, reject it but don't report the validator.
|
// Check a block that is a bit in future, reject it but don't report the validator.
|
||||||
let mut header = Header::default();
|
let mut header = Header::default();
|
||||||
let seal = vec![encode(&4u8), encode(&(&H520::default() as &[u8]))];
|
let seal = vec![encode(&4u8), encode(&H520::zero().as_bytes())];
|
||||||
header.set_seal(seal);
|
header.set_seal(seal);
|
||||||
header.set_author(v1);
|
header.set_author(v1);
|
||||||
header.set_number(2);
|
header.set_number(2);
|
||||||
@ -186,7 +186,7 @@ mod tests {
|
|||||||
|
|
||||||
// Now create one that is more in future. That one should be rejected and validator should be reported.
|
// Now create one that is more in future. That one should be rejected and validator should be reported.
|
||||||
let mut header = Header::default();
|
let mut header = Header::default();
|
||||||
let seal = vec![encode(&8u8), encode(&(&H520::default() as &[u8]))];
|
let seal = vec![encode(&8u8), encode(&H520::zero().as_bytes())];
|
||||||
header.set_seal(seal);
|
header.set_seal(seal);
|
||||||
header.set_author(v1);
|
header.set_author(v1);
|
||||||
header.set_number(2);
|
header.set_number(2);
|
||||||
|
@ -106,7 +106,7 @@ fn check_first_proof(machine: &EthereumMachine, contract_address: Address, old_h
|
|||||||
timestamp: old_header.timestamp(),
|
timestamp: old_header.timestamp(),
|
||||||
last_hashes: {
|
last_hashes: {
|
||||||
// this will break if we don't inclue all 256 last hashes.
|
// this will break if we don't inclue all 256 last hashes.
|
||||||
let mut last_hashes: Vec<_> = (0..256).map(|_| H256::default()).collect();
|
let mut last_hashes: Vec<_> = (0..256).map(|_| H256::zero()).collect();
|
||||||
last_hashes[255] = *old_header.parent_hash();
|
last_hashes[255] = *old_header.parent_hash();
|
||||||
Arc::new(last_hashes)
|
Arc::new(last_hashes)
|
||||||
},
|
},
|
||||||
@ -117,7 +117,7 @@ fn check_first_proof(machine: &EthereumMachine, contract_address: Address, old_h
|
|||||||
let number = old_header.number();
|
let number = old_header.number();
|
||||||
let (data, decoder) = validator_set::functions::get_validators::call();
|
let (data, decoder) = validator_set::functions::get_validators::call();
|
||||||
|
|
||||||
let from = Address::default();
|
let from = Address::zero();
|
||||||
let tx = Transaction {
|
let tx = Transaction {
|
||||||
nonce: machine.account_start_nonce(number),
|
nonce: machine.account_start_nonce(number),
|
||||||
action: Action::Call(contract_address),
|
action: Action::Call(contract_address),
|
||||||
@ -516,7 +516,7 @@ mod tests {
|
|||||||
nonce: 2.into(),
|
nonce: 2.into(),
|
||||||
gas_price: 0.into(),
|
gas_price: 0.into(),
|
||||||
gas: 21000.into(),
|
gas: 21000.into(),
|
||||||
action: Action::Call(Address::default()),
|
action: Action::Call(Address::zero()),
|
||||||
value: 0.into(),
|
value: 0.into(),
|
||||||
data: Vec::new(),
|
data: Vec::new(),
|
||||||
}.sign(&s0, Some(chain_id));
|
}.sign(&s0, Some(chain_id));
|
||||||
|
@ -324,7 +324,7 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
|
|||||||
|
|
||||||
let difficulty = ethash::boundary_to_difficulty(&H256(quick_get_difficulty(
|
let difficulty = ethash::boundary_to_difficulty(&H256(quick_get_difficulty(
|
||||||
&header.bare_hash().0,
|
&header.bare_hash().0,
|
||||||
seal.nonce.low_u64(),
|
seal.nonce.to_low_u64_be(),
|
||||||
&seal.mix_hash.0,
|
&seal.mix_hash.0,
|
||||||
header.number() >= self.ethash_params.progpow_transition
|
header.number() >= self.ethash_params.progpow_transition
|
||||||
)));
|
)));
|
||||||
@ -339,14 +339,14 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
|
|||||||
fn verify_block_unordered(&self, header: &Header) -> Result<(), Error> {
|
fn verify_block_unordered(&self, header: &Header) -> Result<(), Error> {
|
||||||
let seal = Seal::parse_seal(header.seal())?;
|
let seal = Seal::parse_seal(header.seal())?;
|
||||||
|
|
||||||
let result = self.pow.compute_light(header.number() as u64, &header.bare_hash().0, seal.nonce.low_u64());
|
let result = self.pow.compute_light(header.number() as u64, &header.bare_hash().0, seal.nonce.to_low_u64_be());
|
||||||
let mix = H256(result.mix_hash);
|
let mix = H256(result.mix_hash);
|
||||||
let difficulty = ethash::boundary_to_difficulty(&H256(result.value));
|
let difficulty = ethash::boundary_to_difficulty(&H256(result.value));
|
||||||
trace!(target: "miner", "num: {num}, seed: {seed}, h: {h}, non: {non}, mix: {mix}, res: {res}",
|
trace!(target: "miner", "num: {num}, seed: {seed}, h: {h}, non: {non}, mix: {mix}, res: {res}",
|
||||||
num = header.number() as u64,
|
num = header.number() as u64,
|
||||||
seed = H256(slow_hash_block_number(header.number() as u64)),
|
seed = H256(slow_hash_block_number(header.number() as u64)),
|
||||||
h = header.bare_hash(),
|
h = header.bare_hash(),
|
||||||
non = seal.nonce.low_u64(),
|
non = seal.nonce.to_low_u64_be(),
|
||||||
mix = H256(result.mix_hash),
|
mix = H256(result.mix_hash),
|
||||||
res = H256(result.value));
|
res = H256(result.value));
|
||||||
if mix != seal.mix_hash {
|
if mix != seal.mix_hash {
|
||||||
@ -591,7 +591,7 @@ mod tests {
|
|||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
let mut b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
let mut b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
||||||
let mut uncle = Header::new();
|
let mut uncle = Header::new();
|
||||||
let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
|
let uncle_author = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap();
|
||||||
uncle.set_author(uncle_author);
|
uncle.set_author(uncle_author);
|
||||||
b.push_uncle(uncle).unwrap();
|
b.push_uncle(uncle).unwrap();
|
||||||
|
|
||||||
@ -610,8 +610,8 @@ mod tests {
|
|||||||
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap();
|
||||||
let b = b.close().unwrap();
|
let b = b.close().unwrap();
|
||||||
|
|
||||||
let ubi_contract: Address = "00efdd5883ec628983e9063c7d969fe268bbf310".into();
|
let ubi_contract = Address::from_str("00efdd5883ec628983e9063c7d969fe268bbf310").unwrap();
|
||||||
let dev_contract: Address = "00756cf8159095948496617f5fb17ed95059f536".into();
|
let dev_contract = Address::from_str("00756cf8159095948496617f5fb17ed95059f536").unwrap();
|
||||||
assert_eq!(b.state.balance(&Address::zero()).unwrap(), U256::from_str("d8d726b7177a80000").unwrap());
|
assert_eq!(b.state.balance(&Address::zero()).unwrap(), U256::from_str("d8d726b7177a80000").unwrap());
|
||||||
assert_eq!(b.state.balance(&ubi_contract).unwrap(), U256::from_str("2b5e3af16b1880000").unwrap());
|
assert_eq!(b.state.balance(&ubi_contract).unwrap(), U256::from_str("2b5e3af16b1880000").unwrap());
|
||||||
assert_eq!(b.state.balance(&dev_contract).unwrap(), U256::from_str("c249fdd327780000").unwrap());
|
assert_eq!(b.state.balance(&dev_contract).unwrap(), U256::from_str("c249fdd327780000").unwrap());
|
||||||
@ -721,7 +721,7 @@ mod tests {
|
|||||||
fn can_do_proof_of_work_unordered_verification_fail() {
|
fn can_do_proof_of_work_unordered_verification_fail() {
|
||||||
let engine = test_spec().engine;
|
let engine = test_spec().engine;
|
||||||
let mut header: Header = Header::default();
|
let mut header: Header = Header::default();
|
||||||
header.set_seal(vec![rlp::encode(&H256::from("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d")), rlp::encode(&H64::zero())]);
|
header.set_seal(vec![rlp::encode(&H256::from_str("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d").unwrap()), rlp::encode(&H64::zero())]);
|
||||||
header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());
|
header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());
|
||||||
|
|
||||||
let verify_result = engine.verify_block_unordered(&header);
|
let verify_result = engine.verify_block_unordered(&header);
|
||||||
@ -914,7 +914,7 @@ mod tests {
|
|||||||
let tempdir = TempDir::new("").unwrap();
|
let tempdir = TempDir::new("").unwrap();
|
||||||
let ethash = Ethash::new(tempdir.path(), ethparams, machine, None);
|
let ethash = Ethash::new(tempdir.path(), ethparams, machine, None);
|
||||||
let mut header = Header::default();
|
let mut header = Header::default();
|
||||||
header.set_seal(vec![rlp::encode(&H256::from("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d")), rlp::encode(&H64::zero())]);
|
header.set_seal(vec![rlp::encode(&H256::from_str("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d").unwrap()), rlp::encode(&H64::zero())]);
|
||||||
let info = ethash.extra_info(&header);
|
let info = ethash.extra_info(&header);
|
||||||
assert_eq!(info["nonce"], "0x0000000000000000");
|
assert_eq!(info["nonce"], "0x0000000000000000");
|
||||||
assert_eq!(info["mixHash"], "0xb251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d");
|
assert_eq!(info["mixHash"], "0xb251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d");
|
||||||
|
@ -187,7 +187,8 @@ pub fn new_kovan_wasm_test_machine() -> EthereumMachine { load_machine(include_b
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use ethereum_types::U256;
|
use std::str::FromStr;
|
||||||
|
use ethereum_types::{U256, H256, Address};
|
||||||
use state::*;
|
use state::*;
|
||||||
use super::*;
|
use super::*;
|
||||||
use test_helpers::get_temp_state_db;
|
use test_helpers::get_temp_state_db;
|
||||||
@ -201,21 +202,21 @@ mod tests {
|
|||||||
let genesis_header = spec.genesis_header();
|
let genesis_header = spec.genesis_header();
|
||||||
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
||||||
let s = State::from_existing(db, genesis_header.state_root().clone(), engine.account_start_nonce(0), Default::default()).unwrap();
|
let s = State::from_existing(db, genesis_header.state_root().clone(), engine.account_start_nonce(0), Default::default()).unwrap();
|
||||||
assert_eq!(s.balance(&"0000000000000000000000000000000000000001".into()).unwrap(), 1u64.into());
|
assert_eq!(s.balance(&Address::from_str("0000000000000000000000000000000000000001").unwrap()).unwrap(), 1u64.into());
|
||||||
assert_eq!(s.balance(&"0000000000000000000000000000000000000002".into()).unwrap(), 1u64.into());
|
assert_eq!(s.balance(&Address::from_str("0000000000000000000000000000000000000002").unwrap()).unwrap(), 1u64.into());
|
||||||
assert_eq!(s.balance(&"0000000000000000000000000000000000000003".into()).unwrap(), 1u64.into());
|
assert_eq!(s.balance(&Address::from_str("0000000000000000000000000000000000000003").unwrap()).unwrap(), 1u64.into());
|
||||||
assert_eq!(s.balance(&"0000000000000000000000000000000000000004".into()).unwrap(), 1u64.into());
|
assert_eq!(s.balance(&Address::from_str("0000000000000000000000000000000000000004").unwrap()).unwrap(), 1u64.into());
|
||||||
assert_eq!(s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()).unwrap(), U256::from(1u64) << 200);
|
assert_eq!(s.balance(&Address::from_str("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c").unwrap()).unwrap(), U256::from(1u64) << 200);
|
||||||
assert_eq!(s.balance(&"0000000000000000000000000000000000000000".into()).unwrap(), 0u64.into());
|
assert_eq!(s.balance(&Address::from_str("0000000000000000000000000000000000000000").unwrap()).unwrap(), 0u64.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn morden() {
|
fn morden() {
|
||||||
let morden = new_morden(&::std::env::temp_dir());
|
let morden = new_morden(&::std::env::temp_dir());
|
||||||
|
|
||||||
assert_eq!(morden.state_root(), "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into());
|
assert_eq!(morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
|
||||||
let genesis = morden.genesis_block();
|
let genesis = morden.genesis_block();
|
||||||
assert_eq!(view!(BlockView, &genesis).header_view().hash(), "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into());
|
assert_eq!(view!(BlockView, &genesis).header_view().hash(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
|
||||||
|
|
||||||
let _ = morden.engine;
|
let _ = morden.engine;
|
||||||
}
|
}
|
||||||
@ -224,9 +225,9 @@ mod tests {
|
|||||||
fn frontier() {
|
fn frontier() {
|
||||||
let frontier = new_foundation(&::std::env::temp_dir());
|
let frontier = new_foundation(&::std::env::temp_dir());
|
||||||
|
|
||||||
assert_eq!(frontier.state_root(), "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into());
|
assert_eq!(frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
|
||||||
let genesis = frontier.genesis_block();
|
let genesis = frontier.genesis_block();
|
||||||
assert_eq!(view!(BlockView, &genesis).header_view().hash(), "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into());
|
assert_eq!(view!(BlockView, &genesis).header_view().hash(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
|
||||||
|
|
||||||
let _ = frontier.engine;
|
let _ = frontier.engine;
|
||||||
}
|
}
|
||||||
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
//! Transaction Execution environment.
|
//! Transaction Execution environment.
|
||||||
use std::cmp;
|
use std::cmp;
|
||||||
|
use std::convert::TryFrom;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use ethereum_types::{H256, U256, U512, Address};
|
use ethereum_types::{H256, U256, U512, Address};
|
||||||
@ -858,7 +859,7 @@ impl<'a, B: 'a + StateBackend> Executive<'a, B> {
|
|||||||
if !schedule.keep_unsigned_nonce || !t.is_unsigned() {
|
if !schedule.keep_unsigned_nonce || !t.is_unsigned() {
|
||||||
self.state.inc_nonce(&sender)?;
|
self.state.inc_nonce(&sender)?;
|
||||||
}
|
}
|
||||||
self.state.sub_balance(&sender, &U256::from(gas_cost), &mut substate.to_cleanup_mode(&schedule))?;
|
self.state.sub_balance(&sender, &U256::try_from(gas_cost).expect("Total cost (value + gas_cost) is lower than max allowed balance (U256); gas_cost has to fit U256; qed"), &mut substate.to_cleanup_mode(&schedule))?;
|
||||||
|
|
||||||
let (result, output) = match t.action {
|
let (result, output) = match t.action {
|
||||||
Action::Create => {
|
Action::Create => {
|
||||||
@ -1174,7 +1175,7 @@ mod tests {
|
|||||||
use rustc_hex::FromHex;
|
use rustc_hex::FromHex;
|
||||||
use ethkey::{Generator, Random};
|
use ethkey::{Generator, Random};
|
||||||
use super::*;
|
use super::*;
|
||||||
use ethereum_types::{H256, U256, U512, Address};
|
use ethereum_types::{H256, U256, U512, Address, BigEndianHash};
|
||||||
use vm::{ActionParams, ActionValue, CallType, EnvInfo, CreateContractAddress};
|
use vm::{ActionParams, ActionValue, CallType, EnvInfo, CreateContractAddress};
|
||||||
use evm::{Factory, VMType};
|
use evm::{Factory, VMType};
|
||||||
use error::ExecutionError;
|
use error::ExecutionError;
|
||||||
@ -1229,7 +1230,7 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(gas_left, U256::from(79_975));
|
assert_eq!(gas_left, U256::from(79_975));
|
||||||
assert_eq!(state.storage_at(&address, &H256::new()).unwrap(), H256::from(&U256::from(0xf9u64)));
|
assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), BigEndianHash::from_uint(&U256::from(0xf9u64)));
|
||||||
assert_eq!(state.balance(&sender).unwrap(), U256::from(0xf9));
|
assert_eq!(state.balance(&sender).unwrap(), U256::from(0xf9));
|
||||||
assert_eq!(state.balance(&address).unwrap(), U256::from(0x7));
|
assert_eq!(state.balance(&address).unwrap(), U256::from(0x7));
|
||||||
assert_eq!(substate.contracts_created.len(), 0);
|
assert_eq!(substate.contracts_created.len(), 0);
|
||||||
@ -1331,8 +1332,8 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(tracer.drain(), vec![FlatTrace {
|
assert_eq!(tracer.drain(), vec![FlatTrace {
|
||||||
action: trace::Action::Call(trace::Call {
|
action: trace::Action::Call(trace::Call {
|
||||||
from: "4444444444444444444444444444444444444444".into(),
|
from: Address::from_str("4444444444444444444444444444444444444444").unwrap(),
|
||||||
to: "5555555555555555555555555555555555555555".into(),
|
to: Address::from_str("5555555555555555555555555555555555555555").unwrap(),
|
||||||
value: 100.into(),
|
value: 100.into(),
|
||||||
gas: 100_000.into(),
|
gas: 100_000.into(),
|
||||||
input: vec![],
|
input: vec![],
|
||||||
@ -1346,8 +1347,8 @@ mod tests {
|
|||||||
trace_address: Default::default()
|
trace_address: Default::default()
|
||||||
}, FlatTrace {
|
}, FlatTrace {
|
||||||
action: trace::Action::Call(trace::Call {
|
action: trace::Action::Call(trace::Call {
|
||||||
from: "5555555555555555555555555555555555555555".into(),
|
from: Address::from_str("5555555555555555555555555555555555555555").unwrap(),
|
||||||
to: "0000000000000000000000000000000000000003".into(),
|
to: Address::from_str("0000000000000000000000000000000000000003").unwrap(),
|
||||||
value: 1.into(),
|
value: 1.into(),
|
||||||
gas: 66560.into(),
|
gas: 66560.into(),
|
||||||
input: vec![],
|
input: vec![],
|
||||||
@ -1421,8 +1422,8 @@ mod tests {
|
|||||||
trace_address: Default::default(),
|
trace_address: Default::default(),
|
||||||
subtraces: 1,
|
subtraces: 1,
|
||||||
action: trace::Action::Call(trace::Call {
|
action: trace::Action::Call(trace::Call {
|
||||||
from: "cd1722f3947def4cf144679da39c4c32bdc35681".into(),
|
from: Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(),
|
||||||
to: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(),
|
to: Address::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(),
|
||||||
value: 100.into(),
|
value: 100.into(),
|
||||||
gas: 100000.into(),
|
gas: 100000.into(),
|
||||||
input: vec![],
|
input: vec![],
|
||||||
@ -1436,7 +1437,7 @@ mod tests {
|
|||||||
trace_address: vec![0].into_iter().collect(),
|
trace_address: vec![0].into_iter().collect(),
|
||||||
subtraces: 0,
|
subtraces: 0,
|
||||||
action: trace::Action::Create(trace::Create {
|
action: trace::Action::Create(trace::Create {
|
||||||
from: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(),
|
from: Address::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(),
|
||||||
value: 23.into(),
|
value: 23.into(),
|
||||||
gas: 67979.into(),
|
gas: 67979.into(),
|
||||||
init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85]
|
init: vec![96, 16, 128, 96, 12, 96, 0, 57, 96, 0, 243, 0, 96, 0, 53, 84, 21, 96, 9, 87, 0, 91, 96, 32, 53, 96, 0, 53, 85]
|
||||||
@ -1537,8 +1538,8 @@ mod tests {
|
|||||||
trace_address: Default::default(),
|
trace_address: Default::default(),
|
||||||
subtraces: 1,
|
subtraces: 1,
|
||||||
action: trace::Action::Call(trace::Call {
|
action: trace::Action::Call(trace::Call {
|
||||||
from: "cd1722f3947def4cf144679da39c4c32bdc35681".into(),
|
from: Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(),
|
||||||
to: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(),
|
to: Address::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(),
|
||||||
value: 100.into(),
|
value: 100.into(),
|
||||||
gas: 100_000.into(),
|
gas: 100_000.into(),
|
||||||
input: vec![],
|
input: vec![],
|
||||||
@ -1552,7 +1553,7 @@ mod tests {
|
|||||||
trace_address: vec![0].into_iter().collect(),
|
trace_address: vec![0].into_iter().collect(),
|
||||||
subtraces: 0,
|
subtraces: 0,
|
||||||
action: trace::Action::Create(trace::Create {
|
action: trace::Action::Create(trace::Create {
|
||||||
from: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(),
|
from: Address::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(),
|
||||||
value: 23.into(),
|
value: 23.into(),
|
||||||
gas: 66_917.into(),
|
gas: 66_917.into(),
|
||||||
init: vec![0x60, 0x01, 0x60, 0x00, 0xfd]
|
init: vec![0x60, 0x01, 0x60, 0x00, 0xfd]
|
||||||
@ -1803,7 +1804,13 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(gas_left, U256::from(73_237));
|
assert_eq!(gas_left, U256::from(73_237));
|
||||||
assert_eq!(state.storage_at(&address_a, &H256::from(&U256::from(0x23))).unwrap(), H256::from(&U256::from(1)));
|
assert_eq!(
|
||||||
|
state.storage_at(
|
||||||
|
&address_a,
|
||||||
|
&BigEndianHash::from_uint(&U256::from(0x23)),
|
||||||
|
).unwrap(),
|
||||||
|
BigEndianHash::from_uint(&U256::from(1)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// test is incorrect, mk
|
// test is incorrect, mk
|
||||||
@ -1848,8 +1855,8 @@ mod tests {
|
|||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(gas_left, U256::from(59_870));
|
assert_eq!(gas_left, U256::from(59_870));
|
||||||
assert_eq!(state.storage_at(&address, &H256::from(&U256::zero())).unwrap(), H256::from(&U256::from(1)));
|
assert_eq!(state.storage_at(&address, &BigEndianHash::from_uint(&U256::zero())).unwrap(), BigEndianHash::from_uint(&U256::from(1)));
|
||||||
assert_eq!(state.storage_at(&address, &H256::from(&U256::one())).unwrap(), H256::from(&U256::from(1)));
|
assert_eq!(state.storage_at(&address, &BigEndianHash::from_uint(&U256::one())).unwrap(), BigEndianHash::from_uint(&U256::from(1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// test is incorrect, mk
|
// test is incorrect, mk
|
||||||
@ -1890,7 +1897,7 @@ mod tests {
|
|||||||
assert_eq!(state.balance(&sender).unwrap(), U256::from(1));
|
assert_eq!(state.balance(&sender).unwrap(), U256::from(1));
|
||||||
assert_eq!(state.balance(&contract).unwrap(), U256::from(17));
|
assert_eq!(state.balance(&contract).unwrap(), U256::from(17));
|
||||||
assert_eq!(state.nonce(&sender).unwrap(), U256::from(1));
|
assert_eq!(state.nonce(&sender).unwrap(), U256::from(1));
|
||||||
assert_eq!(state.storage_at(&contract, &H256::new()).unwrap(), H256::from(&U256::from(1)));
|
assert_eq!(state.storage_at(&contract, &H256::zero()).unwrap(), BigEndianHash::from_uint(&U256::from(1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
evm_test!{test_transact_invalid_nonce: test_transact_invalid_nonce_int}
|
evm_test!{test_transact_invalid_nonce: test_transact_invalid_nonce_int}
|
||||||
@ -2059,17 +2066,17 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(result, U256::from(1));
|
assert_eq!(result, U256::from(1));
|
||||||
assert_eq!(output[..], returns[..]);
|
assert_eq!(output[..], returns[..]);
|
||||||
assert_eq!(state.storage_at(&contract_address, &H256::from(&U256::zero())).unwrap(), H256::from(&U256::from(0)));
|
assert_eq!(state.storage_at(&contract_address, &H256::zero()).unwrap(), H256::zero());
|
||||||
}
|
}
|
||||||
|
|
||||||
evm_test!{test_eip1283: test_eip1283_int}
|
evm_test!{test_eip1283: test_eip1283_int}
|
||||||
fn test_eip1283(factory: Factory) {
|
fn test_eip1283(factory: Factory) {
|
||||||
let x1 = Address::from(0x1000);
|
let x1 = Address::from_low_u64_be(0x1000);
|
||||||
let x2 = Address::from(0x1001);
|
let x2 = Address::from_low_u64_be(0x1001);
|
||||||
let y1 = Address::from(0x2001);
|
let y1 = Address::from_low_u64_be(0x2001);
|
||||||
let y2 = Address::from(0x2002);
|
let y2 = Address::from_low_u64_be(0x2002);
|
||||||
let operating_address = Address::from(0);
|
let operating_address = Address::zero();
|
||||||
let k = H256::new();
|
let k = H256::zero();
|
||||||
|
|
||||||
let mut state = get_temp_state_with_factory(factory.clone());
|
let mut state = get_temp_state_with_factory(factory.clone());
|
||||||
state.new_contract(&x1, U256::zero(), U256::from(1)).unwrap();
|
state.new_contract(&x1, U256::zero(), U256::from(1)).unwrap();
|
||||||
@ -2085,7 +2092,7 @@ mod tests {
|
|||||||
let machine = ::ethereum::new_constantinople_test_machine();
|
let machine = ::ethereum::new_constantinople_test_machine();
|
||||||
let schedule = machine.schedule(info.number);
|
let schedule = machine.schedule(info.number);
|
||||||
|
|
||||||
assert_eq!(state.storage_at(&operating_address, &k).unwrap(), H256::from(U256::from(0)));
|
assert_eq!(state.storage_at(&operating_address, &k).unwrap(), BigEndianHash::from_uint(&U256::from(0)));
|
||||||
// Test a call via top-level -> y1 -> x1
|
// Test a call via top-level -> y1 -> x1
|
||||||
let (FinalizationResult { gas_left, .. }, refund, gas) = {
|
let (FinalizationResult { gas_left, .. }, refund, gas) = {
|
||||||
let gas = U256::from(0xffffffffffu64);
|
let gas = U256::from(0xffffffffffu64);
|
||||||
@ -2103,7 +2110,7 @@ mod tests {
|
|||||||
assert_eq!(gas_used, U256::from(41860));
|
assert_eq!(gas_used, U256::from(41860));
|
||||||
assert_eq!(refund, 19800);
|
assert_eq!(refund, 19800);
|
||||||
|
|
||||||
assert_eq!(state.storage_at(&operating_address, &k).unwrap(), H256::from(U256::from(1)));
|
assert_eq!(state.storage_at(&operating_address, &k).unwrap(), BigEndianHash::from_uint(&U256::from(1)));
|
||||||
// Test a call via top-level -> y2 -> x2
|
// Test a call via top-level -> y2 -> x2
|
||||||
let (FinalizationResult { gas_left, .. }, refund, gas) = {
|
let (FinalizationResult { gas_left, .. }, refund, gas) = {
|
||||||
let gas = U256::from(0xffffffffffu64);
|
let gas = U256::from(0xffffffffffu64);
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
//! Transaction Execution environment.
|
//! Transaction Execution environment.
|
||||||
use std::cmp;
|
use std::cmp;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address, BigEndianHash};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use state::{Backend as StateBackend, State, Substate, CleanupMode};
|
use state::{Backend as StateBackend, State, Substate, CleanupMode};
|
||||||
use machine::EthereumMachine as Machine;
|
use machine::EthereumMachine as Machine;
|
||||||
@ -166,6 +166,7 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B>
|
|||||||
Ok((code, hash)) => (code, hash),
|
Ok((code, hash)) => (code, hash),
|
||||||
Err(_) => return H256::zero(),
|
Err(_) => return H256::zero(),
|
||||||
};
|
};
|
||||||
|
let data: H256 = BigEndianHash::from_uint(number);
|
||||||
|
|
||||||
let params = ActionParams {
|
let params = ActionParams {
|
||||||
sender: self.origin_info.address.clone(),
|
sender: self.origin_info.address.clone(),
|
||||||
@ -177,7 +178,7 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B>
|
|||||||
gas_price: 0.into(),
|
gas_price: 0.into(),
|
||||||
code: code,
|
code: code,
|
||||||
code_hash: code_hash,
|
code_hash: code_hash,
|
||||||
data: Some(H256::from(number).to_vec()),
|
data: Some(data.as_bytes().to_vec()),
|
||||||
call_type: CallType::Call,
|
call_type: CallType::Call,
|
||||||
params_type: vm::ParamsType::Separate,
|
params_type: vm::ParamsType::Separate,
|
||||||
};
|
};
|
||||||
@ -185,8 +186,8 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B>
|
|||||||
let mut ex = Executive::new(self.state, self.env_info, self.machine, self.schedule);
|
let mut ex = Executive::new(self.state, self.env_info, self.machine, self.schedule);
|
||||||
let r = ex.call_with_crossbeam(params, self.substate, self.stack_depth + 1, self.tracer, self.vm_tracer);
|
let r = ex.call_with_crossbeam(params, self.substate, self.stack_depth + 1, self.tracer, self.vm_tracer);
|
||||||
let output = match &r {
|
let output = match &r {
|
||||||
Ok(ref r) => H256::from(&r.return_data[..32]),
|
Ok(ref r) => H256::from_slice(&r.return_data[..32]),
|
||||||
_ => H256::new(),
|
_ => H256::zero(),
|
||||||
};
|
};
|
||||||
trace!("ext: blockhash contract({}) -> {:?}({}) self.env_info.number={}\n", number, r, output, self.env_info.number);
|
trace!("ext: blockhash contract({}) -> {:?}({}) self.env_info.number={}\n", number, r, output, self.env_info.number);
|
||||||
output
|
output
|
||||||
@ -428,6 +429,7 @@ mod tests {
|
|||||||
use test_helpers::get_temp_state;
|
use test_helpers::get_temp_state;
|
||||||
use super::*;
|
use super::*;
|
||||||
use trace::{NoopTracer, NoopVMTracer};
|
use trace::{NoopTracer, NoopVMTracer};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
fn get_test_origin() -> OriginInfo {
|
fn get_test_origin() -> OriginInfo {
|
||||||
OriginInfo {
|
OriginInfo {
|
||||||
@ -441,7 +443,7 @@ mod tests {
|
|||||||
fn get_test_env_info() -> EnvInfo {
|
fn get_test_env_info() -> EnvInfo {
|
||||||
EnvInfo {
|
EnvInfo {
|
||||||
number: 100,
|
number: 100,
|
||||||
author: 0.into(),
|
author: Address::from_low_u64_be(0),
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
difficulty: 0.into(),
|
difficulty: 0.into(),
|
||||||
last_hashes: Arc::new(vec![]),
|
last_hashes: Arc::new(vec![]),
|
||||||
@ -509,7 +511,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn can_return_block_hash() {
|
fn can_return_block_hash() {
|
||||||
let test_hash = H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd");
|
let test_hash = H256::from_str("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd").unwrap();
|
||||||
let test_env_number = 0x120001;
|
let test_env_number = 0x120001;
|
||||||
|
|
||||||
let mut setup = TestSetup::new();
|
let mut setup = TestSetup::new();
|
||||||
@ -546,11 +548,11 @@ mod tests {
|
|||||||
// this should panic because we have no balance on any account
|
// this should panic because we have no balance on any account
|
||||||
ext.call(
|
ext.call(
|
||||||
&"0000000000000000000000000000000000000000000000000000000000120000".parse::<U256>().unwrap(),
|
&"0000000000000000000000000000000000000000000000000000000000120000".parse::<U256>().unwrap(),
|
||||||
&Address::new(),
|
&Address::zero(),
|
||||||
&Address::new(),
|
&Address::zero(),
|
||||||
Some("0000000000000000000000000000000000000000000000000000000000150000".parse::<U256>().unwrap()),
|
Some("0000000000000000000000000000000000000000000000000000000000150000".parse::<U256>().unwrap()),
|
||||||
&[],
|
&[],
|
||||||
&Address::new(),
|
&Address::zero(),
|
||||||
CallType::Call,
|
CallType::Call,
|
||||||
false,
|
false,
|
||||||
).ok().unwrap();
|
).ok().unwrap();
|
||||||
@ -559,7 +561,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn can_log() {
|
fn can_log() {
|
||||||
let log_data = vec![120u8, 110u8];
|
let log_data = vec![120u8, 110u8];
|
||||||
let log_topics = vec![H256::from("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd")];
|
let log_topics = vec![H256::from_str("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd").unwrap()];
|
||||||
|
|
||||||
let mut setup = TestSetup::new();
|
let mut setup = TestSetup::new();
|
||||||
let state = &mut setup.state;
|
let state = &mut setup.state;
|
||||||
@ -577,7 +579,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn can_suicide() {
|
fn can_suicide() {
|
||||||
let refund_account = &Address::new();
|
let refund_account = &Address::zero();
|
||||||
|
|
||||||
let mut setup = TestSetup::new();
|
let mut setup = TestSetup::new();
|
||||||
let state = &mut setup.state;
|
let state = &mut setup.state;
|
||||||
@ -627,7 +629,7 @@ mod tests {
|
|||||||
let address = {
|
let address = {
|
||||||
let mut ext = Externalities::new(state, &setup.env_info, &setup.machine, &setup.schedule, 0, 0, &origin_info, &mut setup.sub_state, OutputPolicy::InitContract, &mut tracer, &mut vm_tracer, false);
|
let mut ext = Externalities::new(state, &setup.env_info, &setup.machine, &setup.schedule, 0, 0, &origin_info, &mut setup.sub_state, OutputPolicy::InitContract, &mut tracer, &mut vm_tracer, false);
|
||||||
|
|
||||||
match ext.create(&U256::max_value(), &U256::zero(), &[], CreateContractAddress::FromSenderSaltAndCodeHash(H256::default()), false) {
|
match ext.create(&U256::max_value(), &U256::zero(), &[], CreateContractAddress::FromSenderSaltAndCodeHash(H256::zero()), false) {
|
||||||
Ok(ContractCreateResult::Created(address, _)) => address,
|
Ok(ContractCreateResult::Created(address, _)) => address,
|
||||||
_ => panic!("Test create failed; expected Created, got Failed/Reverted."),
|
_ => panic!("Test create failed; expected Created, got Failed/Reverted."),
|
||||||
}
|
}
|
||||||
|
@ -35,6 +35,7 @@ use ethtrie;
|
|||||||
use rlp::RlpStream;
|
use rlp::RlpStream;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use machine::EthereumMachine as Machine;
|
use machine::EthereumMachine as Machine;
|
||||||
|
use ethereum_types::BigEndianHash;
|
||||||
|
|
||||||
use super::HookType;
|
use super::HookType;
|
||||||
|
|
||||||
@ -339,8 +340,8 @@ fn do_json_test_for<H: FnMut(&str, HookType)>(vm_type: &VMType, json_data: &[u8]
|
|||||||
for (k, v) in account.storage {
|
for (k, v) in account.storage {
|
||||||
let key: U256 = k.into();
|
let key: U256 = k.into();
|
||||||
let value: U256 = v.into();
|
let value: U256 = v.into();
|
||||||
let found_storage = try_fail!(state.storage_at(&address, &From::from(key)));
|
let found_storage = try_fail!(state.storage_at(&address, &BigEndianHash::from_uint(&key)));
|
||||||
fail_unless(found_storage == From::from(value), "storage is incorrect");
|
fail_unless(found_storage == BigEndianHash::from_uint(&value), "storage is incorrect");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -111,6 +111,7 @@ macro_rules! test {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Declares a test
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! declare_test {
|
macro_rules! declare_test {
|
||||||
(skip => $arr: expr, $id: ident, $name: expr) => {
|
(skip => $arr: expr, $id: ident, $name: expr) => {
|
||||||
|
@ -35,7 +35,7 @@ fn test_trie<H: FnMut(&str, HookType)>(json: &[u8], trie: TrieSpec, start_stop_h
|
|||||||
start_stop_hook(&name, HookType::OnStart);
|
start_stop_hook(&name, HookType::OnStart);
|
||||||
|
|
||||||
let mut memdb = journaldb::new_memory_db();
|
let mut memdb = journaldb::new_memory_db();
|
||||||
let mut root = H256::default();
|
let mut root = H256::zero();
|
||||||
let mut t = factory.create(&mut memdb, &mut root);
|
let mut t = factory.create(&mut memdb, &mut root);
|
||||||
|
|
||||||
for (key, value) in test.input.data.into_iter() {
|
for (key, value) in test.input.data.into_iter() {
|
||||||
|
@ -107,6 +107,8 @@ extern crate using_queue;
|
|||||||
extern crate vm;
|
extern crate vm;
|
||||||
extern crate wasm;
|
extern crate wasm;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
extern crate rand_xorshift;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
extern crate ethcore_accounts as accounts;
|
extern crate ethcore_accounts as accounts;
|
||||||
#[cfg(feature = "stratum")]
|
#[cfg(feature = "stratum")]
|
||||||
|
@ -60,7 +60,7 @@ impl From<::ethjson::spec::EthashParams> for EthashExtensions {
|
|||||||
EthashExtensions {
|
EthashExtensions {
|
||||||
homestead_transition: p.homestead_transition.map_or(0, Into::into),
|
homestead_transition: p.homestead_transition.map_or(0, Into::into),
|
||||||
dao_hardfork_transition: p.dao_hardfork_transition.map_or(u64::max_value(), Into::into),
|
dao_hardfork_transition: p.dao_hardfork_transition.map_or(u64::max_value(), Into::into),
|
||||||
dao_hardfork_beneficiary: p.dao_hardfork_beneficiary.map_or_else(Address::new, Into::into),
|
dao_hardfork_beneficiary: p.dao_hardfork_beneficiary.map_or_else(Address::zero, Into::into),
|
||||||
dao_hardfork_accounts: p.dao_hardfork_accounts.unwrap_or_else(Vec::new).into_iter().map(Into::into).collect(),
|
dao_hardfork_accounts: p.dao_hardfork_accounts.unwrap_or_else(Vec::new).into_iter().map(Into::into).collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -203,7 +203,7 @@ impl EthereumMachine {
|
|||||||
block,
|
block,
|
||||||
params.eip210_contract_address,
|
params.eip210_contract_address,
|
||||||
params.eip210_contract_gas,
|
params.eip210_contract_gas,
|
||||||
Some(parent_hash.to_vec()),
|
Some(parent_hash.as_bytes().to_vec()),
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -462,12 +462,13 @@ fn round_block_gas_limit(gas_limit: U256, lower_limit: U256, upper_limit: U256)
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
fn get_default_ethash_extensions() -> EthashExtensions {
|
fn get_default_ethash_extensions() -> EthashExtensions {
|
||||||
EthashExtensions {
|
EthashExtensions {
|
||||||
homestead_transition: 1150000,
|
homestead_transition: 1150000,
|
||||||
dao_hardfork_transition: u64::max_value(),
|
dao_hardfork_transition: u64::max_value(),
|
||||||
dao_hardfork_beneficiary: "0000000000000000000000000000000000000001".into(),
|
dao_hardfork_beneficiary: Address::from_str("0000000000000000000000000000000000000001").unwrap(),
|
||||||
dao_hardfork_accounts: Vec::new(),
|
dao_hardfork_accounts: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1499,7 +1499,7 @@ mod tests {
|
|||||||
|
|
||||||
// when new block is imported
|
// when new block is imported
|
||||||
let client = generate_dummy_client(2);
|
let client = generate_dummy_client(2);
|
||||||
let imported = [0.into()];
|
let imported = [H256::zero()];
|
||||||
let empty = &[];
|
let empty = &[];
|
||||||
miner.chain_new_blocks(&*client, &imported, empty, &imported, empty, false);
|
miner.chain_new_blocks(&*client, &imported, empty, &imported, empty, false);
|
||||||
|
|
||||||
@ -1745,7 +1745,6 @@ mod tests {
|
|||||||
|
|
||||||
#[cfg(feature = "price-info")]
|
#[cfg(feature = "price-info")]
|
||||||
fn dynamic_gas_pricer() -> GasPricer {
|
fn dynamic_gas_pricer() -> GasPricer {
|
||||||
use std::time::Duration;
|
|
||||||
use parity_runtime::Executor;
|
use parity_runtime::Executor;
|
||||||
use fetch::Client as FetchClient;
|
use fetch::Client as FetchClient;
|
||||||
use ethcore_miner::gas_price_calibrator::{GasPriceCalibrator, GasPriceCalibratorOptions};
|
use ethcore_miner::gas_price_calibrator::{GasPriceCalibrator, GasPriceCalibratorOptions};
|
||||||
|
@ -21,7 +21,7 @@ use std::net::{SocketAddr, AddrParseError};
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use client::{Client, ImportSealedBlock};
|
use client::{Client, ImportSealedBlock};
|
||||||
use ethereum_types::{H64, H256, clean_0x, U256};
|
use ethereum_types::{H64, H256, U256};
|
||||||
use ethash::{self, SeedHashCompute};
|
use ethash::{self, SeedHashCompute};
|
||||||
#[cfg(feature = "work-notify")]
|
#[cfg(feature = "work-notify")]
|
||||||
use ethcore_miner::work_notify::NotifyWork;
|
use ethcore_miner::work_notify::NotifyWork;
|
||||||
@ -47,6 +47,14 @@ pub struct Options {
|
|||||||
pub secret: Option<H256>,
|
pub secret: Option<H256>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn clean_0x(s: &str) -> &str {
|
||||||
|
if s.starts_with("0x") {
|
||||||
|
&s[2..]
|
||||||
|
} else {
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct SubmitPayload {
|
struct SubmitPayload {
|
||||||
nonce: H64,
|
nonce: H64,
|
||||||
pow_hash: H256,
|
pow_hash: H256,
|
||||||
|
@ -20,7 +20,7 @@ use std::fmt;
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use hash::{keccak};
|
use hash::{keccak};
|
||||||
use ethereum_types::{H256, U256};
|
use ethereum_types::{H256, U256, BigEndianHash};
|
||||||
use hash_db::HashDB;
|
use hash_db::HashDB;
|
||||||
use kvdb::DBValue;
|
use kvdb::DBValue;
|
||||||
use keccak_hasher::KeccakHasher;
|
use keccak_hasher::KeccakHasher;
|
||||||
@ -73,7 +73,7 @@ impl PodAccount {
|
|||||||
let mut stream = RlpStream::new_list(4);
|
let mut stream = RlpStream::new_list(4);
|
||||||
stream.append(&self.nonce);
|
stream.append(&self.nonce);
|
||||||
stream.append(&self.balance);
|
stream.append(&self.balance);
|
||||||
stream.append(&sec_trie_root(self.storage.iter().map(|(k, v)| (k, rlp::encode(&U256::from(&**v))))));
|
stream.append(&sec_trie_root(self.storage.iter().map(|(k, v)| (k, rlp::encode(&v.into_uint())))));
|
||||||
stream.append(&keccak(&self.code.as_ref().unwrap_or(&vec![])));
|
stream.append(&keccak(&self.code.as_ref().unwrap_or(&vec![])));
|
||||||
stream.out()
|
stream.out()
|
||||||
}
|
}
|
||||||
@ -84,10 +84,10 @@ impl PodAccount {
|
|||||||
Some(ref c) if !c.is_empty() => { db.insert(c); }
|
Some(ref c) if !c.is_empty() => { db.insert(c); }
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
let mut r = H256::new();
|
let mut r = H256::zero();
|
||||||
let mut t = factory.create(db, &mut r);
|
let mut t = factory.create(db, &mut r);
|
||||||
for (k, v) in &self.storage {
|
for (k, v) in &self.storage {
|
||||||
if let Err(e) = t.insert(k, &rlp::encode(&U256::from(&**v))) {
|
if let Err(e) = t.insert(k.as_bytes(), &rlp::encode(&v.into_uint())) {
|
||||||
warn!("Encountered potential DB corruption: {}", e);
|
warn!("Encountered potential DB corruption: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -103,7 +103,7 @@ impl From<ethjson::blockchain::Account> for PodAccount {
|
|||||||
storage: a.storage.into_iter().map(|(key, value)| {
|
storage: a.storage.into_iter().map(|(key, value)| {
|
||||||
let key: U256 = key.into();
|
let key: U256 = key.into();
|
||||||
let value: U256 = value.into();
|
let value: U256 = value.into();
|
||||||
(H256::from(key), H256::from(value))
|
(BigEndianHash::from_uint(&key), BigEndianHash::from_uint(&value))
|
||||||
}).collect(),
|
}).collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -118,7 +118,7 @@ impl From<ethjson::spec::Account> for PodAccount {
|
|||||||
storage: a.storage.map_or_else(BTreeMap::new, |s| s.into_iter().map(|(key, value)| {
|
storage: a.storage.map_or_else(BTreeMap::new, |s| s.into_iter().map(|(key, value)| {
|
||||||
let key: U256 = key.into();
|
let key: U256 = key.into();
|
||||||
let value: U256 = value.into();
|
let value: U256 = value.into();
|
||||||
(H256::from(key), H256::from(value))
|
(BigEndianHash::from_uint(&key), BigEndianHash::from_uint(&value))
|
||||||
}).collect()),
|
}).collect()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -130,7 +130,7 @@ impl fmt::Display for PodAccount {
|
|||||||
self.balance,
|
self.balance,
|
||||||
self.nonce,
|
self.nonce,
|
||||||
self.code.as_ref().map_or(0, |c| c.len()),
|
self.code.as_ref().map_or(0, |c| c.len()),
|
||||||
self.code.as_ref().map_or_else(H256::new, |c| keccak(c)),
|
self.code.as_ref().map_or_else(H256::zero, |c| keccak(c)),
|
||||||
self.storage.len(),
|
self.storage.len(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -154,7 +154,7 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option<A
|
|||||||
}),
|
}),
|
||||||
(Some(pre), Some(post)) => {
|
(Some(pre), Some(post)) => {
|
||||||
let storage: Vec<_> = pre.storage.keys().merge(post.storage.keys())
|
let storage: Vec<_> = pre.storage.keys().merge(post.storage.keys())
|
||||||
.filter(|k| pre.storage.get(k).unwrap_or(&H256::new()) != post.storage.get(k).unwrap_or(&H256::new()))
|
.filter(|k| pre.storage.get(k).unwrap_or(&H256::zero()) != post.storage.get(k).unwrap_or(&H256::zero()))
|
||||||
.collect();
|
.collect();
|
||||||
let r = AccountDiff {
|
let r = AccountDiff {
|
||||||
balance: Diff::new(pre.balance, post.balance),
|
balance: Diff::new(pre.balance, post.balance),
|
||||||
@ -165,8 +165,8 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option<A
|
|||||||
},
|
},
|
||||||
storage: storage.into_iter().map(|k|
|
storage: storage.into_iter().map(|k|
|
||||||
(k.clone(), Diff::new(
|
(k.clone(), Diff::new(
|
||||||
pre.storage.get(k).cloned().unwrap_or_else(H256::new),
|
pre.storage.get(k).cloned().unwrap_or_else(H256::zero),
|
||||||
post.storage.get(k).cloned().unwrap_or_else(H256::new)
|
post.storage.get(k).cloned().unwrap_or_else(H256::zero)
|
||||||
))).collect(),
|
))).collect(),
|
||||||
};
|
};
|
||||||
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.is_empty() {
|
if r.balance.is_same() && r.nonce.is_same() && r.code.is_same() && r.storage.is_empty() {
|
||||||
@ -184,6 +184,7 @@ mod test {
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use types::account_diff::*;
|
use types::account_diff::*;
|
||||||
use super::{PodAccount, diff_pod};
|
use super::{PodAccount, diff_pod};
|
||||||
|
use ethereum_types::H256;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn existence() {
|
fn existence() {
|
||||||
@ -227,24 +228,40 @@ mod test {
|
|||||||
balance: 0.into(),
|
balance: 0.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(vec![]),
|
code: Some(vec![]),
|
||||||
storage: map_into![1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 0, 6 => 0, 7 => 0]
|
storage: map![
|
||||||
|
H256::from_low_u64_be(1) => H256::from_low_u64_be(1),
|
||||||
|
H256::from_low_u64_be(2) => H256::from_low_u64_be(2),
|
||||||
|
H256::from_low_u64_be(3) => H256::from_low_u64_be(3),
|
||||||
|
H256::from_low_u64_be(4) => H256::from_low_u64_be(4),
|
||||||
|
H256::from_low_u64_be(5) => H256::from_low_u64_be(0),
|
||||||
|
H256::from_low_u64_be(6) => H256::from_low_u64_be(0),
|
||||||
|
H256::from_low_u64_be(7) => H256::from_low_u64_be(0)
|
||||||
|
],
|
||||||
};
|
};
|
||||||
let b = PodAccount {
|
let b = PodAccount {
|
||||||
balance: 0.into(),
|
balance: 0.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(vec![]),
|
code: Some(vec![]),
|
||||||
storage: map_into![1 => 1, 2 => 3, 3 => 0, 5 => 0, 7 => 7, 8 => 0, 9 => 9]
|
storage: map![
|
||||||
|
H256::from_low_u64_be(1) => H256::from_low_u64_be(1),
|
||||||
|
H256::from_low_u64_be(2) => H256::from_low_u64_be(3),
|
||||||
|
H256::from_low_u64_be(3) => H256::from_low_u64_be(0),
|
||||||
|
H256::from_low_u64_be(5) => H256::from_low_u64_be(0),
|
||||||
|
H256::from_low_u64_be(7) => H256::from_low_u64_be(7),
|
||||||
|
H256::from_low_u64_be(8) => H256::from_low_u64_be(0),
|
||||||
|
H256::from_low_u64_be(9) => H256::from_low_u64_be(9)
|
||||||
|
]
|
||||||
};
|
};
|
||||||
assert_eq!(diff_pod(Some(&a), Some(&b)), Some(AccountDiff {
|
assert_eq!(diff_pod(Some(&a), Some(&b)), Some(AccountDiff {
|
||||||
balance: Diff::Same,
|
balance: Diff::Same,
|
||||||
nonce: Diff::Same,
|
nonce: Diff::Same,
|
||||||
code: Diff::Same,
|
code: Diff::Same,
|
||||||
storage: map![
|
storage: map![
|
||||||
2.into() => Diff::new(2.into(), 3.into()),
|
H256::from_low_u64_be(2) => Diff::new(H256::from_low_u64_be(2), H256::from_low_u64_be(3)),
|
||||||
3.into() => Diff::new(3.into(), 0.into()),
|
H256::from_low_u64_be(3) => Diff::new(H256::from_low_u64_be(3), H256::from_low_u64_be(0)),
|
||||||
4.into() => Diff::new(4.into(), 0.into()),
|
H256::from_low_u64_be(4) => Diff::new(H256::from_low_u64_be(4), H256::from_low_u64_be(0)),
|
||||||
7.into() => Diff::new(0.into(), 7.into()),
|
H256::from_low_u64_be(7) => Diff::new(H256::from_low_u64_be(0), H256::from_low_u64_be(7)),
|
||||||
9.into() => Diff::new(0.into(), 9.into())
|
H256::from_low_u64_be(9) => Diff::new(H256::from_low_u64_be(0), H256::from_low_u64_be(9))
|
||||||
],
|
],
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
@ -90,12 +90,12 @@ mod test {
|
|||||||
use types::state_diff::*;
|
use types::state_diff::*;
|
||||||
use types::account_diff::*;
|
use types::account_diff::*;
|
||||||
use pod_account::PodAccount;
|
use pod_account::PodAccount;
|
||||||
use super::PodState;
|
use super::{PodState, Address};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn create_delete() {
|
fn create_delete() {
|
||||||
let a = PodState::from(map![
|
let a = PodState::from(map![
|
||||||
1.into() => PodAccount {
|
Address::from_low_u64_be(1) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
@ -103,7 +103,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
assert_eq!(super::diff_pod(&a, &PodState::new()), StateDiff { raw: map![
|
assert_eq!(super::diff_pod(&a, &PodState::new()), StateDiff { raw: map![
|
||||||
1.into() => AccountDiff{
|
Address::from_low_u64_be(1) => AccountDiff{
|
||||||
balance: Diff::Died(69.into()),
|
balance: Diff::Died(69.into()),
|
||||||
nonce: Diff::Died(0.into()),
|
nonce: Diff::Died(0.into()),
|
||||||
code: Diff::Died(vec![]),
|
code: Diff::Died(vec![]),
|
||||||
@ -111,7 +111,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
]});
|
]});
|
||||||
assert_eq!(super::diff_pod(&PodState::new(), &a), StateDiff{ raw: map![
|
assert_eq!(super::diff_pod(&PodState::new(), &a), StateDiff{ raw: map![
|
||||||
1.into() => AccountDiff{
|
Address::from_low_u64_be(1) => AccountDiff{
|
||||||
balance: Diff::Born(69.into()),
|
balance: Diff::Born(69.into()),
|
||||||
nonce: Diff::Born(0.into()),
|
nonce: Diff::Born(0.into()),
|
||||||
code: Diff::Born(vec![]),
|
code: Diff::Born(vec![]),
|
||||||
@ -123,7 +123,7 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn create_delete_with_unchanged() {
|
fn create_delete_with_unchanged() {
|
||||||
let a = PodState::from(map![
|
let a = PodState::from(map![
|
||||||
1.into() => PodAccount {
|
Address::from_low_u64_be(1) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
@ -131,13 +131,13 @@ mod test {
|
|||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
let b = PodState::from(map![
|
let b = PodState::from(map![
|
||||||
1.into() => PodAccount {
|
Address::from_low_u64_be(1) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
storage: map![],
|
storage: map![],
|
||||||
},
|
},
|
||||||
2.into() => PodAccount {
|
Address::from_low_u64_be(2) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
@ -145,7 +145,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![
|
assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![
|
||||||
2.into() => AccountDiff{
|
Address::from_low_u64_be(2) => AccountDiff{
|
||||||
balance: Diff::Born(69.into()),
|
balance: Diff::Born(69.into()),
|
||||||
nonce: Diff::Born(0.into()),
|
nonce: Diff::Born(0.into()),
|
||||||
code: Diff::Born(vec![]),
|
code: Diff::Born(vec![]),
|
||||||
@ -153,7 +153,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
]});
|
]});
|
||||||
assert_eq!(super::diff_pod(&b, &a), StateDiff { raw: map![
|
assert_eq!(super::diff_pod(&b, &a), StateDiff { raw: map![
|
||||||
2.into() => AccountDiff{
|
Address::from_low_u64_be(2) => AccountDiff{
|
||||||
balance: Diff::Died(69.into()),
|
balance: Diff::Died(69.into()),
|
||||||
nonce: Diff::Died(0.into()),
|
nonce: Diff::Died(0.into()),
|
||||||
code: Diff::Died(vec![]),
|
code: Diff::Died(vec![]),
|
||||||
@ -165,13 +165,13 @@ mod test {
|
|||||||
#[test]
|
#[test]
|
||||||
fn change_with_unchanged() {
|
fn change_with_unchanged() {
|
||||||
let a = PodState::from(map![
|
let a = PodState::from(map![
|
||||||
1.into() => PodAccount {
|
Address::from_low_u64_be(1) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
storage: map![],
|
storage: map![],
|
||||||
},
|
},
|
||||||
2.into() => PodAccount {
|
Address::from_low_u64_be(2) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
@ -179,13 +179,13 @@ mod test {
|
|||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
let b = PodState::from(map![
|
let b = PodState::from(map![
|
||||||
1.into() => PodAccount {
|
Address::from_low_u64_be(1) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 1.into(),
|
nonce: 1.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
storage: map![],
|
storage: map![],
|
||||||
},
|
},
|
||||||
2.into() => PodAccount {
|
Address::from_low_u64_be(2) => PodAccount {
|
||||||
balance: 69.into(),
|
balance: 69.into(),
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
code: Some(Vec::new()),
|
code: Some(Vec::new()),
|
||||||
@ -193,7 +193,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![
|
assert_eq!(super::diff_pod(&a, &b), StateDiff { raw: map![
|
||||||
1.into() => AccountDiff{
|
Address::from_low_u64_be(1) => AccountDiff{
|
||||||
balance: Diff::Same,
|
balance: Diff::Same,
|
||||||
nonce: Diff::Changed(0.into(), 1.into()),
|
nonce: Diff::Changed(0.into(), 1.into()),
|
||||||
code: Diff::Same,
|
code: Diff::Same,
|
||||||
|
@ -350,6 +350,6 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn encoding_empty_acc() {
|
fn encoding_empty_acc() {
|
||||||
let mut db = get_temp_state_db();
|
let mut db = get_temp_state_db();
|
||||||
assert_eq!(from_fat_rlp(&mut AccountDBMut::new(db.as_hash_db_mut(), &Address::default()), Rlp::new(&::rlp::NULL_RLP), H256::zero()).unwrap(), (ACC_EMPTY, None));
|
assert_eq!(from_fat_rlp(&mut AccountDBMut::new(db.as_hash_db_mut(), &Address::zero()), Rlp::new(&::rlp::NULL_RLP), H256::zero()).unwrap(), (ACC_EMPTY, None));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -152,7 +152,7 @@ mod tests {
|
|||||||
let encoded = encode_block(&b);
|
let encoded = encode_block(&b);
|
||||||
|
|
||||||
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded));
|
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded));
|
||||||
assert_eq!(abridged.to_block(H256::new(), 0, receipts_root).unwrap(), b);
|
assert_eq!(abridged.to_block(H256::zero(), 0, receipts_root).unwrap(), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -163,7 +163,7 @@ mod tests {
|
|||||||
let encoded = encode_block(&b);
|
let encoded = encode_block(&b);
|
||||||
|
|
||||||
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded));
|
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded));
|
||||||
assert_eq!(abridged.to_block(H256::new(), 2, receipts_root).unwrap(), b);
|
assert_eq!(abridged.to_block(H256::zero(), 2, receipts_root).unwrap(), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -177,7 +177,7 @@ mod tests {
|
|||||||
gas: U256::from(50_000),
|
gas: U256::from(50_000),
|
||||||
value: U256::from(1),
|
value: U256::from(1),
|
||||||
data: b"Hello!".to_vec()
|
data: b"Hello!".to_vec()
|
||||||
}.fake_sign(Address::from(0x69));
|
}.fake_sign(Address::from_low_u64_be(0x69));
|
||||||
|
|
||||||
let t2 = Transaction {
|
let t2 = Transaction {
|
||||||
action: Action::Create,
|
action: Action::Create,
|
||||||
@ -186,7 +186,7 @@ mod tests {
|
|||||||
gas: U256::from(300000),
|
gas: U256::from(300000),
|
||||||
value: U256::from(1000000000),
|
value: U256::from(1000000000),
|
||||||
data: "Eep!".into(),
|
data: "Eep!".into(),
|
||||||
}.fake_sign(Address::from(0x55));
|
}.fake_sign(Address::from_low_u64_be(0x55));
|
||||||
|
|
||||||
b.transactions.push(t1.into());
|
b.transactions.push(t1.into());
|
||||||
b.transactions.push(t2.into());
|
b.transactions.push(t2.into());
|
||||||
@ -199,6 +199,6 @@ mod tests {
|
|||||||
let encoded = encode_block(&b);
|
let encoded = encode_block(&b);
|
||||||
|
|
||||||
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded[..]));
|
let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded[..]));
|
||||||
assert_eq!(abridged.to_block(H256::new(), 0, receipts_root).unwrap(), b);
|
assert_eq!(abridged.to_block(H256::zero(), 0, receipts_root).unwrap(), b);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,7 @@ use ethereum_types::H256;
|
|||||||
use kvdb::KeyValueDB;
|
use kvdb::KeyValueDB;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use rlp::{RlpStream, Rlp};
|
use rlp::{RlpStream, Rlp};
|
||||||
use rand::OsRng;
|
use rand::rngs::OsRng;
|
||||||
use types::encoded;
|
use types::encoded;
|
||||||
|
|
||||||
/// Snapshot creation and restoration for PoW chains.
|
/// Snapshot creation and restoration for PoW chains.
|
||||||
@ -210,7 +210,7 @@ impl PowRebuilder {
|
|||||||
Ok(PowRebuilder {
|
Ok(PowRebuilder {
|
||||||
chain: chain,
|
chain: chain,
|
||||||
db: db,
|
db: db,
|
||||||
rng: OsRng::new()?,
|
rng: OsRng::new().map_err(|e| format!("{}", e))?,
|
||||||
disconnected: Vec::new(),
|
disconnected: Vec::new(),
|
||||||
best_number: manifest.block_number,
|
best_number: manifest.block_number,
|
||||||
best_hash: manifest.block_hash,
|
best_hash: manifest.block_hash,
|
||||||
|
@ -51,7 +51,7 @@ use super::state_db::StateDB;
|
|||||||
use super::state::Account as StateAccount;
|
use super::state::Account as StateAccount;
|
||||||
|
|
||||||
use crossbeam::scope;
|
use crossbeam::scope;
|
||||||
use rand::{Rng, OsRng};
|
use rand::{Rng, rngs::OsRng};
|
||||||
|
|
||||||
pub use self::error::Error;
|
pub use self::error::Error;
|
||||||
|
|
||||||
@ -411,7 +411,7 @@ impl StateRebuilder {
|
|||||||
let mut pairs = Vec::with_capacity(rlp.item_count()?);
|
let mut pairs = Vec::with_capacity(rlp.item_count()?);
|
||||||
|
|
||||||
// initialize the pairs vector with empty values so we have slots to write into.
|
// initialize the pairs vector with empty values so we have slots to write into.
|
||||||
pairs.resize(rlp.item_count()?, (H256::new(), Vec::new()));
|
pairs.resize(rlp.item_count()?, (H256::zero(), Vec::new()));
|
||||||
|
|
||||||
let status = rebuild_accounts(
|
let status = rebuild_accounts(
|
||||||
self.db.as_hash_db_mut(),
|
self.db.as_hash_db_mut(),
|
||||||
@ -450,9 +450,9 @@ impl StateRebuilder {
|
|||||||
if !flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
|
if !flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
|
||||||
|
|
||||||
if &thin_rlp[..] != &empty_rlp[..] {
|
if &thin_rlp[..] != &empty_rlp[..] {
|
||||||
self.bloom.set(&*hash);
|
self.bloom.set(hash.as_bytes());
|
||||||
}
|
}
|
||||||
account_trie.insert(&hash, &thin_rlp)?;
|
account_trie.insert(hash.as_bytes(), &thin_rlp)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -928,9 +928,9 @@ mod tests {
|
|||||||
version: 2,
|
version: 2,
|
||||||
state_hashes: state_hashes.clone(),
|
state_hashes: state_hashes.clone(),
|
||||||
block_hashes: block_hashes.clone(),
|
block_hashes: block_hashes.clone(),
|
||||||
state_root: H256::default(),
|
state_root: H256::zero(),
|
||||||
block_number: 100000,
|
block_number: 100000,
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
},
|
},
|
||||||
pruning: Algorithm::Archive,
|
pruning: Algorithm::Archive,
|
||||||
db: restoration_db_handler(db_config).open(&tempdir.path().to_owned()).unwrap(),
|
db: restoration_db_handler(db_config).open(&tempdir.path().to_owned()).unwrap(),
|
||||||
|
@ -124,7 +124,7 @@ pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) {
|
|||||||
SecTrieDBMut::from_existing(&mut db, root).unwrap()
|
SecTrieDBMut::from_existing(&mut db, root).unwrap()
|
||||||
};
|
};
|
||||||
|
|
||||||
for (k, v) in map.make_with(seed) {
|
for (k, v) in map.make_with(&mut seed.to_fixed_bytes()) {
|
||||||
trie.insert(&k, &v).unwrap();
|
trie.insert(&k, &v).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -157,7 +157,6 @@ pub fn restore(
|
|||||||
genesis: &[u8],
|
genesis: &[u8],
|
||||||
) -> Result<(), ::error::Error> {
|
) -> Result<(), ::error::Error> {
|
||||||
use std::sync::atomic::AtomicBool;
|
use std::sync::atomic::AtomicBool;
|
||||||
use snappy;
|
|
||||||
|
|
||||||
let flag = AtomicBool::new(true);
|
let flag = AtomicBool::new(true);
|
||||||
let components = engine.snapshot_components().unwrap();
|
let components = engine.snapshot_components().unwrap();
|
||||||
|
@ -126,7 +126,7 @@ fn make_chain(accounts: Arc<AccountProvider>, blocks_beyond: usize, transitions:
|
|||||||
nonce: *nonce,
|
nonce: *nonce,
|
||||||
gas_price: 1.into(),
|
gas_price: 1.into(),
|
||||||
gas: 21_000.into(),
|
gas: 21_000.into(),
|
||||||
action: Action::Call(Address::new()),
|
action: Action::Call(Address::zero()),
|
||||||
value: 1.into(),
|
value: 1.into(),
|
||||||
data: Vec::new(),
|
data: Vec::new(),
|
||||||
}.sign(&*RICH_SECRET, client.signing_chain_id());
|
}.sign(&*RICH_SECRET, client.signing_chain_id());
|
||||||
|
@ -119,7 +119,7 @@ fn checks_flag() {
|
|||||||
let mut stream = RlpStream::new_list(5);
|
let mut stream = RlpStream::new_list(5);
|
||||||
|
|
||||||
stream.append(&100u64)
|
stream.append(&100u64)
|
||||||
.append(&H256::default())
|
.append(&H256::zero())
|
||||||
.append(&(!0u64));
|
.append(&(!0u64));
|
||||||
|
|
||||||
stream.append_empty_data().append_empty_data();
|
stream.append_empty_data().append_empty_data();
|
||||||
@ -137,7 +137,7 @@ fn checks_flag() {
|
|||||||
block_hashes: Vec::new(),
|
block_hashes: Vec::new(),
|
||||||
state_root: ::hash::KECCAK_NULL_RLP,
|
state_root: ::hash::KECCAK_NULL_RLP,
|
||||||
block_number: 102,
|
block_number: 102,
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut rebuilder = SNAPSHOT_MODE.rebuilder(chain, db.clone(), &manifest).unwrap();
|
let mut rebuilder = SNAPSHOT_MODE.rebuilder(chain, db.clone(), &manifest).unwrap();
|
||||||
|
@ -28,18 +28,21 @@ use super::helpers::StateProducer;
|
|||||||
|
|
||||||
use error::Error;
|
use error::Error;
|
||||||
|
|
||||||
use rand::{XorShiftRng, SeedableRng};
|
use rand::SeedableRng;
|
||||||
|
use rand_xorshift::XorShiftRng;
|
||||||
use ethereum_types::H256;
|
use ethereum_types::H256;
|
||||||
use journaldb::{self, Algorithm};
|
use journaldb::{self, Algorithm};
|
||||||
use kvdb_rocksdb::{Database, DatabaseConfig};
|
use kvdb_rocksdb::{Database, DatabaseConfig};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
|
||||||
|
const RNG_SEED: [u8; 16] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn snap_and_restore() {
|
fn snap_and_restore() {
|
||||||
use hash_db::HashDB;
|
use hash_db::HashDB;
|
||||||
let mut producer = StateProducer::new();
|
let mut producer = StateProducer::new();
|
||||||
let mut rng = XorShiftRng::from_seed([1, 2, 3, 4]);
|
let mut rng = XorShiftRng::from_seed(RNG_SEED);
|
||||||
let mut old_db = journaldb::new_memory_db();
|
let mut old_db = journaldb::new_memory_db();
|
||||||
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
||||||
|
|
||||||
@ -65,7 +68,7 @@ fn snap_and_restore() {
|
|||||||
block_hashes: Vec::new(),
|
block_hashes: Vec::new(),
|
||||||
state_root: state_root,
|
state_root: state_root,
|
||||||
block_number: 1000,
|
block_number: 1000,
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
|
|
||||||
let db_path = tempdir.path().join("db");
|
let db_path = tempdir.path().join("db");
|
||||||
@ -84,7 +87,7 @@ fn snap_and_restore() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assert_eq!(rebuilder.state_root(), state_root);
|
assert_eq!(rebuilder.state_root(), state_root);
|
||||||
rebuilder.finalize(1000, H256::default()).unwrap();
|
rebuilder.finalize(1000, H256::zero()).unwrap();
|
||||||
|
|
||||||
new_db
|
new_db
|
||||||
};
|
};
|
||||||
@ -157,7 +160,7 @@ fn get_code_from_prev_chunk() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn checks_flag() {
|
fn checks_flag() {
|
||||||
let mut producer = StateProducer::new();
|
let mut producer = StateProducer::new();
|
||||||
let mut rng = XorShiftRng::from_seed([5, 6, 7, 8]);
|
let mut rng = XorShiftRng::from_seed(RNG_SEED);
|
||||||
let mut old_db = journaldb::new_memory_db();
|
let mut old_db = journaldb::new_memory_db();
|
||||||
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
||||||
|
|
||||||
@ -179,7 +182,7 @@ fn checks_flag() {
|
|||||||
block_hashes: Vec::new(),
|
block_hashes: Vec::new(),
|
||||||
state_root: state_root,
|
state_root: state_root,
|
||||||
block_number: 0,
|
block_number: 0,
|
||||||
block_hash: H256::default(),
|
block_hash: H256::zero(),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
|
|
||||||
let tempdir = TempDir::new("").unwrap();
|
let tempdir = TempDir::new("").unwrap();
|
||||||
|
@ -123,7 +123,7 @@ mod tests {
|
|||||||
|
|
||||||
use client::{ChainNotify, NewBlocks, ChainRoute};
|
use client::{ChainNotify, NewBlocks, ChainRoute};
|
||||||
|
|
||||||
use ethereum_types::{H256, U256};
|
use ethereum_types::{H256, U256, BigEndianHash};
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@ -151,7 +151,7 @@ mod tests {
|
|||||||
fn harness(numbers: Vec<u64>, period: u64, history: u64, expected: Option<u64>) {
|
fn harness(numbers: Vec<u64>, period: u64, history: u64, expected: Option<u64>) {
|
||||||
const DURATION_ZERO: Duration = Duration::from_millis(0);
|
const DURATION_ZERO: Duration = Duration::from_millis(0);
|
||||||
|
|
||||||
let hashes: Vec<_> = numbers.clone().into_iter().map(|x| H256::from(U256::from(x))).collect();
|
let hashes: Vec<_> = numbers.clone().into_iter().map(|x| BigEndianHash::from_uint(&U256::from(x))).collect();
|
||||||
let map = hashes.clone().into_iter().zip(numbers).collect();
|
let map = hashes.clone().into_iter().zip(numbers).collect();
|
||||||
|
|
||||||
let watcher = Watcher {
|
let watcher = Watcher {
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user