sweep most unwraps from ethcore crate, dapps crate (#2762)

* sweep most unwraps from ethcore crate

* purge unwrap from dapps server

* whitespace

[ci:none]
This commit is contained in:
Robert Habermeier
2016-10-20 23:41:15 +02:00
committed by Gav Wood
parent 866ab9c7a3
commit 96f4c10453
31 changed files with 150 additions and 80 deletions

View File

@@ -176,7 +176,8 @@ impl AccountProvider {
AccountProvider {
unlocked: Mutex::new(HashMap::new()),
address_book: Mutex::new(AddressBook::new(Default::default())),
sstore: Box::new(EthStore::open(Box::new(NullDir::default())).unwrap())
sstore: Box::new(EthStore::open(Box::new(NullDir::default()))
.expect("NullDir load always succeeds; qed"))
}
}
@@ -187,7 +188,7 @@ impl AccountProvider {
/// Creates new random account and returns address and public key
pub fn new_account_and_public(&self, password: &str) -> Result<(Address, Public), Error> {
let acc = Random.generate().unwrap();
let acc = Random.generate().expect("secp context has generation capabilities; qed");
let public = acc.public().clone();
let secret = acc.secret().clone();
let address = try!(self.sstore.insert_account(secret, password));

View File

@@ -350,7 +350,7 @@ impl<'x> OpenBlock<'x> {
let t = outcome.trace;
self.block.traces.as_mut().map(|traces| traces.push(t));
self.block.receipts.push(outcome.receipt);
Ok(self.block.receipts.last().unwrap())
Ok(self.block.receipts.last().expect("receipt just pushed; qed"))
}
Err(x) => Err(From::from(x))
}

View File

@@ -132,7 +132,8 @@ pub trait BlockProvider {
/// Returns the header of the genesis block.
fn genesis_header(&self) -> Header {
self.block_header(&self.genesis_hash()).unwrap()
self.block_header(&self.genesis_hash())
.expect("Genesis header always stored; qed")
}
/// Returns numbers of blocks containing given bloom.

View File

@@ -55,18 +55,23 @@ impl<T> CacheManager<T> where T: Eq + Hash {
}
for _ in 0..COLLECTION_QUEUE_SIZE {
let current_size = notify_unused(self.cache_usage.pop_back().unwrap());
self.cache_usage.push_front(Default::default());
if current_size < self.max_cache_size {
break;
if let Some(back) = self.cache_usage.pop_back() {
let current_size = notify_unused(back);
self.cache_usage.push_front(Default::default());
if current_size < self.max_cache_size {
break
}
}
}
}
fn rotate_cache_if_needed(&mut self) {
if self.cache_usage.len() == 0 { return }
if self.cache_usage[0].len() * self.bytes_per_cache_entry > self.pref_cache_size / COLLECTION_QUEUE_SIZE {
let cache = self.cache_usage.pop_back().unwrap();
self.cache_usage.push_front(cache);
if let Some(cache) = self.cache_usage.pop_back() {
self.cache_usage.push_front(cache);
}
}
}
}

View File

@@ -478,7 +478,11 @@ impl Client {
if number >= self.history {
let n = number - self.history;
state.mark_canonical(&mut batch, n, &chain.block_hash(n).unwrap()).expect("DB commit failed");
if let Some(ancient_hash) = chain.block_hash(n) {
state.mark_canonical(&mut batch, n, &ancient_hash).expect("DB commit failed");
} else {
debug!(target: "client", "Missing expected hash for block {}", n);
}
}
let route = chain.insert_block(&mut batch, block_data, receipts);

View File

@@ -123,10 +123,14 @@ pub trait Engine : Sync + Send {
fn is_builtin(&self, a: &Address) -> bool { self.builtins().contains_key(a) }
/// Determine the code execution cost of the builtin contract with address `a`.
/// Panics if `is_builtin(a)` is not true.
fn cost_of_builtin(&self, a: &Address, input: &[u8]) -> U256 { self.builtins().get(a).unwrap().cost(input.len()) }
fn cost_of_builtin(&self, a: &Address, input: &[u8]) -> U256 {
self.builtins().get(a).expect("queried cost of nonexistent builtin").cost(input.len())
}
/// Execution the builtin contract `a` on `input` and return `output`.
/// Panics if `is_builtin(a)` is not true.
fn execute_builtin(&self, a: &Address, input: &[u8], output: &mut BytesRef) { self.builtins().get(a).unwrap().execute(input, output); }
fn execute_builtin(&self, a: &Address, input: &[u8], output: &mut BytesRef) {
self.builtins().get(a).expect("attempted to execute nonexistent builtin").execute(input, output);
}
// TODO: sealing stuff - though might want to leave this for later.
}

View File

@@ -102,7 +102,7 @@ impl<Cost: CostType> evm::Evm for Interpreter<Cost> {
let mut informant = informant::EvmInformant::new(ext.depth());
let code = &params.code.as_ref().unwrap();
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 gasometer = Gasometer::<Cost>::new(try!(Cost::from_u256(params.gas)));
@@ -318,11 +318,11 @@ impl<Cost: CostType> Interpreter<Cost> {
// Get sender & receive addresses, check if we have balance
let (sender_address, receive_address, has_balance, call_type) = match instruction {
instructions::CALL => {
let has_balance = ext.balance(&params.address) >= value.unwrap();
let has_balance = ext.balance(&params.address) >= value.expect("value set for all but delegate call; qed");
(&params.address, &code_address, has_balance, CallType::Call)
},
instructions::CALLCODE => {
let has_balance = ext.balance(&params.address) >= value.unwrap();
let has_balance = ext.balance(&params.address) >= value.expect("value set for all but delegate call; qed");
(&params.address, &params.address, has_balance, CallType::CallCode)
},
instructions::DELEGATECALL => (&params.sender, &params.address, true, CallType::DelegateCall),

View File

@@ -359,7 +359,7 @@ impl evm::Evm for JitEvm {
data.timestamp = ext.env_info().timestamp as i64;
self.context = Some(unsafe { evmjit::ContextHandle::new(data, schedule, &mut ext_handle) });
let mut context = self.context.as_mut().unwrap();
let mut context = self.context.as_mut().expect("context handle set on the prior line; qed");
let res = context.exec();
match res {

View File

@@ -427,8 +427,16 @@ impl<'a> Executive<'a> {
trace!("exec::finalize: t.gas={}, sstore_refunds={}, suicide_refunds={}, refunds_bound={}, gas_left_prerefund={}, refunded={}, gas_left={}, gas_used={}, refund_value={}, fees_value={}\n",
t.gas, sstore_refunds, suicide_refunds, refunds_bound, gas_left_prerefund, refunded, gas_left, gas_used, refund_value, fees_value);
trace!("exec::finalize: Refunding refund_value={}, sender={}\n", refund_value, t.sender().unwrap());
self.state.add_balance(&t.sender().unwrap(), &refund_value);
let sender = match t.sender() {
Ok(sender) => sender,
Err(e) => {
debug!(target: "executive", "attempted to finalize transaction without sender: {}", e);
return Err(ExecutionError::Internal);
}
};
trace!("exec::finalize: Refunding refund_value={}, sender={}\n", refund_value, sender);
self.state.add_balance(&sender, &refund_value);
trace!("exec::finalize: Compensating author: fees_value={}, author={}\n", fees_value, &self.info.author);
self.state.add_balance(&self.info.author, &fees_value);

View File

@@ -199,8 +199,9 @@ impl Header {
match &mut *hash {
&mut Some(ref h) => h.clone(),
hash @ &mut None => {
*hash = Some(self.rlp_sha3(Seal::With));
hash.as_ref().unwrap().clone()
let h = self.rlp_sha3(Seal::With);
*hash = Some(h.clone());
h
}
}
}
@@ -211,8 +212,9 @@ impl Header {
match &mut *hash {
&mut Some(ref h) => h.clone(),
hash @ &mut None => {
*hash = Some(self.rlp_sha3(Seal::Without));
hash.as_ref().unwrap().clone()
let h = self.rlp_sha3(Seal::Without);
*hash = Some(h.clone());
h
}
}
}

View File

@@ -136,7 +136,7 @@ impl GasPriceCalibrator {
let gas_per_tx: f32 = 21000.0;
let wei_per_gas: f32 = wei_per_usd * usd_per_tx / gas_per_tx;
info!(target: "miner", "Updated conversion rate to Ξ1 = {} ({} wei/gas)", Colour::White.bold().paint(format!("US${}", usd_per_eth)), Colour::Yellow.bold().paint(format!("{}", wei_per_gas)));
set_price(U256::from_dec_str(&format!("{:.0}", wei_per_gas)).unwrap());
set_price(U256::from(wei_per_gas as u64));
}) {
self.next_calibration = Instant::now() + self.options.recalibration_period;
} else {
@@ -747,7 +747,7 @@ impl MinerService for Miner {
let mut transaction_queue = self.transaction_queue.lock();
let import = self.add_transactions_to_queue(
chain, vec![transaction], TransactionOrigin::Local, &mut transaction_queue
).pop().unwrap();
).pop().expect("one result returned per added transaction; one added => one result; qed");
match import {
Ok(ref res) => {
@@ -869,7 +869,11 @@ impl MinerService for Miner {
gas_used: receipt.gas_used - prev_gas,
contract_address: match tx.action {
Action::Call(_) => None,
Action::Create => Some(contract_address(&tx.sender().unwrap(), &tx.nonce)),
Action::Create => {
let sender = tx.sender()
.expect("transactions in pending block have already been checked for valid sender; qed");
Some(contract_address(&sender, &tx.nonce))
}
},
logs: receipt.logs.clone(),
}

View File

@@ -52,7 +52,8 @@ impl<F: Fn(PriceInfo) + Sync + Send + 'static> Handler<HttpStream> for SetPriceH
.and_then(|json| json.find_path(&["result", "ethusd"])
.and_then(|obj| match *obj {
Json::String(ref s) => Some((self.set_price)(PriceInfo {
ethusd: FromStr::from_str(s).unwrap()
ethusd: FromStr::from_str(s)
.expect("Etherscan API will always return properly formatted price; qed")
})),
_ => None,
}));
@@ -67,10 +68,14 @@ impl PriceInfo {
let client = try!(Client::new().map_err(|_| ()));
thread::spawn(move || {
let (tx, rx) = mpsc::channel();
let _ = client.request(FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice").unwrap(), SetPriceHandler {
set_price: set_price,
channel: tx,
}).ok().and_then(|_| rx.recv().ok());
let url = FromStr::from_str("http://api.etherscan.io/api?module=stats&action=ethprice")
.expect("string known to be a valid URL; qed");
let _ = client.request(
url,
SetPriceHandler {
set_price: set_price,
channel: tx,
}).ok().and_then(|_| rx.recv().ok());
client.close();
});
Ok(())

View File

@@ -700,7 +700,7 @@ impl TransactionQueue {
None => vec![],
};
for k in nonces_from_sender {
let order = self.current.drop(&sender, &k).unwrap();
let order = self.current.drop(&sender, &k).expect("transaction known to be in self.current; qed");
self.current.insert(sender, k, order.penalize());
}
// Same thing for future
@@ -709,7 +709,7 @@ impl TransactionQueue {
None => vec![],
};
for k in nonces_from_sender {
let order = self.future.drop(&sender, &k).unwrap();
let order = self.future.drop(&sender, &k).expect("transaction known to be in self.future; qed");
self.future.insert(sender, k, order.penalize());
}
}

View File

@@ -150,7 +150,8 @@ impl Spec {
if self.state_root_memo.read().is_none() {
*self.state_root_memo.write() = Some(self.genesis_state.root());
}
self.state_root_memo.read().as_ref().unwrap().clone()
self.state_root_memo.read().as_ref().cloned()
.expect("state root memo ensured to be set at this point; qed")
}
/// Get the known knodes of the network in enode format.

View File

@@ -520,7 +520,7 @@ impl State {
}
{
let mut trie = factories.trie.from_existing(db.as_hashdb_mut(), root).unwrap();
let mut trie = try!(factories.trie.from_existing(db.as_hashdb_mut(), root));
for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) {
a.state = AccountState::Committed;
match a.account {
@@ -691,14 +691,15 @@ impl State {
}
self.note_cache(a);
match &mut self.cache.borrow_mut().get_mut(a).unwrap().account {
&mut Some(ref mut acc) => not_default(acc),
slot => *slot = Some(default()),
}
// at this point the account is guaranteed to be in the cache.
// at this point the entry is guaranteed to be in the cache.
RefMut::map(self.cache.borrow_mut(), |c| {
let mut entry = c.get_mut(a).unwrap();
let mut entry = c.get_mut(a).expect("entry known to exist in the cache; qed");
match &mut entry.account {
&mut Some(ref mut acc) => not_default(acc),
slot => *slot = Some(default()),
}
// set the dirty flag after changing account data.
entry.state = AccountState::Dirty;
match entry.account {

View File

@@ -134,10 +134,11 @@ impl StateDB {
let hash_count_entry = db.get(COL_ACCOUNT_BLOOM, ACCOUNT_BLOOM_HASHCOUNT_KEY)
.expect("Low-level database error");
if hash_count_entry.is_none() {
return Bloom::new(ACCOUNT_BLOOM_SPACE, DEFAULT_ACCOUNT_PRESET);
}
let hash_count_bytes = hash_count_entry.unwrap();
let hash_count_bytes = match hash_count_entry {
Some(bytes) => bytes,
None => return Bloom::new(ACCOUNT_BLOOM_SPACE, DEFAULT_ACCOUNT_PRESET),
};
assert_eq!(hash_count_bytes.len(), 1);
let hash_count = hash_count_bytes[0];

View File

@@ -129,7 +129,7 @@ impl<T> TraceDB<T> where T: DatabaseExtras {
pub fn new(config: Config, tracesdb: Arc<Database>, extras: Arc<T>) -> Self {
let mut batch = DBTransaction::new(&tracesdb);
batch.put(db::COL_TRACE, b"version", TRACE_DB_VER);
tracesdb.write(batch).unwrap();
tracesdb.write(batch).expect("failed to update version");
TraceDB {
traces: RwLock::new(HashMap::new()),

View File

@@ -21,7 +21,7 @@ use std::cell::*;
use rlp::*;
use util::sha3::Hashable;
use util::{H256, Address, U256, Bytes, HeapSizeOf};
use ethkey::{Signature, sign, Secret, Public, recover, public_to_address, Error as EthkeyError};
use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError};
use error::*;
use evm::Schedule;
use header::BlockNumber;
@@ -143,7 +143,8 @@ impl Transaction {
/// Signs the transaction as coming from `sender`.
pub fn sign(self, secret: &Secret) -> SignedTransaction {
let sig = sign(secret, &self.hash()).unwrap();
let sig = ::ethkey::sign(secret, &self.hash())
.expect("data is valid and context has signing capabilities; qed");
self.with_signature(sig)
}

View File

@@ -108,7 +108,8 @@ pub fn verify_block_family(header: &Header, bytes: &[u8], engine: &Engine, bc: &
match bc.block_details(&hash) {
Some(details) => {
excluded.insert(details.parent.clone());
let b = bc.block(&hash).unwrap();
let b = bc.block(&hash)
.expect("parent already known to be stored; qed");
excluded.extend(BlockView::new(&b).uncle_hashes());
hash = details.parent;
}