Merge branch 'master' into ui-2

This commit is contained in:
Jaco Greeff 2017-07-03 09:56:54 +02:00
commit 9f8467aa80
71 changed files with 332 additions and 221 deletions

18
Cargo.lock generated
View File

@ -317,7 +317,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "elastic-array"
version = "0.8.0"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"heapsize 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
@ -635,7 +635,7 @@ version = "1.7.0"
dependencies = [
"ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.103 (registry+https://github.com/rust-lang/crates.io-index)",
"elastic-array 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"elastic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"eth-secp256k1 0.5.6 (git+https://github.com/paritytech/rust-secp256k1)",
"ethcore-bigint 0.1.3",
@ -672,6 +672,7 @@ dependencies = [
"ethcore-bigint 0.1.3",
"ethkey 0.2.0",
"rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"subtle 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"tiny-keccak 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -2129,7 +2130,7 @@ name = "rlp"
version = "0.2.0"
dependencies = [
"byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"elastic-array 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"elastic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-bigint 0.1.3",
"lazy_static 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)",
@ -2461,6 +2462,14 @@ name = "strsim"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "subtle"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-traits 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "syn"
version = "0.11.11"
@ -2942,7 +2951,7 @@ dependencies = [
"checksum docopt 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ab32ea6e284d87987066f21a9e809a73c14720571ef34516f0890b3d355ccfd8"
"checksum dtoa 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5edd69c67b2f8e0911629b7e6b8a34cb3956613cd7c6e6414966dee349c2db4f"
"checksum either 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3d2b503c86dad62aaf414ecf2b8c527439abedb3f8d812537f0b12bfd6f32a91"
"checksum elastic-array 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "561b1b1bb58e6d9212b75a28cca442f8a87cceb35cb1b6d6f39f5df5346a9160"
"checksum elastic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "258ff6a9a94f648d0379dbd79110e057edbb53eb85cc237e33eadf8e5a30df85"
"checksum env_logger 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e3856f1697098606fc6cb97a93de88ca3f3bc35bb878c725920e6e82ecf05e83"
"checksum eth-secp256k1 0.5.6 (git+https://github.com/paritytech/rust-secp256k1)" = "<none>"
"checksum ethabi 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "65f71b9ac0b0f8e6230d32dbf5acf7c2c61334af1148175d0a7e72b14c3d475e"
@ -3100,6 +3109,7 @@ dependencies = [
"checksum spmc 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "93bdab61c1a413e591c4d17388ffa859eaff2df27f1e13a5ec8b716700605adf"
"checksum stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "15132e0e364248108c5e2c02e3ab539be8d6f5d52a01ca9bbf27ed657316f02b"
"checksum strsim 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d15c810519a91cf877e7e36e63fe068815c678181439f2f29e2562147c3694"
"checksum subtle 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b811576c12506ff3f6da145585dc833edc32ee34c9fc021127d90e8134cc05c"
"checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad"
"checksum synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6"
"checksum syntex 0.58.0 (registry+https://github.com/rust-lang/crates.io-index)" = "35f3cc9d446323ef8fefad933b65cd6de271d29fa14a2e9d036a084770c6d6d5"

View File

@ -126,7 +126,7 @@ pub fn compute_root<I>(cht_num: u64, iterable: I) -> Option<H256>
let start_num = start_number(cht_num) as usize;
for (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() {
v.push((key!(i + start_num).to_vec(), val!(h, td).to_vec()))
v.push((key!(i + start_num).into_vec(), val!(h, td).into_vec()))
}
if v.len() == SIZE as usize {

View File

@ -388,7 +388,7 @@ impl HeaderChain {
None => {
match self.db.get(self.col, &hash) {
Ok(db_value) => {
db_value.map(|x| x.to_vec()).map(encoded::Header::new)
db_value.map(|x| x.into_vec()).map(encoded::Header::new)
.and_then(|header| {
cache.insert_block_header(hash.clone(), header.clone());
Some(header)

View File

@ -137,7 +137,7 @@ impl Provider for TestProvider {
fn storage_proof(&self, req: request::CompleteStorageRequest) -> Option<request::StorageResponse> {
Some(StorageResponse {
proof: vec![::rlp::encode(&req.key_hash).to_vec()],
proof: vec![::rlp::encode(&req.key_hash).into_vec()],
value: req.key_hash | req.address_hash,
})
}

View File

@ -738,7 +738,7 @@ impl BlockReceipts {
/// Check a response with receipts against the stored header.
pub fn check_response(&self, cache: &Mutex<::cache::Cache>, receipts: &[Receipt]) -> Result<Vec<Receipt>, Error> {
let receipts_root = self.0.as_ref()?.receipts_root();
let found_root = ::util::triehash::ordered_trie_root(receipts.iter().map(|r| ::rlp::encode(r).to_vec()));
let found_root = ::util::triehash::ordered_trie_root(receipts.iter().map(|r| ::rlp::encode(r).into_vec()));
match receipts_root == found_root {
true => {
@ -902,7 +902,7 @@ mod tests {
header.set_number(10_000);
header.set_extra_data(b"test_header".to_vec());
let hash = header.hash();
let raw_header = encoded::Header::new(::rlp::encode(&header).to_vec());
let raw_header = encoded::Header::new(::rlp::encode(&header).into_vec());
let cache = Mutex::new(make_cache());
assert!(HeaderByHash(hash.into()).check_response(&cache, &hash.into(), &[raw_header]).is_ok())
@ -916,10 +916,10 @@ mod tests {
let mut body_stream = RlpStream::new_list(2);
body_stream.begin_list(0).begin_list(0);
let req = Body(encoded::Header::new(::rlp::encode(&header).to_vec()).into());
let req = Body(encoded::Header::new(::rlp::encode(&header).into_vec()).into());
let cache = Mutex::new(make_cache());
let response = encoded::Body::new(body_stream.drain().to_vec());
let response = encoded::Body::new(body_stream.drain().into_vec());
assert!(req.check_response(&cache, &response).is_ok())
}
@ -934,12 +934,12 @@ mod tests {
let mut header = Header::new();
let receipts_root = ::util::triehash::ordered_trie_root(
receipts.iter().map(|x| ::rlp::encode(x).to_vec())
receipts.iter().map(|x| ::rlp::encode(x).into_vec())
);
header.set_receipts_root(receipts_root);
let req = BlockReceipts(encoded::Header::new(::rlp::encode(&header).to_vec()).into());
let req = BlockReceipts(encoded::Header::new(::rlp::encode(&header).into_vec()).into());
let cache = Mutex::new(make_cache());
assert!(req.check_response(&cache, &receipts).is_ok())
@ -987,7 +987,7 @@ mod tests {
header.set_state_root(root.clone());
let req = Account {
header: encoded::Header::new(::rlp::encode(&header).to_vec()).into(),
header: encoded::Header::new(::rlp::encode(&header).into_vec()).into(),
address: addr,
};
@ -1001,7 +1001,7 @@ mod tests {
let code_hash = ::util::Hashable::sha3(&code);
let header = Header::new();
let req = Code {
header: encoded::Header::new(::rlp::encode(&header).to_vec()).into(),
header: encoded::Header::new(::rlp::encode(&header).into_vec()).into(),
code_hash: code_hash.into(),
};

View File

@ -1673,7 +1673,7 @@ mod tests {
let full_req = Request::Headers(req.clone());
let res = HeadersResponse {
headers: vec![
::ethcore::encoded::Header::new(::rlp::encode(&Header::default()).to_vec())
::ethcore::encoded::Header::new(::rlp::encode(&Header::default()).into_vec())
]
};
let full_res = Response::Headers(res.clone());

View File

@ -382,11 +382,11 @@ impl<'x> OpenBlock<'x> {
if let Err(e) = s.block.state.commit() {
warn!("Encountered error on state commit: {}", e);
}
s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().to_vec())));
s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().into_vec())));
let uncle_bytes = s.block.uncles.iter().fold(RlpStream::new_list(s.block.uncles.len()), |mut s, u| {s.append_raw(&u.rlp(Seal::With), 1); s} ).out();
s.block.header.set_uncles_hash(uncle_bytes.sha3());
s.block.header.set_state_root(s.block.state.root().clone());
s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().to_vec())));
s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().into_vec())));
s.block.header.set_log_bloom(s.block.receipts.iter().fold(LogBloom::zero(), |mut b, r| {b = &b | &r.log_bloom; b})); //TODO: use |= operator
s.block.header.set_gas_used(s.block.receipts.last().map_or(U256::zero(), |r| r.gas_used));
@ -410,14 +410,14 @@ impl<'x> OpenBlock<'x> {
warn!("Encountered error on state commit: {}", e);
}
if s.block.header.transactions_root().is_zero() || s.block.header.transactions_root() == &SHA3_NULL_RLP {
s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().to_vec())));
s.block.header.set_transactions_root(ordered_trie_root(s.block.transactions.iter().map(|e| e.rlp_bytes().into_vec())));
}
let uncle_bytes = s.block.uncles.iter().fold(RlpStream::new_list(s.block.uncles.len()), |mut s, u| {s.append_raw(&u.rlp(Seal::With), 1); s} ).out();
if s.block.header.uncles_hash().is_zero() {
s.block.header.set_uncles_hash(uncle_bytes.sha3());
}
if s.block.header.receipts_root().is_zero() || s.block.header.receipts_root() == &SHA3_NULL_RLP {
s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().to_vec())));
s.block.header.set_receipts_root(ordered_trie_root(s.block.receipts.iter().map(|r| r.rlp_bytes().into_vec())));
}
s.block.header.set_state_root(s.block.state.root().clone());
@ -510,7 +510,7 @@ impl LockedBlock {
for receipt in &mut block.block.receipts {
receipt.state_root = None;
}
block.block.header.set_receipts_root(ordered_trie_root(block.block.receipts.iter().map(|r| r.rlp_bytes().to_vec())));
block.block.header.set_receipts_root(ordered_trie_root(block.block.receipts.iter().map(|r| r.rlp_bytes().into_vec())));
block
}
}

View File

@ -266,7 +266,7 @@ impl BlockProvider for BlockChain {
let result = match opt {
Some(b) => {
let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).to_vec();
let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).into_vec();
let mut write = self.block_headers.write();
write.insert(hash.clone(), bytes.clone());
Some(encoded::Header::new(bytes))
@ -302,7 +302,7 @@ impl BlockProvider for BlockChain {
let result = match opt {
Some(b) => {
let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).to_vec();
let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).into_vec();
let mut write = self.block_bodies.write();
write.insert(hash.clone(), bytes.clone());
Some(encoded::Body::new(bytes))
@ -536,7 +536,7 @@ impl BlockChain {
let best_block_rlp = bc.block(&best_block_hash).unwrap().into_inner();
let best_block_timestamp = BlockView::new(&best_block_rlp).header().timestamp();
let raw_first = bc.db.get(db::COL_EXTRA, b"first").unwrap().map(|v| v.to_vec());
let raw_first = bc.db.get(db::COL_EXTRA, b"first").unwrap().map(|v| v.into_vec());
let mut best_ancient = bc.db.get(db::COL_EXTRA, b"ancient").unwrap().map(|h| H256::from_slice(&h));
let best_ancient_number;
if best_ancient.is_none() && best_block_number > 1 && bc.block_hash(1).is_none() {

View File

@ -67,6 +67,6 @@ impl WithTransaction for Block {
impl CompleteBlock for Block {
fn complete(mut self, parent_hash: H256) -> Bytes {
self.header.set_parent_hash(parent_hash);
encode(&self).to_vec()
encode(&self).into_vec()
}
}

View File

@ -1443,7 +1443,7 @@ impl BlockChainClient for Client {
}
fn block_receipts(&self, hash: &H256) -> Option<Bytes> {
self.chain.read().block_receipts(hash).map(|receipts| ::rlp::encode(&receipts).to_vec())
self.chain.read().block_receipts(hash).map(|receipts| ::rlp::encode(&receipts).into_vec())
}
fn import_block(&self, bytes: Bytes) -> Result<H256, BlockImportError> {

View File

@ -517,7 +517,7 @@ impl Engine for AuthorityRound {
// only issue the seal if we were the first to reach the compare_and_swap.
if !self.proposed.compare_and_swap(false, true, AtomicOrdering::SeqCst) {
return Seal::Regular(vec![encode(&step).to_vec(), encode(&(&H520::from(signature) as &[u8])).to_vec()]);
return Seal::Regular(vec![encode(&step).into_vec(), encode(&(&H520::from(signature) as &[u8])).into_vec()]);
}
} else {
warn!(target: "engine", "generate_seal: FAIL: Accounts secret key unavailable.");
@ -880,7 +880,7 @@ mod tests {
fn can_do_signature_verification_fail() {
let engine = Spec::new_test_round().engine;
let mut header: Header = Header::default();
header.set_seal(vec![encode(&H520::default()).to_vec()]);
header.set_seal(vec![encode(&H520::default()).into_vec()]);
let verify_result = engine.verify_block_external(&header, None);
assert!(verify_result.is_err());
@ -923,7 +923,7 @@ mod tests {
let tap = AccountProvider::transient_provider();
let addr = tap.insert_account("0".sha3().into(), "0").unwrap();
let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&0usize).to_vec()]);
parent_header.set_seal(vec![encode(&0usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap());
let mut header: Header = Header::default();
header.set_number(1);
@ -935,10 +935,10 @@ mod tests {
let signature = tap.sign(addr, Some("0".into()), header.bare_hash()).unwrap();
// Two validators.
// Spec starts with step 2.
header.set_seal(vec![encode(&2usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&2usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
assert!(engine.verify_block_external(&header, None).is_err());
header.set_seal(vec![encode(&1usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&1usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
assert!(engine.verify_block_external(&header, None).is_ok());
}
@ -949,7 +949,7 @@ mod tests {
let addr = tap.insert_account("0".sha3().into(), "0").unwrap();
let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&0usize).to_vec()]);
parent_header.set_seal(vec![encode(&0usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap());
let mut header: Header = Header::default();
header.set_number(1);
@ -961,10 +961,10 @@ mod tests {
let signature = tap.sign(addr, Some("0".into()), header.bare_hash()).unwrap();
// Two validators.
// Spec starts with step 2.
header.set_seal(vec![encode(&1usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&1usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
assert!(engine.verify_block_external(&header, None).is_ok());
header.set_seal(vec![encode(&5usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&5usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
assert!(engine.verify_block_external(&header, None).is_err());
}
@ -975,7 +975,7 @@ mod tests {
let addr = tap.insert_account("0".sha3().into(), "0").unwrap();
let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&4usize).to_vec()]);
parent_header.set_seal(vec![encode(&4usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap());
let mut header: Header = Header::default();
header.set_number(1);
@ -987,9 +987,9 @@ mod tests {
let signature = tap.sign(addr, Some("0".into()), header.bare_hash()).unwrap();
// Two validators.
// Spec starts with step 2.
header.set_seal(vec![encode(&5usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&5usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
header.set_seal(vec![encode(&3usize).to_vec(), encode(&(&*signature as &[u8])).to_vec()]);
header.set_seal(vec![encode(&3usize).into_vec(), encode(&(&*signature as &[u8])).into_vec()]);
assert!(engine.verify_block_family(&header, &parent_header, None).is_err());
}
@ -1011,12 +1011,12 @@ mod tests {
let aura = AuthorityRound::new(Default::default(), params, Default::default()).unwrap();
let mut parent_header: Header = Header::default();
parent_header.set_seal(vec![encode(&1usize).to_vec()]);
parent_header.set_seal(vec![encode(&1usize).into_vec()]);
parent_header.set_gas_limit(U256::from_str("222222").unwrap());
let mut header: Header = Header::default();
header.set_number(1);
header.set_gas_limit(U256::from_str("222222").unwrap());
header.set_seal(vec![encode(&3usize).to_vec()]);
header.set_seal(vec![encode(&3usize).into_vec()]);
assert!(aura.verify_block_family(&header, &parent_header, None).is_ok());
assert_eq!(last_benign.load(AtomicOrdering::SeqCst), 1);

View File

@ -139,7 +139,7 @@ impl Engine for BasicAuthority {
if self.validators.contains(header.parent_hash(), author) {
// account should be pernamently unlocked, otherwise sealing will fail
if let Ok(signature) = self.signer.sign(header.bare_hash()) {
return Seal::Regular(vec![::rlp::encode(&(&H520::from(signature) as &[u8])).to_vec()]);
return Seal::Regular(vec![::rlp::encode(&(&H520::from(signature) as &[u8])).into_vec()]);
} else {
trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable");
}
@ -301,7 +301,7 @@ mod tests {
fn can_do_signature_verification_fail() {
let engine = new_test_authority().engine;
let mut header: Header = Header::default();
header.set_seal(vec![::rlp::encode(&H520::default()).to_vec()]);
header.set_seal(vec![::rlp::encode(&H520::default()).into_vec()]);
let verify_result = engine.verify_block_family(&header, &Default::default(), None);
assert!(verify_result.is_err());

View File

@ -93,7 +93,7 @@ mod tests {
assert!(engine.verify_block_basic(&header, None).is_ok());
header.set_seal(vec![::rlp::encode(&H520::default()).to_vec()]);
header.set_seal(vec![::rlp::encode(&H520::default()).into_vec()]);
assert!(engine.verify_block_unordered(&header, None).is_ok());
}

View File

@ -228,7 +228,7 @@ mod tests {
},
block_hash: Some("1".sha3())
};
let raw_rlp = ::rlp::encode(&message).to_vec();
let raw_rlp = ::rlp::encode(&message).into_vec();
let rlp = Rlp::new(&raw_rlp);
assert_eq!(message, rlp.as_val());
@ -265,8 +265,8 @@ mod tests {
fn proposal_message() {
let mut header = Header::default();
let seal = vec![
::rlp::encode(&0u8).to_vec(),
::rlp::encode(&H520::default()).to_vec(),
::rlp::encode(&0u8).into_vec(),
::rlp::encode(&H520::default()).into_vec(),
Vec::new()
];

View File

@ -342,9 +342,9 @@ impl Tendermint {
let precommits = self.votes.round_signatures(vote_step, &bh);
trace!(target: "engine", "Collected seal: {:?}", precommits);
let seal = vec![
::rlp::encode(&vote_step.view).to_vec(),
::rlp::encode(&vote_step.view).into_vec(),
::rlp::NULL_RLP.to_vec(),
::rlp::encode_list(&precommits).to_vec()
::rlp::encode_list(&precommits).into_vec()
];
self.submit_seal(bh, seal);
self.votes.throw_out_old(&vote_step);
@ -446,8 +446,8 @@ impl Engine for Tendermint {
*self.proposal.write() = bh;
*self.proposal_parent.write() = header.parent_hash().clone();
Seal::Proposal(vec![
::rlp::encode(&view).to_vec(),
::rlp::encode(&signature).to_vec(),
::rlp::encode(&view).into_vec(),
::rlp::encode(&signature).into_vec(),
::rlp::EMPTY_LIST_RLP.to_vec()
])
} else {
@ -467,7 +467,7 @@ impl Engine for Tendermint {
self.broadcast_message(rlp.as_raw().to_vec());
if let Some(double) = self.votes.vote(message.clone(), &sender) {
let height = message.vote_step.height as BlockNumber;
self.validators.report_malicious(&sender, height, height, ::rlp::encode(&double).to_vec());
self.validators.report_malicious(&sender, height, height, ::rlp::encode(&double).into_vec());
return Err(EngineError::DoubleVote(sender).into());
}
trace!(target: "engine", "Handling a valid {:?} from {}.", message, sender);
@ -696,8 +696,8 @@ mod tests {
let vote_info = message_info_rlp(&VoteStep::new(header.number() as Height, view, Step::Propose), Some(header.bare_hash()));
let signature = tap.sign(*author, None, vote_info.sha3()).unwrap();
vec![
::rlp::encode(&view).to_vec(),
::rlp::encode(&H520::from(signature)).to_vec(),
::rlp::encode(&view).into_vec(),
::rlp::encode(&H520::from(signature)).into_vec(),
::rlp::EMPTY_LIST_RLP.to_vec()
]
}
@ -813,7 +813,7 @@ mod tests {
let signature1 = tap.sign(proposer, None, vote_info.sha3()).unwrap();
seal[1] = ::rlp::NULL_RLP.to_vec();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone())]).to_vec();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone())]).into_vec();
header.set_seal(seal.clone());
// One good signature is not enough.
@ -825,7 +825,7 @@ mod tests {
let voter = insert_and_unlock(&tap, "0");
let signature0 = tap.sign(voter, None, vote_info.sha3()).unwrap();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone()), H520::from(signature0.clone())]).to_vec();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1.clone()), H520::from(signature0.clone())]).into_vec();
header.set_seal(seal.clone());
assert!(engine.verify_block_family(&header, &parent_header, None).is_ok());
@ -833,7 +833,7 @@ mod tests {
let bad_voter = insert_and_unlock(&tap, "101");
let bad_signature = tap.sign(bad_voter, None, vote_info.sha3()).unwrap();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1), H520::from(bad_signature)]).to_vec();
seal[2] = ::rlp::encode_list(&vec![H520::from(signature1), H520::from(bad_signature)]).into_vec();
header.set_seal(seal);
// One good and one bad signature.

View File

@ -161,7 +161,7 @@ mod tests {
client.miner().set_engine_signer(v1, "".into()).unwrap();
let mut header = Header::default();
let seal = vec![encode(&5u8).to_vec(), encode(&(&H520::default() as &[u8])).to_vec()];
let seal = vec![encode(&5u8).into_vec(), encode(&(&H520::default() as &[u8])).into_vec()];
header.set_seal(seal);
header.set_author(v1);
header.set_number(2);

View File

@ -80,7 +80,7 @@ fn decode_first_proof(rlp: &UntrustedRlp) -> Result<(Header, Vec<DBValue>), ::er
fn encode_proof(header: &Header, receipts: &[Receipt]) -> Bytes {
let mut stream = RlpStream::new_list(2);
stream.append(header).append_list(receipts);
stream.drain().to_vec()
stream.drain().into_vec()
}
fn decode_proof(rlp: &UntrustedRlp) -> Result<(Header, Vec<Receipt>), ::error::Error> {

View File

@ -540,7 +540,7 @@ impl Header {
/// Set the nonce and mix hash fields of the header.
pub fn set_nonce_and_mix_hash(&mut self, nonce: &H64, mix_hash: &H256) {
self.set_seal(vec![rlp::encode(mix_hash).to_vec(), rlp::encode(nonce).to_vec()]);
self.set_seal(vec![rlp::encode(mix_hash).into_vec(), rlp::encode(nonce).into_vec()]);
}
}
@ -622,7 +622,7 @@ mod tests {
fn can_do_difficulty_verification_fail() {
let engine = new_morden().engine;
let mut header: Header = Header::default();
header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
header.set_seal(vec![rlp::encode(&H256::zero()).into_vec(), rlp::encode(&H64::zero()).into_vec()]);
let verify_result = engine.verify_block_basic(&header, None);
@ -637,7 +637,7 @@ mod tests {
fn can_do_proof_of_work_verification_fail() {
let engine = new_morden().engine;
let mut header: Header = Header::default();
header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
header.set_seal(vec![rlp::encode(&H256::zero()).into_vec(), rlp::encode(&H64::zero()).into_vec()]);
header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());
let verify_result = engine.verify_block_basic(&header, None);
@ -667,7 +667,7 @@ mod tests {
fn can_do_seal256_verification_fail() {
let engine = new_morden().engine;
let mut header: Header = Header::default();
header.set_seal(vec![rlp::encode(&H256::zero()).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
header.set_seal(vec![rlp::encode(&H256::zero()).into_vec(), rlp::encode(&H64::zero()).into_vec()]);
let verify_result = engine.verify_block_unordered(&header, None);
match verify_result {
@ -681,7 +681,7 @@ mod tests {
fn can_do_proof_of_work_unordered_verification_fail() {
let engine = new_morden().engine;
let mut header: Header = Header::default();
header.set_seal(vec![rlp::encode(&H256::from("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d")).to_vec(), rlp::encode(&H64::zero()).to_vec()]);
header.set_seal(vec![rlp::encode(&H256::from("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d")).into_vec(), rlp::encode(&H64::zero()).into_vec()]);
header.set_difficulty(U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffaaaaaaaaaaaaaaaaaaaa").unwrap());
let verify_result = engine.verify_block_unordered(&header, None);

View File

@ -113,7 +113,7 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
let mut informant = informant::EvmInformant::new(ext.depth());
let code = &params.code.as_ref().expect("exec always called with code; qed");
let valid_jump_destinations = self.cache.jump_destinations(&params.code_hash, code);
let mut valid_jump_destinations = None;
let mut gasometer = Gasometer::<Cost>::new(Cost::from_u256(params.gas)?);
let mut stack = VecStack::with_capacity(ext.schedule().stack_limit, U256::zero());
@ -162,7 +162,11 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
// Advance
match result {
InstructionResult::JumpToPosition(position) => {
let pos = self.verify_jump(position, &valid_jump_destinations)?;
if valid_jump_destinations.is_none() {
valid_jump_destinations = Some(self.cache.jump_destinations(&params.code_hash, code));
}
let jump_destinations = valid_jump_destinations.as_ref().expect("jump_destinations are initialized on first jump; qed");
let pos = self.verify_jump(position, jump_destinations)?;
reader.position = pos;
},
InstructionResult::StopExecutionNeedsReturn {gas, init_off, init_size, apply} => {

View File

@ -329,7 +329,7 @@ mod tests {
let header_rlp = "f901f9a0d405da4e66f1445d455195229624e133f5baafe72b5cf7b3c36c12c8146e98b7a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a05fb2b4bfdef7b314451cb138a534d225c922fc0e5fbe25e451142732c3e25c25a088d2ec6b9860aae1a2c3b299f72b6a5d70d7f7ba4722c78f2c49ba96273c2158a007c6fdfa8eea7e86b81f5b0fc0f78f90cc19f4aa60d323151e0cac660199e9a1b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302008003832fefba82524d84568e932a80a0a0349d8c3df71f1a48a9df7d03fd5f14aeee7d91332c009ecaff0a71ead405bd88ab4e252a7e8c2a23".from_hex().unwrap();
let header: Header = rlp::decode(&header_rlp);
let encoded_header = rlp::encode(&header).to_vec();
let encoded_header = rlp::encode(&header).into_vec();
assert_eq!(header_rlp, encoded_header);
}

View File

@ -32,6 +32,6 @@ impl SimpleMigration for V8 {
fn simple_migrate(&mut self, key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)> {
self.0.tick();
Some((key,UntrustedRlp::new(&value).compress(RlpType::Blocks).to_vec()))
Some((key,UntrustedRlp::new(&value).compress(RlpType::Blocks).into_vec()))
}
}

View File

@ -39,8 +39,7 @@ impl SimpleMigration for ToV6 {
fn version(&self) -> u32 { 6 }
fn simple_migrate(&mut self, key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)> {
fn simple_migrate(&mut self, mut key: Vec<u8>, value: Vec<u8>) -> Option<(Vec<u8>, Vec<u8>)> {
//// at this version all extras keys are 33 bytes long.
if key.len() == 33 {
// block details key changes:
@ -72,19 +71,21 @@ impl SimpleMigration for ToV6 {
// - index is moved to the front
// - index is changed 4 -> 3
if key[32] == 4 {
key.reverse();
// i have no idea why it was reversed
let reverse = key.into_iter().rev().collect::<Vec<_>>();
let mut result = [0u8; 6];
// new extras index is 3
result[0] = 3;
// 9th (+ prefix) byte was the level. Now it's second.
result[1] = reverse[9];
result[2] = reverse[4];
result[3] = reverse[3];
result[4] = reverse[2];
result[5] = reverse[1];
let reverse = key;
let result = vec![
// new extras index is 3
3,
// 9th (+ prefix) byte was the level. Now it's second.
reverse[9],
reverse[4],
reverse[3],
reverse[2],
reverse[1],
];
return Some((result.to_vec(), value));
return Some((result, value));
}
// blocks receipts key changes:

View File

@ -153,7 +153,7 @@ impl OverlayRecentV7 {
// and commit the altered entries.
fn migrate_journal(&self, source: Arc<Database>, mut batch: Batch, dest: &mut Database) -> Result<(), Error> {
if let Some(val) = source.get(None, V7_LATEST_ERA_KEY).map_err(Error::Custom)? {
batch.insert(V7_LATEST_ERA_KEY.into(), val.clone().to_vec(), dest)?;
batch.insert(V7_LATEST_ERA_KEY.into(), val.clone().into_vec(), dest)?;
let mut era = decode::<u64>(&val);
loop {

View File

@ -104,7 +104,7 @@ impl Migration for ToV10 {
let mut batch = Batch::new(config, col);
for (key, value) in source.iter(col).into_iter().flat_map(|inner| inner) {
self.progress.tick();
batch.insert(key.to_vec(), value.to_vec(), dest)?;
batch.insert(key.into_vec(), value.into_vec(), dest)?;
}
batch.commit(dest)?;

View File

@ -62,17 +62,17 @@ impl Migration for ToV9 {
self.progress.tick();
match self.extract {
Extract::Header => {
batch.insert(key.to_vec(), Rlp::new(&value).at(0).as_raw().to_vec(), dest)?
batch.insert(key.into_vec(), Rlp::new(&value).at(0).as_raw().to_vec(), dest)?
},
Extract::Body => {
let mut body = RlpStream::new_list(2);
let block_rlp = Rlp::new(&value);
body.append_raw(block_rlp.at(1).as_raw(), 1);
body.append_raw(block_rlp.at(2).as_raw(), 1);
batch.insert(key.to_vec(), body.out(), dest)?
batch.insert(key.into_vec(), body.out(), dest)?
},
Extract::All => {
batch.insert(key.to_vec(), value.to_vec(), dest)?
batch.insert(key.into_vec(), value.into_vec(), dest)?
}
}
}

View File

@ -145,7 +145,7 @@ impl JobDispatcher for StratumJobDispatcher {
);
self.with_core_void(|client, miner| {
let seal = vec![encode(&payload.mix_hash).to_vec(), encode(&payload.nonce).to_vec()];
let seal = vec![encode(&payload.mix_hash).into_vec(), encode(&payload.nonce).into_vec()];
if let Err(e) = miner.submit_seal(&*client, payload.pow_hash, seal) {
warn!(target: "stratum", "submit_seal error: {:?}", e);
};

View File

@ -165,7 +165,7 @@ struct TransactionOrder {
/// Gas usage priority factor. Usage depends on strategy.
/// Represents the linear increment in required gas price for heavy transactions.
///
/// High gas limit + Low gas price = Low priority
/// High gas limit + Low gas price = Very Low priority
/// High gas limit + High gas price = High priority
gas_factor: U256,
/// Gas (limit) of the transaction. Usage depends on strategy.
@ -175,6 +175,8 @@ struct TransactionOrder {
strategy: PrioritizationStrategy,
/// Hash to identify associated transaction
hash: H256,
/// Incremental id assigned when transaction is inserted to the queue.
insertion_id: u64,
/// Origin of the transaction
origin: TransactionOrigin,
/// Penalties
@ -193,6 +195,7 @@ impl TransactionOrder {
gas_factor: factor,
strategy: strategy,
hash: tx.hash(),
insertion_id: tx.insertion_id,
origin: tx.origin,
penalties: 0,
}
@ -262,8 +265,8 @@ impl Ord for TransactionOrder {
return b.gas_price.cmp(&self.gas_price);
}
// Compare hashes
self.hash.cmp(&b.hash)
// Lastly compare insertion_id
self.insertion_id.cmp(&b.insertion_id)
}
}
@ -274,19 +277,28 @@ struct VerifiedTransaction {
transaction: SignedTransaction,
/// Transaction origin.
origin: TransactionOrigin,
/// Insertion time
insertion_time: QueuingInstant,
/// Delay until specified condition is met.
condition: Option<Condition>,
/// Insertion time
insertion_time: QueuingInstant,
/// ID assigned upon insertion, should be unique.
insertion_id: u64,
}
impl VerifiedTransaction {
fn new(transaction: SignedTransaction, origin: TransactionOrigin, time: QueuingInstant, condition: Option<Condition>) -> Self {
fn new(
transaction: SignedTransaction,
origin: TransactionOrigin,
condition: Option<Condition>,
insertion_time: QueuingInstant,
insertion_id: u64,
) -> Self {
VerifiedTransaction {
transaction: transaction,
origin: origin,
insertion_time: time,
condition: condition,
transaction,
origin,
condition,
insertion_time,
insertion_id,
}
}
@ -486,6 +498,9 @@ pub struct AccountDetails {
/// Transactions with `gas > (gas_limit + gas_limit * Factor(in percents))` are not imported to the queue.
const GAS_LIMIT_HYSTERESIS: usize = 200; // (100/GAS_LIMIT_HYSTERESIS) %
/// Transaction with the same (sender, nonce) can be replaced only if
/// `new_gas_price > old_gas_price + old_gas_price >> SHIFT`
const GAS_PRICE_BUMP_SHIFT: usize = 3; // 2 = 25%, 3 = 12.5%, 4 = 6.25%
/// Describes the strategy used to prioritize transactions in the queue.
#[cfg_attr(feature="dev", allow(enum_variant_names))]
@ -557,6 +572,8 @@ pub struct TransactionQueue {
last_nonces: HashMap<Address, U256>,
/// List of local transactions and their statuses.
local_transactions: LocalTransactionsList,
/// Next id that should be assigned to a transaction imported to the queue.
next_transaction_id: u64,
}
impl Default for TransactionQueue {
@ -600,6 +617,7 @@ impl TransactionQueue {
by_hash: HashMap::new(),
last_nonces: HashMap::new(),
local_transactions: LocalTransactionsList::default(),
next_transaction_id: 0,
}
}
@ -824,7 +842,9 @@ impl TransactionQueue {
}
tx.check_low_s()?;
// No invalid transactions beyond this point.
let vtx = VerifiedTransaction::new(tx, origin, time, condition);
let id = self.next_transaction_id;
self.next_transaction_id += 1;
let vtx = VerifiedTransaction::new(tx, origin, condition, time, id);
let r = self.import_tx(vtx, client_account.nonce).map_err(Error::Transaction);
assert_eq!(self.future.by_priority.len() + self.current.by_priority.len(), self.by_hash.len());
r
@ -1352,16 +1372,19 @@ impl TransactionQueue {
// There was already transaction in queue. Let's check which one should stay
let old_hash = old.hash;
let new_hash = order.hash;
let old_fee = old.gas_price;
let new_fee = order.gas_price;
if old_fee.cmp(&new_fee) == Ordering::Greater {
let old_gas_price = old.gas_price;
let new_gas_price = order.gas_price;
let min_required_gas_price = old_gas_price + (old_gas_price >> GAS_PRICE_BUMP_SHIFT);
if min_required_gas_price > new_gas_price {
trace!(target: "txqueue", "Didn't insert transaction because gas price was too low: {:?} ({:?} stays in the queue)", order.hash, old.hash);
// Put back old transaction since it has greater priority (higher gas_price)
set.insert(address, nonce, old);
// and remove new one
let order = by_hash.remove(&order.hash).expect("The hash has been just inserted and no other line is altering `by_hash`.");
if order.origin.is_local() {
local.mark_replaced(order.transaction, old_fee, old_hash);
local.mark_replaced(order.transaction, old_gas_price, old_hash);
}
false
} else {
@ -1369,7 +1392,7 @@ impl TransactionQueue {
// Make sure we remove old transaction entirely
let old = by_hash.remove(&old.hash).expect("The hash is coming from `future` so it has to be in `by_hash`.");
if old.origin.is_local() {
local.mark_replaced(old.transaction, new_fee, new_hash);
local.mark_replaced(old.transaction, new_gas_price, new_hash);
}
true
}
@ -1611,12 +1634,12 @@ pub mod test {
gas_limit: !U256::zero(),
};
let (tx1, tx2) = new_tx_pair_default(1.into(), 0.into());
let tx1 = VerifiedTransaction::new(tx1, TransactionOrigin::External, 0, None);
let tx2 = VerifiedTransaction::new(tx2, TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx1, TransactionOrigin::External, None, 0, 0);
let tx2 = VerifiedTransaction::new(tx2, TransactionOrigin::External, None, 0, 1);
let mut by_hash = {
let mut x = HashMap::new();
let tx1 = VerifiedTransaction::new(tx1.transaction.clone(), TransactionOrigin::External, 0, None);
let tx2 = VerifiedTransaction::new(tx2.transaction.clone(), TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx1.transaction.clone(), TransactionOrigin::External, None, 0, 0);
let tx2 = VerifiedTransaction::new(tx2.transaction.clone(), TransactionOrigin::External, None, 0, 1);
x.insert(tx1.hash(), tx1);
x.insert(tx2.hash(), tx2);
x
@ -1654,12 +1677,12 @@ pub mod test {
// Create two transactions with same nonce
// (same hash)
let (tx1, tx2) = new_tx_pair_default(0.into(), 0.into());
let tx1 = VerifiedTransaction::new(tx1, TransactionOrigin::External, 0, None);
let tx2 = VerifiedTransaction::new(tx2, TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx1, TransactionOrigin::External, None, 0, 0);
let tx2 = VerifiedTransaction::new(tx2, TransactionOrigin::External, None, 0, 1);
let by_hash = {
let mut x = HashMap::new();
let tx1 = VerifiedTransaction::new(tx1.transaction.clone(), TransactionOrigin::External, 0, None);
let tx2 = VerifiedTransaction::new(tx2.transaction.clone(), TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx1.transaction.clone(), TransactionOrigin::External, None, 0, 0);
let tx2 = VerifiedTransaction::new(tx2.transaction.clone(), TransactionOrigin::External, None, 0, 1);
x.insert(tx1.hash(), tx1);
x.insert(tx2.hash(), tx2);
x
@ -1701,10 +1724,10 @@ pub mod test {
gas_limit: !U256::zero(),
};
let tx = new_tx_default();
let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External, None, 0, 0);
let order1 = TransactionOrder::for_transaction(&tx1, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly);
assert!(set.insert(tx1.sender(), tx1.nonce(), order1).is_none());
let tx2 = VerifiedTransaction::new(tx, TransactionOrigin::External, 0, None);
let tx2 = VerifiedTransaction::new(tx, TransactionOrigin::External, None, 0, 1);
let order2 = TransactionOrder::for_transaction(&tx2, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly);
assert!(set.insert(tx2.sender(), tx2.nonce(), order2).is_some());
}
@ -1721,7 +1744,7 @@ pub mod test {
assert_eq!(set.gas_price_entry_limit(), 0.into());
let tx = new_tx_default();
let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External, 0, None);
let tx1 = VerifiedTransaction::new(tx.clone(), TransactionOrigin::External, None, 0, 0);
let order1 = TransactionOrder::for_transaction(&tx1, 0.into(), 1.into(), PrioritizationStrategy::GasPriceOnly);
assert!(set.insert(tx1.sender(), tx1.nonce(), order1.clone()).is_none());
assert_eq!(set.gas_price_entry_limit(), 2.into());
@ -2473,6 +2496,32 @@ pub mod test {
assert_eq!(stats.pending, 2);
}
#[test]
fn should_not_replace_same_transaction_if_the_fee_is_less_than_minimal_bump() {
use ethcore_logger::init_log;
init_log();
// given
let mut txq = TransactionQueue::default();
let keypair = Random.generate().unwrap();
let tx = new_unsigned_tx(123.into(), default_gas_val(), 20.into()).sign(keypair.secret(), None);
let tx2 = {
let mut tx2 = (**tx).clone();
tx2.gas_price = U256::from(21);
tx2.sign(keypair.secret(), None)
};
// when
txq.add(tx, TransactionOrigin::External, 0, None, &default_tx_provider()).unwrap();
let res = txq.add(tx2, TransactionOrigin::External, 0, None, &default_tx_provider());
// then
assert_eq!(unwrap_tx_err(res), TransactionError::TooCheapToReplace);
let stats = txq.status();
assert_eq!(stats.pending, 1);
assert_eq!(stats.future, 0);
assert_eq!(txq.top_transactions()[0].gas_price, U256::from(20));
}
#[test]
fn should_replace_same_transaction_when_has_higher_fee() {
use ethcore_logger::init_log;
@ -2480,10 +2529,10 @@ pub mod test {
// given
let mut txq = TransactionQueue::default();
let keypair = Random.generate().unwrap();
let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret(), None);
let tx = new_unsigned_tx(123.into(), default_gas_val(), 10.into()).sign(keypair.secret(), None);
let tx2 = {
let mut tx2 = (**tx).clone();
tx2.gas_price = U256::from(200);
tx2.gas_price = U256::from(20);
tx2.sign(keypair.secret(), None)
};
@ -2495,7 +2544,7 @@ pub mod test {
let stats = txq.status();
assert_eq!(stats.pending, 1);
assert_eq!(stats.future, 0);
assert_eq!(txq.top_transactions()[0].gas_price, U256::from(200));
assert_eq!(txq.top_transactions()[0].gas_price, U256::from(20));
}
#[test]
@ -2815,6 +2864,24 @@ pub mod test {
assert_eq!(txq.top_transactions().len(), 1);
}
#[test]
fn should_not_order_transactions_by_hash() {
// given
let secret1 = "0000000000000000000000000000000000000000000000000000000000000002".parse().unwrap();
let secret2 = "0000000000000000000000000000000000000000000000000000000000000001".parse().unwrap();
let tx1 = new_unsigned_tx(123.into(), default_gas_val(), 0.into()).sign(&secret1, None);
let tx2 = new_unsigned_tx(123.into(), default_gas_val(), 0.into()).sign(&secret2, None);
let mut txq = TransactionQueue::default();
// when
txq.add(tx1.clone(), TransactionOrigin::External, 0, None, &default_tx_provider()).unwrap();
txq.add(tx2, TransactionOrigin::External, 0, None, &default_tx_provider()).unwrap();
// then
assert_eq!(txq.top_transactions()[0], tx1);
assert_eq!(txq.top_transactions().len(), 2);
}
#[test]
fn should_not_return_transactions_over_nonce_cap() {
// given

View File

@ -121,7 +121,7 @@ pub fn to_fat_rlps(account_hash: &H256, acc: &BasicAccount, acct_db: &AccountDB,
let stream = ::std::mem::replace(&mut account_stream, RlpStream::new_list(2));
chunks.push(stream.out());
target_chunk_size = max_chunk_size;
leftover = Some(pair.to_vec());
leftover = Some(pair.into_vec());
break;
}
},

View File

@ -190,7 +190,7 @@ mod tests {
let receipts_root = b.header.receipts_root().clone();
b.header.set_transactions_root(::util::triehash::ordered_trie_root(
b.transactions.iter().map(::rlp::encode).map(|out| out.to_vec())
b.transactions.iter().map(::rlp::encode).map(|out| out.into_vec())
));
let encoded = encode_block(&b);

View File

@ -462,7 +462,7 @@ fn rebuild_accounts(
}
}
::rlp::encode(&acc).to_vec()
::rlp::encode(&acc).into_vec()
};
*out = (hash, thin_rlp);

View File

@ -77,7 +77,7 @@ impl StateProducer {
let mut account: BasicAccount = ::rlp::decode(&*account_data);
let acct_db = AccountDBMut::from_hash(db, *address_hash);
fill_storage(acct_db, &mut account.storage_root, &mut self.storage_seed);
*account_data = DBValue::from_vec(::rlp::encode(&account).to_vec());
*account_data = DBValue::from_vec(::rlp::encode(&account).into_vec());
}
// sweep again to alter account trie.

View File

@ -257,7 +257,7 @@ impl Account {
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
self.code_cache = Arc::new(x.to_vec());
self.code_cache = Arc::new(x.into_vec());
Some(self.code_cache.clone())
},
_ => {
@ -476,10 +476,10 @@ mod tests {
fn account_compress() {
let raw = Account::new_basic(2.into(), 4.into()).rlp();
let rlp = UntrustedRlp::new(&raw);
let compact_vec = rlp.compress(RlpType::Snapshot).to_vec();
let compact_vec = rlp.compress(RlpType::Snapshot).into_vec();
assert!(raw.len() > compact_vec.len());
let again_raw = UntrustedRlp::new(&compact_vec).decompress(RlpType::Snapshot);
assert_eq!(raw, again_raw.to_vec());
assert_eq!(raw, again_raw.into_vec());
}
#[test]

View File

@ -1826,14 +1826,14 @@ mod tests {
let mut state = get_temp_state();
state.require_or_from(&a, false, ||Account::new_contract(42.into(), 0.into()), |_|{}).unwrap();
state.init_code(&a, vec![1, 2, 3]).unwrap();
assert_eq!(state.code(&a).unwrap(), Some(Arc::new([1u8, 2, 3].to_vec())));
assert_eq!(state.code(&a).unwrap(), Some(Arc::new(vec![1u8, 2, 3])));
state.commit().unwrap();
assert_eq!(state.code(&a).unwrap(), Some(Arc::new([1u8, 2, 3].to_vec())));
assert_eq!(state.code(&a).unwrap(), Some(Arc::new(vec![1u8, 2, 3])));
state.drop()
};
let state = State::from_existing(db, root, U256::from(0u8), Default::default()).unwrap();
assert_eq!(state.code(&a).unwrap(), Some(Arc::new([1u8, 2, 3].to_vec())));
assert_eq!(state.code(&a).unwrap(), Some(Arc::new(vec![1u8, 2, 3])));
}
#[test]

View File

@ -133,7 +133,7 @@ pub fn create_test_block_with_data(header: &Header, transactions: &[SignedTransa
rlp.append(header);
rlp.begin_list(transactions.len());
for t in transactions {
rlp.append_raw(&rlp::encode(t).to_vec(), 1);
rlp.append_raw(&rlp::encode(t).into_vec(), 1);
}
rlp.append_list(&uncles);
rlp.out()

View File

@ -475,7 +475,7 @@ mod tests {
let mut uncles_rlp = RlpStream::new();
uncles_rlp.append_list(&good_uncles);
let good_uncles_hash = uncles_rlp.as_raw().sha3();
let good_transactions_root = ordered_trie_root(good_transactions.iter().map(|t| ::rlp::encode::<UnverifiedTransaction>(t).to_vec()));
let good_transactions_root = ordered_trie_root(good_transactions.iter().map(|t| ::rlp::encode::<UnverifiedTransaction>(t).into_vec()));
let mut parent = good.clone();
parent.set_number(9);

View File

@ -9,4 +9,4 @@ tiny-keccak = "1.2"
eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1" }
ethkey = { path = "../ethkey" }
ethcore-bigint = { path = "../util/bigint" }
subtle = "0.1"

View File

@ -16,11 +16,12 @@
//! Crypto utils used ethstore and network.
extern crate ethcore_bigint as bigint;
extern crate tiny_keccak;
extern crate crypto as rcrypto;
extern crate secp256k1;
extern crate ethcore_bigint as bigint;
extern crate ethkey;
extern crate secp256k1;
extern crate subtle;
extern crate tiny_keccak;
use std::fmt;
use tiny_keccak::Keccak;
@ -34,7 +35,7 @@ pub const KEY_LENGTH: usize = 32;
pub const KEY_ITERATIONS: usize = 10240;
pub const KEY_LENGTH_AES: usize = KEY_LENGTH / 2;
/// Default MAC to use (in RPC).
/// Default authenticated data to use (in RPC).
pub const DEFAULT_MAC: [u8; 2] = [0, 0];
#[derive(PartialEq, Debug)]
@ -149,13 +150,13 @@ pub mod aes {
use rcrypto::symmetriccipher::{Encryptor, Decryptor, SymmetricCipherError};
use rcrypto::buffer::{RefReadBuffer, RefWriteBuffer, WriteBuffer};
/// Encrypt a message
/// Encrypt a message (CTR mode)
pub fn encrypt(k: &[u8], iv: &[u8], plain: &[u8], dest: &mut [u8]) {
let mut encryptor = CtrMode::new(AesSafe128Encryptor::new(k), iv.to_vec());
encryptor.encrypt(&mut RefReadBuffer::new(plain), &mut RefWriteBuffer::new(dest), true).expect("Invalid length or padding");
}
/// Decrypt a message
/// Decrypt a message (CTR mode)
pub fn decrypt(k: &[u8], iv: &[u8], encrypted: &[u8], dest: &mut [u8]) {
let mut encryptor = CtrMode::new(AesSafe128Encryptor::new(k), iv.to_vec());
encryptor.decrypt(&mut RefReadBuffer::new(encrypted), &mut RefWriteBuffer::new(dest), true).expect("Invalid length or padding");
@ -208,8 +209,11 @@ pub mod ecies {
use ethkey::{Random, Generator, Public, Secret};
use {Error, ecdh, aes, Keccak256};
/// Encrypt a message with a public key
pub fn encrypt(public: &Public, shared_mac: &[u8], plain: &[u8]) -> Result<Vec<u8>, Error> {
/// Encrypt a message with a public key, writing an HMAC covering both
/// the plaintext and authenticated data.
///
/// Authenticated data may be empty.
pub fn encrypt(public: &Public, auth_data: &[u8], plain: &[u8]) -> Result<Vec<u8>, Error> {
let r = Random.generate()
.expect("context known to have key-generation capabilities; qed");
@ -239,13 +243,13 @@ pub mod ecies {
let cipher_iv = &msgd[64..(64 + 16 + plain.len())];
hmac.input(cipher_iv);
}
hmac.input(shared_mac);
hmac.input(auth_data);
hmac.raw_result(&mut msgd[(64 + 16 + plain.len())..]);
}
Ok(msg)
}
/// Encrypt a message with a public key
/// Encrypt a message with a public key and no HMAC
pub fn encrypt_single_message(public: &Public, plain: &[u8]) -> Result<Vec<u8>, Error> {
let r = Random.generate()
.expect("context known to have key-generation capabilities");
@ -272,8 +276,9 @@ pub mod ecies {
Ok(msgd)
}
/// Decrypt a message with a secret key
pub fn decrypt(secret: &Secret, shared_mac: &[u8], encrypted: &[u8]) -> Result<Vec<u8>, Error> {
/// Decrypt a message with a secret key, checking HMAC for ciphertext
/// and authenticated data validity.
pub fn decrypt(secret: &Secret, auth_data: &[u8], encrypted: &[u8]) -> Result<Vec<u8>, Error> {
let meta_len = 1 + 64 + 16 + 32;
if encrypted.len() < meta_len || encrypted[0] < 2 || encrypted[0] > 4 {
return Err(Error::InvalidMessage); //invalid message: publickey
@ -300,10 +305,12 @@ pub mod ecies {
// Verify tag
let mut hmac = Hmac::new(Sha256::new(), &mkey);
hmac.input(cipher_with_iv);
hmac.input(shared_mac);
hmac.input(auth_data);
let mut mac = [0u8; 32];
hmac.raw_result(&mut mac);
if &mac[..] != msg_mac {
// constant time compare to avoid timing attack.
if ::subtle::arrays_equal(&mac[..], msg_mac) != 1 {
return Err(Error::InvalidMessage);
}
@ -312,7 +319,7 @@ pub mod ecies {
Ok(msg)
}
/// Decrypt single message with a secret key
/// Decrypt single message with a secret key and no HMAC.
pub fn decrypt_single_message(secret: &Secret, encrypted: &[u8]) -> Result<Vec<u8>, Error> {
let meta_len = 64;
if encrypted.len() < meta_len {

View File

@ -104,7 +104,7 @@ impl Crypto {
cipher: Cipher::Aes128Ctr(Aes128Ctr {
iv: iv,
}),
ciphertext: (*ciphertext).to_vec(),
ciphertext: ciphertext.into_vec(),
kdf: Kdf::Pbkdf2(Pbkdf2 {
dklen: crypto::KEY_LENGTH as u32,
salt: salt,

View File

@ -122,7 +122,7 @@ impl trace::VMTracer for Informant {
fn prepare_subtrace(&self, code: &[u8]) -> Self where Self: Sized {
let mut vm = Informant::default();
vm.depth = self.depth + 1;
vm.code = code.to_vec();
vm.code = code.into_vec();
vm.gas_used = self.gas_used;
vm
}

View File

@ -233,7 +233,7 @@ mod tests {
let _ = write_chunk(&mut transport, &mut progress, b"foobar");
assert_eq!(b"foobar".to_vec(), transport);
assert_eq!(b"foobar".into_vec(), transport);
assert_eq!(6, progress);
}
@ -244,7 +244,7 @@ mod tests {
let _ = write_chunk(&mut transport, &mut progress, b"foobar");
assert_eq!(b"bar".to_vec(), transport);
assert_eq!(b"bar".into_vec(), transport);
assert_eq!(6, progress);
}

View File

@ -79,7 +79,7 @@ impl IpfsHandler {
fn block_list(&self, hash: H256) -> Result<Out> {
let uncles = self.client().find_uncles(&hash).ok_or(Error::BlockNotFound)?;
Ok(Out::OctetStream(rlp::encode_list(&uncles).to_vec()))
Ok(Out::OctetStream(rlp::encode_list(&uncles).into_vec()))
}
/// Get transaction by hash and return as raw binary.
@ -87,7 +87,7 @@ impl IpfsHandler {
let tx_id = TransactionId::Hash(hash);
let tx = self.client().transaction(tx_id).ok_or(Error::TransactionNotFound)?;
Ok(Out::OctetStream(rlp::encode(&*tx).to_vec()))
Ok(Out::OctetStream(rlp::encode(&*tx).into_vec()))
}
/// Get state trie node by hash and return as raw binary.

View File

@ -121,7 +121,7 @@ impl TransactionEntry {
impl From<PendingTransaction> for TransactionEntry {
fn from(pending: PendingTransaction) -> Self {
TransactionEntry {
rlp_bytes: ::rlp::encode(&pending.transaction).to_vec(),
rlp_bytes: ::rlp::encode(&pending.transaction).into_vec(),
condition: pending.condition.map(Into::into),
}
}

View File

@ -227,8 +227,7 @@ fn execute_light(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) ->
}
// start on_demand service.
let account_start_nonce = service.client().engine().account_start_nonce(0);
let on_demand = Arc::new(::light::on_demand::OnDemand::new(cache.clone(), account_start_nonce));
let on_demand = Arc::new(::light::on_demand::OnDemand::new(cache.clone()));
// set network path.
net_conf.net_config_path = Some(db_dirs.network_path().to_string_lossy().into_owned());

View File

@ -36,6 +36,6 @@ pub fn sign_call<B: MiningBlockChainClient, M: MinerService>(
gas: request.gas.unwrap_or(50_000_000.into()),
gas_price: request.gas_price.unwrap_or_else(|| default_gas_price(&**client, &**miner)),
value: request.value.unwrap_or(0.into()),
data: request.data.map_or_else(Vec::new, |d| d.to_vec())
data: request.data.unwrap_or_default(),
}.fake_sign(from))
}

View File

@ -192,7 +192,7 @@ impl LightFetch {
let action = req.to.map_or(Action::Create, Action::Call);
let gas = req.gas.unwrap_or(U256::from(10_000_000)); // better gas amount?
let value = req.value.unwrap_or_else(U256::zero);
let data = req.data.map_or_else(Vec::new, |d| d.to_vec());
let data = req.data.unwrap_or_default();
future::done(match nonce {
Some(n) => Ok(EthTransaction {

View File

@ -607,7 +607,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM> Eth for EthClient<C, SN, S, M, EM> where
let mix_hash: H256 = mix_hash.into();
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let seal = vec![rlp::encode(&mix_hash).to_vec(), rlp::encode(&nonce).to_vec()];
let seal = vec![rlp::encode(&mix_hash).into_vec(), rlp::encode(&nonce).into_vec()];
Ok(self.miner.submit_seal(&*self.client, pow_hash, seal).is_ok())
}

View File

@ -154,7 +154,7 @@ impl EthClient {
true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t, eip86_transition)).collect()),
_ => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()),
},
extra_data: Bytes::new(header.extra_data().to_vec()),
extra_data: Bytes::new(header.extra_data().clone()),
},
extra_info: extra_info
}

View File

@ -126,7 +126,7 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
.and_then(|(pending_tx, dispatcher)| {
let network_id = pending_tx.network_id();
trace!(target: "miner", "send_transaction: dispatching tx: {} for network ID {:?}",
::rlp::encode(&*pending_tx).to_vec().pretty(), network_id);
::rlp::encode(&*pending_tx).into_vec().pretty(), network_id);
dispatcher.dispatch_transaction(pending_tx).map(Into::into)
})

View File

@ -963,7 +963,7 @@ fn rpc_eth_send_raw_transaction() {
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
let t = t.with_signature(signature, None);
let rlp = rlp::encode(&t).to_vec().to_hex();
let rlp = rlp::encode(&t).into_vec().to_hex();
let req = r#"{
"jsonrpc": "2.0",

View File

@ -195,7 +195,7 @@ impl Transaction {
Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data.sha3()).into()),
Action::Call(_) => None,
},
raw: ::rlp::encode(&t.signed).to_vec().into(),
raw: ::rlp::encode(&t.signed).into_vec().into(),
public_key: t.recover_public().ok().map(Into::into),
network_id: t.network_id(),
standard_v: t.standard_v().into(),
@ -229,7 +229,7 @@ impl Transaction {
Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data.sha3()).into()),
Action::Call(_) => None,
},
raw: ::rlp::encode(&t).to_vec().into(),
raw: ::rlp::encode(&t).into_vec().into(),
public_key: t.public_key().map(Into::into),
network_id: t.network_id(),
standard_v: t.standard_v().into(),

View File

@ -93,7 +93,7 @@ impl KeyStorage for PersistentKeyStorage {
self.db.get(None, document)
.map_err(Error::Database)?
.ok_or(Error::DocumentNotFound)
.map(|key| key.to_vec())
.map(|key| key.into_vec())
.and_then(|key| serde_json::from_slice::<SerializableDocumentKeyShare>(&key).map_err(|e| Error::Database(e.to_string())))
.map(Into::into)
}

View File

@ -342,7 +342,7 @@ mod tests {
let mut core = Core::new().expect("Tokio Core should be created with no errors");
let mut buffer = vec![0u8; 2048];
let mut data_vec = data.as_bytes().to_vec();
let mut data_vec = data.as_bytes().into_vec();
data_vec.extend(b"\n");
let stream = TcpStream::connect(addr, &core.handle())
@ -353,7 +353,7 @@ mod tests {
io::read(stream, &mut buffer)
})
.and_then(|(_, read_buf, len)| {
future::ok(read_buf[0..len].to_vec())
future::ok(read_buf[0..len].into_vec())
});
let result = core.run(stream).expect("Core should run with no errors");
@ -454,7 +454,7 @@ mod tests {
let mut auth_request =
r#"{"jsonrpc": "2.0", "method": "mining.authorize", "params": ["miner1", ""], "id": 1}"#
.as_bytes()
.to_vec();
.into_vec();
auth_request.extend(b"\n");
let mut core = Core::new().expect("Tokio Core should be created with no errors");
@ -487,7 +487,7 @@ mod tests {
})
.and_then(|(_, read_buf, len)| {
trace!(target: "stratum", "Received work from server");
future::ok(read_buf[0..len].to_vec())
future::ok(read_buf[0..len].into_vec())
});
let response = String::from_utf8(
core.run(stream).expect("Core should run with no errors")

View File

@ -427,7 +427,7 @@ struct TxRelay(Arc<BlockChainClient>);
impl LightHandler for TxRelay {
fn on_transactions(&self, ctx: &EventContext, relay: &[::ethcore::transaction::UnverifiedTransaction]) {
trace!(target: "pip", "Relaying {} transactions from peer {}", relay.len(), ctx.peer());
self.0.queue_transactions(relay.iter().map(|tx| ::rlp::encode(tx).to_vec()).collect(), ctx.peer())
self.0.queue_transactions(relay.iter().map(|tx| ::rlp::encode(tx).into_vec()).collect(), ctx.peer())
}
}

View File

@ -126,6 +126,8 @@ const MAX_NEW_HASHES: usize = 64;
const MAX_TX_TO_IMPORT: usize = 512;
const MAX_NEW_BLOCK_AGE: BlockNumber = 20;
const MAX_TRANSACTION_SIZE: usize = 300*1024;
// maximal packet size with transactions (cannot be greater than 16MB - protocol limitation).
const MAX_TRANSACTION_PACKET_SIZE: usize = 8 * 1024 * 1024;
// Maximal number of transactions in sent in single packet.
const MAX_TRANSACTIONS_TO_PROPAGATE: usize = 64;
// Min number of blocks to be behind for a snapshot sync
@ -2044,7 +2046,7 @@ impl ChainSync {
// update stats
for hash in &all_transactions_hashes {
let id = io.peer_session_info(peer_id).and_then(|info| info.id);
stats.propagated(*hash, id, block_number);
stats.propagated(hash, id, block_number);
}
peer_info.last_sent_transactions = all_transactions_hashes.clone();
return Some((peer_id, all_transactions_hashes.len(), all_transactions_rlp.clone()));
@ -2060,14 +2062,35 @@ impl ChainSync {
}
// Construct RLP
let mut packet = RlpStream::new_list(to_send.len());
for tx in &transactions {
if to_send.contains(&tx.transaction.hash()) {
packet.append(&tx.transaction);
// update stats
let id = io.peer_session_info(peer_id).and_then(|info| info.id);
stats.propagated(tx.transaction.hash(), id, block_number);
let (packet, to_send) = {
let mut to_send = to_send;
let mut packet = RlpStream::new();
packet.begin_unbounded_list();
let mut pushed = 0;
for tx in &transactions {
let hash = tx.transaction.hash();
if to_send.contains(&hash) {
let mut transaction = RlpStream::new();
tx.transaction.rlp_append(&mut transaction);
let appended = packet.append_raw_checked(&transaction.drain(), 1, MAX_TRANSACTION_PACKET_SIZE);
if !appended {
// Maximal packet size reached just proceed with sending
debug!("Transaction packet size limit reached. Sending incomplete set of {}/{} transactions.", pushed, to_send.len());
to_send = to_send.into_iter().take(pushed).collect();
break;
}
pushed += 1;
}
}
packet.complete_unbounded_list();
(packet, to_send)
};
// Update stats
let id = io.peer_session_info(peer_id).and_then(|info| info.id);
for hash in &to_send {
// update stats
stats.propagated(hash, id, block_number);
}
peer_info.last_sent_transactions = all_transactions_hashes

View File

@ -177,7 +177,7 @@ mod tests {
parent_hash = Some(header.hash());
encoded::Header::new(::rlp::encode(&header).to_vec())
encoded::Header::new(::rlp::encode(&header).into_vec())
}).collect();
assert!(verify(&headers, &request).is_ok());
@ -203,7 +203,7 @@ mod tests {
parent_hash = Some(header.hash());
encoded::Header::new(::rlp::encode(&header).to_vec())
encoded::Header::new(::rlp::encode(&header).into_vec())
}).collect();
assert!(verify(&headers, &request).is_ok());
@ -229,7 +229,7 @@ mod tests {
parent_hash = Some(header.hash());
encoded::Header::new(::rlp::encode(&header).to_vec())
encoded::Header::new(::rlp::encode(&header).into_vec())
}).collect();
assert_eq!(verify(&headers, &request), Err(BasicError::TooManyHeaders(20, 25)));
@ -248,7 +248,7 @@ mod tests {
let mut header = Header::default();
header.set_number(x);
encoded::Header::new(::rlp::encode(&header).to_vec())
encoded::Header::new(::rlp::encode(&header).into_vec())
}).collect();
assert_eq!(verify(&headers, &request), Err(BasicError::WrongSkip(5, Some(2))));

View File

@ -56,9 +56,9 @@ pub struct TransactionsStats {
impl TransactionsStats {
/// Increases number of propagations to given `enodeid`.
pub fn propagated(&mut self, hash: H256, enode_id: Option<NodeId>, current_block_num: BlockNumber) {
pub fn propagated(&mut self, hash: &H256, enode_id: Option<NodeId>, current_block_num: BlockNumber) {
let enode_id = enode_id.unwrap_or_default();
let mut stats = self.pending_transactions.entry(hash).or_insert_with(|| Stats::new(current_block_num));
let mut stats = self.pending_transactions.entry(*hash).or_insert_with(|| Stats::new(current_block_num));
let mut count = stats.propagated_to.entry(enode_id).or_insert(0);
*count = count.saturating_add(1);
}
@ -101,9 +101,9 @@ mod tests {
let enodeid2 = 5.into();
// when
stats.propagated(hash, Some(enodeid1), 5);
stats.propagated(hash, Some(enodeid1), 10);
stats.propagated(hash, Some(enodeid2), 15);
stats.propagated(&hash, Some(enodeid1), 5);
stats.propagated(&hash, Some(enodeid1), 10);
stats.propagated(&hash, Some(enodeid2), 15);
// then
let stats = stats.get(&hash);
@ -122,7 +122,7 @@ mod tests {
let mut stats = TransactionsStats::default();
let hash = 5.into();
let enodeid1 = 5.into();
stats.propagated(hash, Some(enodeid1), 10);
stats.propagated(&hash, Some(enodeid1), 10);
// when
stats.retain(&HashSet::new());

View File

@ -16,7 +16,7 @@ time = "0.1.34"
rocksdb = { git = "https://github.com/paritytech/rust-rocksdb" }
eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1" }
rust-crypto = "0.2.34"
elastic-array = "0.8"
elastic-array = "0.9"
rlp = { path = "rlp" }
heapsize = "0.4"
itertools = "0.5"

View File

@ -45,14 +45,14 @@ fn random_bytes(min_count: usize, diff_count: usize, seed: &mut H256) -> Vec<u8>
assert!(min_count + diff_count <= 32);
*seed = seed.sha3();
let r = min_count + (seed[31] as usize % (diff_count + 1));
seed[0..r].to_vec()
seed[0..r].into_vec()
}
fn random_value(seed: &mut H256) -> Bytes {
*seed = seed.sha3();
match seed[0] % 2 {
1 => vec![seed[31];1],
_ => seed.to_vec(),
_ => seed.into_vec(),
}
}

View File

@ -7,7 +7,7 @@ version = "0.2.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
elastic-array = "0.8"
elastic-array = "0.9"
ethcore-bigint = { path = "../bigint" }
lazy_static = "0.2"
rustc-serialize = "0.3"

File diff suppressed because one or more lines are too long

View File

@ -98,7 +98,7 @@ pub fn decode_list<T>(bytes: &[u8]) -> Vec<T> where T: Decodable {
///
/// fn main () {
/// let animal = "cat";
/// let out = rlp::encode(&animal).to_vec();
/// let out = rlp::encode(&animal).into_vec();
/// assert_eq!(out, vec![0x83, b'c', b'a', b't']);
/// }
/// ```

View File

@ -264,8 +264,8 @@ impl RlpStream {
/// panic! if stream is not finished.
pub fn out(self) -> Vec<u8> {
match self.is_finished() {
//true => self.encoder.out().to_vec(),
true => self.buffer.to_vec(),
//true => self.encoder.out().into_vec(),
true => self.buffer.into_vec(),
false => panic!()
}
}

View File

@ -242,8 +242,8 @@ impl JournalDB for OverlayRecentDB {
fn state(&self, key: &H256) -> Option<Bytes> {
let journal_overlay = self.journal_overlay.read();
let key = to_short_key(key);
journal_overlay.backing_overlay.get(&key).map(|v| v.to_vec())
.or_else(|| journal_overlay.pending_overlay.get(&key).map(|d| d.clone().to_vec()))
journal_overlay.backing_overlay.get(&key).map(|v| v.into_vec())
.or_else(|| journal_overlay.pending_overlay.get(&key).map(|d| d.clone().into_vec()))
.or_else(|| self.backing.get_by_prefix(self.column, &key[0..DB_PREFIX_LEN]).map(|b| b.into_vec()))
}
@ -288,7 +288,7 @@ impl JournalDB for OverlayRecentDB {
batch.put_vec(self.column, &k.drain(), r.out());
if journal_overlay.latest_era.map_or(true, |e| now > e) {
trace!(target: "journaldb", "Set latest era to {}", now);
batch.put_vec(self.column, &LATEST_ERA_KEY, encode(&now).to_vec());
batch.put_vec(self.column, &LATEST_ERA_KEY, encode(&now).into_vec());
journal_overlay.latest_era = Some(now);
}

View File

@ -216,7 +216,7 @@ impl KeyValueDB for InMemory {
Some(map) =>
map.iter()
.find(|&(ref k ,_)| k.starts_with(prefix))
.map(|(_, v)| (&**v).to_vec().into_boxed_slice())
.map(|(_, v)| v.to_vec().into_boxed_slice())
}
}
@ -227,7 +227,7 @@ impl KeyValueDB for InMemory {
match op {
DBOp::Insert { col, key, value } => {
if let Some(mut col) = columns.get_mut(&col) {
col.insert(key.to_vec(), value);
col.insert(key.into_vec(), value);
}
},
DBOp::InsertCompressed { col, key, value } => {
@ -235,7 +235,7 @@ impl KeyValueDB for InMemory {
let compressed = UntrustedRlp::new(&value).compress(RlpType::Blocks);
let mut value = DBValue::new();
value.append_slice(&compressed);
col.insert(key.to_vec(), value);
col.insert(key.into_vec(), value);
}
},
DBOp::Delete { col, key } => {
@ -253,7 +253,7 @@ impl KeyValueDB for InMemory {
Some(map) => Box::new( // TODO: worth optimizing at all?
map.clone()
.into_iter()
.map(|(k, v)| (k.into_boxed_slice(), v.to_vec().into_boxed_slice()))
.map(|(k, v)| (k.into_boxed_slice(), v.into_vec().into_boxed_slice()))
),
None => Box::new(None.into_iter()),
}
@ -267,7 +267,7 @@ impl KeyValueDB for InMemory {
map.clone()
.into_iter()
.skip_while(move |&(ref k, _)| !k.starts_with(prefix))
.map(|(k, v)| (k.into_boxed_slice(), v.to_vec().into_boxed_slice()))
.map(|(k, v)| (k.into_boxed_slice(), v.into_vec().into_boxed_slice()))
),
None => Box::new(None.into_iter()),
}

View File

@ -163,7 +163,7 @@ impl<T: SimpleMigration> Migration for T {
};
for (key, value) in iter {
if let Some((key, value)) = self.simple_migrate(key.to_vec(), value.to_vec()) {
if let Some((key, value)) = self.simple_migrate(key.into_vec(), value.into_vec()) {
batch.insert(key, value, dest)?;
}
}

View File

@ -95,7 +95,7 @@ impl Migration for AddsColumn {
let mut batch = Batch::new(config, col);
for (key, value) in source.iter(col).into_iter().flat_map(|inner| inner) {
batch.insert(key.to_vec(), value.to_vec(), dest)?;
batch.insert(key.into_vec(), value.into_vec(), dest)?;
}

View File

@ -95,7 +95,7 @@ impl<'db> Iterator for FatDBIterator<'db> {
.map(|res|
res.map(|(hash, value)| {
let aux_hash = hash.sha3();
(self.trie.db().get(&aux_hash).expect("Missing fatdb hash").to_vec(), value)
(self.trie.db().get(&aux_hash).expect("Missing fatdb hash").into_vec(), value)
})
)
}

View File

@ -111,7 +111,7 @@ impl StandardMap {
let v = match self.value_mode {
ValueMode::Mirror => k.clone(),
ValueMode::Random => Self::random_value(seed),
ValueMode::Index => encode(&index).to_vec(),
ValueMode::Index => encode(&index).into_vec(),
};
d.push((k, v))
}

View File

@ -378,7 +378,7 @@ fn iterator() {
}
let t = TrieDB::new(&memdb, &root).unwrap();
assert_eq!(d.iter().map(|i| i.clone().to_vec()).collect::<Vec<_>>(), t.iter().unwrap().map(|x| x.unwrap().0).collect::<Vec<_>>());
assert_eq!(d.iter().map(|i| i.clone().into_vec()).collect::<Vec<_>>(), t.iter().unwrap().map(|x| x.unwrap().0).collect::<Vec<_>>());
assert_eq!(d, t.iter().unwrap().map(|x| x.unwrap().1).collect::<Vec<_>>());
}

View File

@ -1026,14 +1026,14 @@ mod tests {
let mut memdb = MemoryDB::new();
let mut root = H256::new();
let mut t1 = TrieDBMut::new(&mut memdb, &mut root);
t1.insert(&[0x01, 0x23], &big_value.to_vec()).unwrap();
t1.insert(&[0x01, 0x34], &big_value.to_vec()).unwrap();
t1.insert(&[0x01, 0x23], big_value).unwrap();
t1.insert(&[0x01, 0x34], big_value).unwrap();
let mut memdb2 = MemoryDB::new();
let mut root2 = H256::new();
let mut t2 = TrieDBMut::new(&mut memdb2, &mut root2);
t2.insert(&[0x01], &big_value.to_vec()).unwrap();
t2.insert(&[0x01, 0x23], &big_value.to_vec()).unwrap();
t2.insert(&[0x01, 0x34], &big_value.to_vec()).unwrap();
t2.insert(&[0x01], big_value).unwrap();
t2.insert(&[0x01, 0x23], big_value).unwrap();
t2.insert(&[0x01, 0x34], big_value).unwrap();
t2.remove(&[0x01]).unwrap();
}

View File

@ -48,7 +48,7 @@ pub fn ordered_trie_root<I>(input: I) -> H256
// optimize it later
.into_iter()
.enumerate()
.map(|(i, vec)| (rlp::encode(&i).to_vec(), vec))
.map(|(i, vec)| (rlp::encode(&i).into_vec(), vec))
.collect::<BTreeMap<_, _>>()
// then move them to a vector
.into_iter()