Merge pull request #101 from ethcore/clippy

fixed clippy lints for db, keys, miner, and script
This commit is contained in:
Marek Kotewicz 2016-11-08 21:59:33 +01:00 committed by GitHub
commit 7a5ab9e96b
12 changed files with 117 additions and 117 deletions

View File

@ -347,7 +347,7 @@ impl Database {
for (c, column) in overlay.iter_mut().enumerate() {
let column_data = mem::replace(column, HashMap::new());
for (key, state) in column_data.into_iter() {
for (key, state) in column_data {
match state {
KeyState::Delete => {
if c > 0 {

View File

@ -143,7 +143,7 @@ impl UpdateContext {
pub fn apply(mut self, db: &Database) -> Result<(), Error> {
// actually saving meta
for (hash, meta) in self.meta.drain() {
self.db_transaction.put(Some(COL_TRANSACTIONS_META), &*hash, &meta.to_bytes());
self.db_transaction.put(Some(COL_TRANSACTIONS_META), &*hash, &meta.into_bytes());
}
try!(db.write(self.db_transaction));
@ -277,7 +277,7 @@ impl Storage {
// another iteration skipping coinbase transaction
for accepted_tx in accepted_txs.iter().skip(1) {
for input in accepted_tx.inputs.iter() {
for input in &accepted_tx.inputs {
if !match context.meta.get_mut(&input.previous_output.hash) {
Some(ref mut meta) => {
if meta.is_spent(input.previous_output.index as usize) {
@ -334,7 +334,7 @@ impl Storage {
// denote outputs used
if tx_hash_num == 0 { continue; } // coinbase transaction does not have inputs
for input in tx.inputs.iter() {
for input in &tx.inputs {
if !match context.meta.get_mut(&input.previous_output.hash) {
Some(ref mut meta) => {
meta.denote_used(input.previous_output.index as usize);
@ -433,7 +433,7 @@ impl Storage {
}
// canonizing all route from the split point
for new_canonical_hash in route.iter() {
for new_canonical_hash in &route {
now_best += 1;
try!(self.canonize_block(context, now_best, &new_canonical_hash));
}
@ -467,13 +467,13 @@ impl Store for Storage {
fn block_transaction_hashes(&self, block_ref: BlockRef) -> Vec<H256> {
self.resolve_hash(block_ref)
.map(|h| self.block_transaction_hashes_by_hash(&h))
.unwrap_or(Vec::new())
.unwrap_or_default()
}
fn block_transactions(&self, block_ref: BlockRef) -> Vec<chain::Transaction> {
self.resolve_hash(block_ref)
.map(|h| self.block_transactions_by_hash(&h))
.unwrap_or(Vec::new())
.unwrap_or_default()
}
fn transaction_bytes(&self, hash: &H256) -> Option<Bytes> {

View File

@ -35,7 +35,7 @@ impl TransactionMeta {
self.spent.set(index, false);
}
pub fn to_bytes(self) -> Vec<u8> {
pub fn into_bytes(self) -> Vec<u8> {
let mut result = vec![0u8; 4];
LittleEndian::write_u32(&mut result[0..4], self.block_height);
result.extend(self.spent.to_bytes());

View File

@ -1,4 +1,4 @@
//! Bitcoin KeyPair
//! Bitcoin key pair.
use std::fmt;
use secp256k1::key;

View File

@ -4,7 +4,7 @@
//! `Public` - 65 bytes (TODO: make it optionally compressed)
//! `Private` - secret with additional network identifier (and compressed flag?)
//! `AddressHash` - 20 bytes derived from public
//! `Address` - address_hash with network identifier and format type
//! `Address` - addressh ash with network identifier and format type
extern crate rand;
extern crate rustc_serialize;

View File

@ -38,10 +38,11 @@ impl Private {
let recovery_id = recovery_id.to_i32() as u8;
let mut signature = H520::default();
signature[1..65].copy_from_slice(&data[0..64]);
signature[0] = match self.compressed {
true => 27 + recovery_id + 4,
false => 27 + recovery_id,
};
if self.compressed {
signature[0] = 27 + recovery_id + 4;
} else {
signature[0] = 27 + recovery_id;
}
Ok(signature.into())
}
}
@ -62,7 +63,7 @@ impl DisplayLayout for Private {
result.push(1);
}
let cs = checksum(&result);
result.extend(&*cs);
result.extend_from_slice(&*cs);
result
}

View File

@ -4,7 +4,7 @@
//! and orders them by given strategies. It works like multi-indexed priority queue, giving option to pop 'top'
//! transactions.
//! It also guarantees that ancestor-descendant relation won't break during ordered removal (ancestors always removed
//! before descendants). Removal using remove_by_hash can break this rule.
//! before descendants). Removal using `remove_by_hash` can break this rule.
use primitives::hash::H256;
use chain::Transaction;
use std::cmp::Ordering;
@ -15,6 +15,7 @@ use ser::Serializable;
use heapsize::HeapSizeOf;
/// Transactions ordering strategy
#[cfg_attr(feature="cargo-clippy", allow(enum_variant_names))]
#[derive(Debug, Clone, Copy)]
pub enum OrderingStrategy {
/// Order transactions by the time they have entered the memory pool
@ -79,7 +80,7 @@ struct Storage {
references: ReferenceStorage,
}
/// Multi-index storage which holds references to entries from Storage::by_hash
/// Multi-index storage which holds references to entries from `Storage::by_hash`
#[derive(Debug, Clone)]
struct ReferenceStorage {
/// By-input storage
@ -90,7 +91,7 @@ struct ReferenceStorage {
ordered: OrderedReferenceStorage,
}
/// Multi-index orderings storage which holds ordered references to entries from Storage::by_hash
/// Multi-index orderings storage which holds ordered references to entries from `Storage::by_hash`
#[derive(Debug, Clone)]
struct OrderedReferenceStorage {
/// By-entry-time storage
@ -223,7 +224,7 @@ impl Ord for ByPackageScoreOrderedEntry {
impl HeapSizeOf for Entry {
fn heap_size_of_children(&self) -> usize {
self.transaction.heap_size_of_children() + self.ancestors.heap_size_of_children()
self.transaction.heap_size_of_children() + self.ancestors.heap_size_of_children()
}
}
@ -251,11 +252,11 @@ impl Storage {
// remember that this transactions depends on its inputs
for input_hash in entry.transaction.inputs.iter().map(|input| &input.previous_output.hash) {
self.references.by_input.entry(input_hash.clone()).or_insert_with(|| HashSet::new()).insert(entry.hash.clone());
self.references.by_input.entry(input_hash.clone()).or_insert_with(HashSet::new).insert(entry.hash.clone());
}
// update score of all packages this transaction is in
for ancestor_hash in entry.ancestors.iter() {
for ancestor_hash in &entry.ancestors {
if let Some(mut ancestor_entry) = self.by_hash.get_mut(ancestor_hash) {
let removed = self.references.ordered.by_package_score.remove(&(ancestor_entry as &Entry).into());
@ -278,7 +279,7 @@ impl Storage {
}
// add to by_hash storage
self.by_hash.insert(entry.hash.clone(), entry);
self.by_hash.insert(entry.hash.clone(), entry);
}
pub fn get_by_hash(&self, h: &H256) -> Option<&Entry> {
@ -368,7 +369,7 @@ impl Storage {
self.by_hash.get(&top_hash).map(|entry| {
// simulate removal
removed.insert(top_hash.clone());
references.remove(Some(&removed), &self.by_hash, &entry);
references.remove(Some(&removed), &self.by_hash, entry);
// return this entry
result.push(top_hash);
@ -427,7 +428,7 @@ impl Storage {
// move all descendants out of storage for later insertion
Some(all_descendants.into_iter()
.filter_map(|hash| self.remove_by_hash(&hash).map(|entry| entry.transaction))
.filter_map(|hash| self.remove_by_hash(hash).map(|entry| entry.transaction))
.collect())
}
else {
@ -463,7 +464,7 @@ impl Storage {
}
pub fn get_transactions_ids(&self) -> Vec<H256> {
self.by_hash.keys().map(|h| h.clone()).collect()
self.by_hash.keys().cloned().collect()
}
}
@ -477,7 +478,7 @@ impl ReferenceStorage {
pub fn remove(&mut self, removed: Option<&HashSet<H256>>, by_hash: &HashMap<H256, Entry>, entry: &Entry) {
// for each pending descendant transaction
if let Some(descendants) = self.by_input.get(&entry.hash) {
let descendants = descendants.iter().filter_map(|hash| by_hash.get(&hash));
let descendants = descendants.iter().filter_map(|hash| by_hash.get(hash));
for descendant in descendants {
// if there are no more ancestors of this transaction in the pool
// => can move from pending to orderings
@ -485,7 +486,7 @@ impl ReferenceStorage {
self.pending.remove(&descendant.hash);
if let Some(descendant_entry) = by_hash.get(&descendant.hash) {
self.ordered.insert_to_orderings(&descendant_entry);
self.ordered.insert_to_orderings(descendant_entry);
}
}
}
@ -539,13 +540,19 @@ impl HeapSizeOf for OrderedReferenceStorage {
}
}
impl MemoryPool {
/// Creates new memory pool
pub fn new() -> Self {
impl Default for MemoryPool {
fn default() -> Self {
MemoryPool {
storage: Storage::new(),
}
}
}
impl MemoryPool {
/// Creates new memory pool
pub fn new() -> Self {
MemoryPool::default()
}
/// Insert verified transaction to the `MemoryPool`
pub fn insert_verified(&mut self, t: Transaction) {
@ -598,7 +605,7 @@ impl MemoryPool {
/// Get transaction by hash
pub fn get(&self, hash: &H256) -> Option<&Transaction> {
self.storage.get_by_hash(hash).map(|ref entry| &entry.transaction)
self.storage.get_by_hash(hash).map(|entry| &entry.transaction)
}
/// Checks if transaction is in the mempool
@ -645,10 +652,10 @@ impl MemoryPool {
fn get_ancestors(&self, t: &Transaction) -> HashSet<H256> {
let mut ancestors: HashSet<H256> = HashSet::new();
let ancestors_entries = t.inputs.iter()
.filter_map(|ref input| self.storage.get_by_hash(&input.previous_output.hash));
.filter_map(|input| self.storage.get_by_hash(&input.previous_output.hash));
for ancestor_entry in ancestors_entries {
ancestors.insert(ancestor_entry.hash.clone());
for grand_ancestor in ancestor_entry.ancestors.iter() {
for grand_ancestor in &ancestor_entry.ancestors {
ancestors.insert(grand_ancestor.clone());
}
}
@ -661,7 +668,7 @@ impl MemoryPool {
fn get_transaction_miner_fee(&self, t: &Transaction) -> i64 {
let input_value = 0; // TODO: sum all inputs of transaction
let output_value = t.outputs.iter().fold(0, |acc, ref output| acc + output.value);
let output_value = t.outputs.iter().fold(0, |acc, output| acc + output.value);
(output_value - input_value) as i64
}

View File

@ -13,11 +13,11 @@ impl Builder {
}
pub fn push_bool(mut self, value: bool) -> Self {
let opcode = match value {
true => Opcode::OP_1,
false => Opcode::OP_0,
};
self.data.push(opcode as u8);
if value {
self.data.push(Opcode::OP_1 as u8);
} else {
self.data.push(Opcode::OP_0 as u8);
}
self
}

View File

@ -222,11 +222,7 @@ fn cast_to_bool(data: &[u8]) -> bool {
}
let last = data[data.len() - 1];
if last == 0 || last == 0x80 {
false
} else {
true
}
!(last == 0 || last == 0x80)
}
pub fn verify_script(
@ -290,6 +286,7 @@ pub fn verify_script(
Ok(())
}
#[cfg_attr(feature="cargo-clippy", allow(match_same_arms))]
pub fn eval_script(
stack: &mut Stack<Bytes>,
script: &Script,
@ -450,10 +447,8 @@ pub fn eval_script(
},
Opcode::OP_NOP => break,
Opcode::OP_CHECKLOCKTIMEVERIFY => {
if !flags.verify_clocktimeverify {
if flags.verify_discourage_upgradable_nops {
return Err(Error::DiscourageUpgradableNops);
}
if !flags.verify_clocktimeverify && flags.verify_discourage_upgradable_nops {
return Err(Error::DiscourageUpgradableNops);
}
// Note that elsewhere numeric opcodes are limited to
@ -484,10 +479,8 @@ pub fn eval_script(
}
},
Opcode::OP_CHECKSEQUENCEVERIFY => {
if !flags.verify_chechsequenceverify {
if flags.verify_discourage_upgradable_nops {
return Err(Error::DiscourageUpgradableNops);
}
if !flags.verify_chechsequenceverify && flags.verify_discourage_upgradable_nops {
return Err(Error::DiscourageUpgradableNops);
}
let sequence = try!(Num::from_slice(try!(stack.last()), flags.verify_minimaldata, 5));
@ -496,10 +489,8 @@ pub fn eval_script(
return Err(Error::NegativeLocktime);
}
if (sequence & (SEQUENCE_LOCKTIME_DISABLE_FLAG as i64).into()).is_zero() {
if !checker.check_sequence(sequence) {
return Err(Error::UnsatisfiedLocktime);
}
if (sequence & (SEQUENCE_LOCKTIME_DISABLE_FLAG as i64).into()).is_zero() && !checker.check_sequence(sequence) {
return Err(Error::UnsatisfiedLocktime);
}
},
Opcode::OP_NOP1 |
@ -528,8 +519,9 @@ pub fn eval_script(
if exec_stack.is_empty() {
return Err(Error::UnbalancedConditional);
}
let last = exec_stack[exec_stack.len() - 1];
exec_stack[exec_stack.len() - 1] == !last;
let last_index = exec_stack.len() - 1;
let last = exec_stack[last_index];
exec_stack[last_index] = !last;
},
Opcode::OP_ENDIF => {
if exec_stack.is_empty() {
@ -620,11 +612,11 @@ pub fn eval_script(
Opcode::OP_EQUAL => {
let v1 = try!(stack.pop());
let v2 = try!(stack.pop());
let to_push = match v1 == v2 {
true => vec![1],
false => vec![0],
};
stack.push(to_push.into());
if v1 == v2 {
stack.push(vec![1].into());
} else {
stack.push(vec![0].into());
}
},
Opcode::OP_EQUALVERIFY => {
let equal = try!(stack.pop()) == try!(stack.pop());
@ -737,11 +729,11 @@ pub fn eval_script(
let v1 = try!(Num::from_slice(&try!(stack.pop()), flags.verify_minimaldata, 4));
let v2 = try!(Num::from_slice(&try!(stack.pop()), flags.verify_minimaldata, 4));
let v3 = try!(Num::from_slice(&try!(stack.pop()), flags.verify_minimaldata, 4));
let to_push = match v2 <= v3 && v3 <= v1 {
true => vec![1],
false => vec![0],
};
stack.push(to_push.into());
if v2 <= v3 && v3 <= v1 {
stack.push(vec![1].into());
} else {
stack.push(vec![0].into());
}
},
Opcode::OP_RIPEMD160 => {
let v = ripemd160(&try!(stack.pop()));
@ -771,7 +763,7 @@ pub fn eval_script(
let signature = try!(stack.pop());
let mut subscript = script.subscript(begincode);
if version == SignatureVersion::Base {
subscript = script.find_and_delete(&signature);
subscript = subscript.find_and_delete(&signature);
}
try!(check_signature_encoding(&signature, flags));
@ -780,11 +772,11 @@ pub fn eval_script(
let success = check_signature(checker, signature.into(), pubkey.into(), &subscript, version);
match opcode {
Opcode::OP_CHECKSIG => {
let to_push = match success {
true => vec![1],
false => vec![0],
};
stack.push(to_push.into());
if success {
stack.push(vec![1].into());
} else {
stack.push(vec![0].into());
}
},
Opcode::OP_CHECKSIGVERIFY if !success => {
return Err(Error::CheckSigVerify);
@ -843,11 +835,11 @@ pub fn eval_script(
match opcode {
Opcode::OP_CHECKMULTISIG => {
let to_push = match success {
true => vec![1],
false => vec![0],
};
stack.push(to_push.into());
if success {
stack.push(vec![1].into());
} else {
stack.push(vec![0].into());
}
},
Opcode::OP_CHECKMULTISIGVERIFY if !success => {
return Err(Error::CheckSigVerify);

View File

@ -3,10 +3,10 @@ use std::ops;
use bytes::Bytes;
use Error;
/// Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
/// Numeric opcodes (`OP_1ADD`, etc) are restricted to operating on 4-byte integers.
/// The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
/// but results may overflow (and are valid as long as they are not used in a subsequent
/// numeric operation). CScriptNum enforces those semantics by storing results as
/// numeric operation). `CScriptNum` enforces those semantics by storing results as
/// an int64 and allowing out-of-range values to be returned as a vector of bytes but
/// throwing an exception if arithmetic is done or the result is interpreted as an integer.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
@ -16,10 +16,7 @@ pub struct Num {
impl From<bool> for Num {
fn from(i: bool) -> Self {
let v = match i {
true => 1,
false => 0,
};
let v = if i { 1 } else { 0 };
Num {
value: v
}
@ -86,23 +83,21 @@ impl Num {
return Ok(0u8.into());
}
if require_minimal {
// Check that the number is encoded with the minimum possible
// number of bytes.
//
// If the most-significant-byte - excluding the sign bit - is zero
// then we're not minimal. Note how this test also rejects the
// negative-zero encoding, 0x80.
if (data.last().unwrap() & 0x7f) == 0 {
if data.len() <= 1 || (data[data.len() - 2] & 0x80) == 0 {
return Err(Error::NumberNotMinimallyEncoded)
}
}
// Check that the number is encoded with the minimum possible
// number of bytes.
//
// If the most-significant-byte - excluding the sign bit - is zero
// then we're not minimal. Note how this test also rejects the
// negative-zero encoding, 0x80.
if require_minimal &&
(data.last().unwrap() & 0x7f) == 0 &&
(data.len() <= 1 || (data[data.len() - 2] & 0x80) == 0) {
return Err(Error::NumberNotMinimallyEncoded)
}
let mut result = 0i64;
for i in 0..data.len() {
result |= (data[i] as i64) << (8 * i);
for (i, item) in data.iter().enumerate() {
result |= (*item as i64) << (8 * i);
}
// If the input vector's most significant byte is 0x80, remove it from
@ -121,9 +116,10 @@ impl Num {
let mut result = vec![];
let negative = self.value < 0;
let mut absvalue = match negative {
true => (-self.value) as u64,
false => self.value as u64,
let mut absvalue = if negative {
(-self.value) as u64
} else {
self.value as u64
};
while absvalue > 0 {
@ -142,9 +138,10 @@ impl Num {
// converting to an integral.
if result[result.len() - 1] & 0x80 != 0 {
match negative {
true => result.push(0x80),
false => result.push(0),
if negative {
result.push(0x80);
} else {
result.push(0);
}
} else if negative {
let rlen = result.len();

View File

@ -16,7 +16,7 @@ pub const MAX_PUBKEYS_PER_MULTISIG: usize = 20;
/// Maximum script length in bytes
pub const MAX_SCRIPT_SIZE: usize = 10000;
/// Threshold for nLockTime: below this value it is interpreted as block number,
/// Threshold for `nLockTime`: below this value it is interpreted as block number,
/// otherwise as UNIX timestamp.
pub const LOCKTIME_THRESHOLD: u32 = 500000000; // Tue Nov 5 00:53:20 1985 UTC

View File

@ -26,6 +26,7 @@ impl From<SighashBase> for u32 {
}
}
#[cfg_attr(feature="cargo-clippy", allow(doc_markdown))]
/// Documentation
/// https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_SINGLE
#[derive(Debug, PartialEq, Clone, Copy)]
@ -37,9 +38,10 @@ pub struct Sighash {
impl From<Sighash> for u32 {
fn from(s: Sighash) -> Self {
let base = s.base as u32;
match s.anyone_can_pay {
true => base | 0x80,
false => base,
if s.anyone_can_pay {
base | 0x80
} else {
base
}
}
}
@ -48,7 +50,6 @@ impl From<u32> for Sighash {
fn from(u: u32) -> Self {
// use 0x9f istead of 0x1f to catch 0x80
match u & 0x9f {
1 => Sighash::new(SighashBase::All, false),
2 => Sighash::new(SighashBase::None, false),
3 => Sighash::new(SighashBase::Single, false),
0x81 => Sighash::new(SighashBase::All, true),
@ -56,7 +57,7 @@ impl From<u32> for Sighash {
0x83 => Sighash::new(SighashBase::Single, true),
x if x & 0x80 == 0x80 => Sighash::new(SighashBase::All, true),
// 0 is handled like all...
_ => Sighash::new(SighashBase::All, false),
1 | _ => Sighash::new(SighashBase::All, false),
}
}
}
@ -155,9 +156,10 @@ impl TransactionInputSigner {
.enumerate()
.map(|(n, input)| TransactionInput {
previous_output: input.previous_output.clone(),
script_sig: match n == input_index {
true => script_pubkey.to_bytes(),
false => Bytes::default(),
script_sig: if n == input_index {
script_pubkey.to_bytes()
} else {
Bytes::default()
},
sequence: match sighash.base {
SighashBase::Single | SighashBase::None if n != input_index => 0,
@ -172,9 +174,10 @@ impl TransactionInputSigner {
SighashBase::Single => self.outputs.iter()
.take(input_index + 1)
.enumerate()
.map(|(n, out)| match n == input_index {
true => out.clone(),
false => TransactionOutput::default(),
.map(|(n, out)| if n == input_index {
out.clone()
} else {
TransactionOutput::default()
})
.collect(),
SighashBase::None => Vec::new(),