Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

sweep most unwraps from ethcore crate, dapps crate #2762

Merged
merged 3 commits into from
Oct 20, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions ethcore/src/account_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
}

Expand All @@ -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));
Expand Down
2 changes: 1 addition & 1 deletion ethcore/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
3 changes: 2 additions & 1 deletion ethcore/src/blockchain/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 11 additions & 6 deletions ethcore/src/cache_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
}
6 changes: 5 additions & 1 deletion ethcore/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,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);
Expand Down
8 changes: 6 additions & 2 deletions ethcore/src/engines/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
}
6 changes: 3 additions & 3 deletions ethcore/src/evm/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion ethcore/src/evm/jit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 10 additions & 2 deletions ethcore/src/executive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error is not really possible at that point (sender is validated much earlier)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, but it's not ensured at compile-time. so we could either expect (which depends on a specific usage of the function, and might get broken in the future) or just do nothing whenever the constraints of the function aren't met.

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);

Expand Down
10 changes: 6 additions & 4 deletions ethcore/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand All @@ -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
}
}
}
Expand Down
10 changes: 7 additions & 3 deletions ethcore/src/miner/miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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(),
}
Expand Down
15 changes: 10 additions & 5 deletions ethcore/src/miner/price_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}));
Expand All @@ -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(())
Expand Down
4 changes: 2 additions & 2 deletions ethcore/src/miner/transaction_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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());
}
}
Expand Down
3 changes: 2 additions & 1 deletion ethcore/src/spec/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 9 additions & 8 deletions ethcore/src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,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 {
Expand Down Expand Up @@ -688,14 +688,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 {
Expand Down
9 changes: 5 additions & 4 deletions ethcore/src/state_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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];

Expand Down
2 changes: 1 addition & 1 deletion ethcore/src/trace/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
5 changes: 3 additions & 2 deletions ethcore/src/types/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
}

Expand Down
3 changes: 2 additions & 1 deletion ethcore/src/verification/verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down