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 all commits
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dapps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ethcore-util = { path = "../util" }
fetch = { path = "../util/fetch" }
parity-ui = { path = "./ui" }
parity-dapps-glue = { path = "./js-glue" }
mime = "0.2"
### DEPRECATED
parity-dapps = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" }
parity-dapps-home = { git = "https://github.com/ethcore/parity-ui.git", version = "1.4" }
Expand Down
1 change: 1 addition & 0 deletions dapps/js-glue/src/lib.rs.in
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::default::Default;
pub struct File {
pub path: &'static str,
pub content: &'static [u8],
// TODO: use strongly-typed MIME.
pub content_type: &'static str,
}

Expand Down
12 changes: 8 additions & 4 deletions dapps/src/api/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ use serde_json;
use endpoint::Handler;
use handlers::{ContentHandler, EchoHandler};

pub fn as_json<T : Serialize>(val: &T) -> Box<Handler> {
Box::new(ContentHandler::ok(serde_json::to_string(val).unwrap(), "application/json".to_owned()))
pub fn as_json<T: Serialize>(val: &T) -> Box<Handler> {
let json = serde_json::to_string(val)
.expect("serialization to string is infallible; qed");
Box::new(ContentHandler::ok(json, mime!(Application/Json)))
}

pub fn as_json_error<T : Serialize>(val: &T) -> Box<Handler> {
Box::new(ContentHandler::not_found(serde_json::to_string(val).unwrap(), "application/json".to_owned()))
pub fn as_json_error<T: Serialize>(val: &T) -> Box<Handler> {
let json = serde_json::to_string(val)
.expect("serialization to string is infallible; qed");
Box::new(ContentHandler::not_found(json, mime!(Application/Json)))
}

pub fn ping_response(local_domain: &str) -> Box<Handler> {
Expand Down
7 changes: 4 additions & 3 deletions dapps/src/apps/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ impl ContentCache {
}

let mut removed = Vec::with_capacity(len - expected_size);
while len > expected_size {
let entry = self.cache.pop_front().unwrap();

while self.cache.len() > expected_size {
let entry = self.cache.pop_front().expect("expected_size bounded at 0, len is greater; qed");

match entry.1 {
ContentStatus::Fetching(ref fetch) => {
trace!(target: "dapps", "Aborting {} because of limit.", entry.0);
Expand All @@ -73,7 +75,6 @@ impl ContentCache {
}

removed.push(entry);
len -= 1;
}
removed
}
Expand Down
6 changes: 3 additions & 3 deletions dapps/src/apps/urlhint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ impl URLHintContract {
}

let mut it = vec.into_iter();
let account_slash_repo = it.next().unwrap();
let commit = it.next().unwrap();
let owner = it.next().unwrap();
let account_slash_repo = it.next().expect("element 0 of 3-len vector known to exist; qed");
let commit = it.next().expect("element 1 of 3-len vector known to exist; qed");
let owner = it.next().expect("element 2 of 3-len vector known to exist qed");

match (account_slash_repo, commit, owner) {
(Token::String(account_slash_repo), Token::FixedBytes(commit), Token::Address(owner)) => {
Expand Down
15 changes: 8 additions & 7 deletions dapps/src/handlers/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use std::io::Write;
use hyper::{header, server, Decoder, Encoder, Next};
use hyper::net::HttpStream;
use hyper::mime::Mime;
use hyper::status::StatusCode;

use util::version;
Expand All @@ -29,22 +30,22 @@ use handlers::add_security_headers;
pub struct ContentHandler {
code: StatusCode,
content: String,
mimetype: String,
mimetype: Mime,
write_pos: usize,
safe_to_embed_at_port: Option<u16>,
}

impl ContentHandler {
pub fn ok(content: String, mimetype: String) -> Self {
pub fn ok(content: String, mimetype: Mime) -> Self {
Self::new(StatusCode::Ok, content, mimetype)
}

pub fn not_found(content: String, mimetype: String) -> Self {
pub fn not_found(content: String, mimetype: Mime) -> Self {
Self::new(StatusCode::NotFound, content, mimetype)
}

pub fn html(code: StatusCode, content: String, embeddable_at: Option<u16>) -> Self {
Self::new_embeddable(code, content, "text/html".into(), embeddable_at)
Self::new_embeddable(code, content, mime!(Text/Html), embeddable_at)
}

pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>) -> Self {
Expand All @@ -61,11 +62,11 @@ impl ContentHandler {
), embeddable_at)
}

pub fn new(code: StatusCode, content: String, mimetype: String) -> Self {
pub fn new(code: StatusCode, content: String, mimetype: Mime) -> Self {
Self::new_embeddable(code, content, mimetype, None)
}

pub fn new_embeddable(code: StatusCode, content: String, mimetype: String, embeddable_at: Option<u16>) -> Self {
pub fn new_embeddable(code: StatusCode, content: String, mimetype: Mime, embeddable_at: Option<u16>) -> Self {
ContentHandler {
code: code,
content: content,
Expand All @@ -87,7 +88,7 @@ impl server::Handler<HttpStream> for ContentHandler {

fn on_response(&mut self, res: &mut server::Response) -> Next {
res.set_status(self.code);
res.headers_mut().set(header::ContentType(self.mimetype.parse().unwrap()));
res.headers_mut().set(header::ContentType(self.mimetype.clone()));
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port.clone());
Next::write()
}
Expand Down
12 changes: 8 additions & 4 deletions dapps/src/handlers/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl server::Handler<HttpStream> for EchoHandler {

// Don't even read the payload if origin is forbidden!
if let Cors::Forbidden = self.cors {
self.handler = Some(ContentHandler::ok(String::new(), "text/plain".into()));
self.handler = Some(ContentHandler::ok(String::new(), mime!(Text/Plain)));
Next::write()
} else {
Next::read()
Expand All @@ -92,7 +92,7 @@ impl server::Handler<HttpStream> for EchoHandler {
fn on_request_readable(&mut self, decoder: &mut Decoder<HttpStream>) -> Next {
match decoder.read_to_string(&mut self.content) {
Ok(0) => {
self.handler = Some(ContentHandler::ok(self.content.clone(), "application/json".into()));
self.handler = Some(ContentHandler::ok(self.content.clone(), mime!(Application/Json)));
Next::write()
},
Ok(_) => Next::read(),
Expand All @@ -114,11 +114,15 @@ impl server::Handler<HttpStream> for EchoHandler {
]));
headers.set(header::AccessControlAllowOrigin::Value(domain.clone()));
}
self.handler.as_mut().unwrap().on_response(res)
self.handler.as_mut()
.expect("handler always set in on_request, which is before now; qed")
.on_response(res)
}

fn on_response_writable(&mut self, encoder: &mut Encoder<HttpStream>) -> Next {
self.handler.as_mut().unwrap().on_response_writable(encoder)
self.handler.as_mut()
.expect("handler always set in on_request, which is before now; qed")
.on_response_writable(encoder)
}
}

Expand Down
11 changes: 8 additions & 3 deletions dapps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,8 @@
#![warn(missing_docs)]
#![cfg_attr(feature="nightly", plugin(clippy))]

#[macro_use]
extern crate log;
extern crate url as url_lib;
extern crate hyper;
extern crate url as url_lib;
extern crate unicase;
extern crate serde;
extern crate serde_json;
Expand All @@ -61,6 +59,13 @@ extern crate ethcore_rpc;
extern crate ethcore_util as util;
extern crate linked_hash_map;
extern crate fetch;

#[macro_use]
extern crate log;

#[macro_use]
extern crate mime;

#[cfg(test)]
extern crate ethcore_devtools as devtools;

Expand Down
7 changes: 6 additions & 1 deletion dapps/src/page/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,12 @@ impl<T: Dapp> server::Handler<HttpStream> for PageHandler<T> {
match self.file {
ServedFile::File(ref f) => {
res.set_status(StatusCode::Ok);
res.headers_mut().set(header::ContentType(f.content_type().parse().unwrap()));

match f.content_type().parse() {
Ok(mime) => res.headers_mut().set(header::ContentType(mime)),
Err(()) => debug!(target: "page_handler", "invalid MIME type: {}", f.content_type()),
}

// Security headers:
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port);
Next::write()
Expand Down
2 changes: 1 addition & 1 deletion dapps/src/proxypac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function FindProxyForURL(url, host) {{
}}
"#,
DAPPS_DOMAIN, path.host, path.port);
Box::new(ContentHandler::ok(content, "application/javascript".to_owned()))
Box::new(ContentHandler::ok(content, mime!(Application/Javascript)))
}
}

Expand Down
16 changes: 12 additions & 4 deletions dapps/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,15 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
self.handler = match endpoint {
// First check special endpoints
(ref path, ref endpoint) if self.special.contains_key(endpoint) => {
self.special.get(endpoint).unwrap().to_async_handler(path.clone().unwrap_or_default(), control)
self.special.get(endpoint)
.expect("special known to contain key; qed")
.to_async_handler(path.clone().unwrap_or_default(), control)
},
// Then delegate to dapp
(Some(ref path), _) if self.endpoints.contains_key(&path.app_id) => {
self.endpoints.get(&path.app_id).unwrap().to_async_handler(path.clone(), control)
self.endpoints.get(&path.app_id)
.expect("special known to contain key; qed")
.to_async_handler(path.clone(), control)
},
// Try to resolve and fetch the dapp
(Some(ref path), _) if self.fetch.contains(&path.app_id) => {
Expand All @@ -108,7 +112,9 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
},
// RPC by default
_ => {
self.special.get(&SpecialEndpoint::Rpc).unwrap().to_async_handler(EndpointPath::default(), control)
self.special.get(&SpecialEndpoint::Rpc)
.expect("RPC endpoint always stored; qed")
.to_async_handler(EndpointPath::default(), control)
}
};

Expand Down Expand Up @@ -143,7 +149,9 @@ impl<A: Authorization> Router<A> {
allowed_hosts: Option<Vec<String>>,
) -> Self {

let handler = special.get(&SpecialEndpoint::Utils).unwrap().to_handler(EndpointPath::default());
let handler = special.get(&SpecialEndpoint::Utils)
.expect("Utils endpoint always stored; qed")
.to_handler(EndpointPath::default());
Router {
control: Some(control),
main_page: main_page,
Expand Down
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
Loading