Skip to content

Commit

Permalink
Less cloning and additional pattern simplifications (#3223)
Browse files Browse the repository at this point in the history
* API Cleanup

* Chain Cleanup

* Core Cleanup

* Keychain Cleanup

* P2P Cleanup

* Pool Cleanup

* Store Cleanup

* Util Cleanup

* Cleanup clone_from_slice

* Address jasper comments
  • Loading branch information
quentinlesceller authored Feb 12, 2020
1 parent c4e6971 commit 04a0123
Show file tree
Hide file tree
Showing 43 changed files with 267 additions and 326 deletions.
2 changes: 1 addition & 1 deletion api/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ impl Handler for BasicAuthURIMiddleware {
unauthorized_response(&self.basic_realm)
}
} else {
return next_handler.call(req, handlers);
next_handler.call(req, handlers)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions api/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub type ClientResponseFuture<T> = Box<dyn Future<Item = T, Error = Error> + Sen
/// Helper function to easily issue a HTTP GET request against a given URL that
/// returns a JSON object. Handles request building, JSON deserialization and
/// response code checking.
pub fn get<'a, T>(url: &'a str, api_secret: Option<String>) -> Result<T, Error>
pub fn get<T>(url: &str, api_secret: Option<String>) -> Result<T, Error>
where
for<'de> T: Deserialize<'de>,
{
Expand All @@ -44,7 +44,7 @@ where
/// Helper function to easily issue an async HTTP GET request against a given
/// URL that returns a future. Handles request building, JSON deserialization
/// and response code checking.
pub fn get_async<'a, T>(url: &'a str, api_secret: Option<String>) -> ClientResponseFuture<T>
pub fn get_async<T>(url: &str, api_secret: Option<String>) -> ClientResponseFuture<T>
where
for<'de> T: Deserialize<'de> + Send + 'static,
{
Expand Down
24 changes: 8 additions & 16 deletions api/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,14 +191,10 @@ impl OwnerAPIHandlerV2 {

impl crate::router::Handler for OwnerAPIHandlerV2 {
fn post(&self, req: Request<Body>) -> ResponseFuture {
Box::new(
self.handle_post_request(req)
.and_then(|r| ok(r))
.or_else(|e| {
error!("Request Error: {:?}", e);
ok(create_error_response(e))
}),
)
Box::new(self.handle_post_request(req).and_then(ok).or_else(|e| {
error!("Request Error: {:?}", e);
ok(create_error_response(e))
}))
}

fn options(&self, _req: Request<Body>) -> ResponseFuture {
Expand Down Expand Up @@ -260,14 +256,10 @@ impl ForeignAPIHandlerV2 {

impl crate::router::Handler for ForeignAPIHandlerV2 {
fn post(&self, req: Request<Body>) -> ResponseFuture {
Box::new(
self.handle_post_request(req)
.and_then(|r| ok(r))
.or_else(|e| {
error!("Request Error: {:?}", e);
ok(create_error_response(e))
}),
)
Box::new(self.handle_post_request(req).and_then(ok).or_else(|e| {
error!("Request Error: {:?}", e);
ok(create_error_response(e))
}))
}

fn options(&self, _req: Request<Body>) -> ResponseFuture {
Expand Down
30 changes: 12 additions & 18 deletions api/src/handlers/blocks_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl HeaderHandler {
if let Ok(height) = input.parse() {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(BlockHeaderPrintable::from_header(&header)),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
check_block_param(&input)?;
Expand All @@ -60,14 +60,14 @@ impl HeaderHandler {
let oid = get_output(&self.chain, &commit_id)?.1;
match w(&self.chain)?.get_header_for_output(&oid) {
Ok(header) => Ok(BlockHeaderPrintable::from_header(&header)),
Err(_) => Err(ErrorKind::NotFound)?,
Err(_) => Err(ErrorKind::NotFound.into()),
}
}

pub fn get_header_v2(&self, h: &Hash) -> Result<BlockHeaderPrintable, Error> {
let chain = w(&self.chain)?;
let header = chain.get_block_header(h).context(ErrorKind::NotFound)?;
return Ok(BlockHeaderPrintable::from_header(&header));
Ok(BlockHeaderPrintable::from_header(&header))
}

// Try to get hash from height, hash or output commit
Expand All @@ -80,7 +80,7 @@ impl HeaderHandler {
if let Some(height) = height {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
if let Some(hash) = hash {
Expand All @@ -90,12 +90,10 @@ impl HeaderHandler {
let oid = get_output_v2(&self.chain, &commit, false, false)?.1;
match w(&self.chain)?.get_header_for_output(&oid) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
return Err(ErrorKind::Argument(
"not a valid hash, height or output commit".to_owned(),
))?;
Err(ErrorKind::Argument("not a valid hash, height or output commit".to_owned()).into())
}
}

Expand Down Expand Up @@ -145,7 +143,7 @@ impl BlockHandler {
if let Ok(height) = input.parse() {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
check_block_param(&input)?;
Expand All @@ -164,7 +162,7 @@ impl BlockHandler {
if let Some(height) = height {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
if let Some(hash) = hash {
Expand All @@ -174,23 +172,19 @@ impl BlockHandler {
let oid = get_output_v2(&self.chain, &commit, false, false)?.1;
match w(&self.chain)?.get_header_for_output(&oid) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
}
}
return Err(ErrorKind::Argument(
"not a valid hash, height or output commit".to_owned(),
))?;
Err(ErrorKind::Argument("not a valid hash, height or output commit".to_owned()).into())
}
}

fn check_block_param(input: &String) -> Result<(), Error> {
fn check_block_param(input: &str) -> Result<(), Error> {
lazy_static! {
static ref RE: Regex = Regex::new(r"[0-9a-fA-F]{64}").unwrap();
}
if !RE.is_match(&input) {
return Err(ErrorKind::Argument(
"Not a valid hash or height.".to_owned(),
))?;
return Err(ErrorKind::Argument("Not a valid hash or height.".to_owned()).into());
}
Ok(())
}
Expand Down
10 changes: 5 additions & 5 deletions api/src/handlers/chain_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl OutputHandler {
outputs = [&outputs[..], &block_output_batch[..]].concat();
}
}
return Ok(outputs);
Ok(outputs)
}

// allows traversal of utxo set
Expand Down Expand Up @@ -327,7 +327,7 @@ impl OutputHandler {
let mut return_vec = vec![];
for i in (start_height..=end_height).rev() {
if let Ok(res) = self.outputs_at_height(i, commitments.clone(), include_rp) {
if res.outputs.len() > 0 {
if !res.outputs.is_empty() {
return_vec.push(res);
}
}
Expand Down Expand Up @@ -359,7 +359,7 @@ impl OutputHandler {
include_rproof,
include_merkle_proof,
) {
if res.len() > 0 {
if !res.is_empty() {
return_vec = [&return_vec[..], &res[..]].concat();
}
}
Expand Down Expand Up @@ -394,7 +394,7 @@ impl KernelHandler {
.trim_end_matches('/')
.rsplit('/')
.next()
.ok_or(ErrorKind::RequestError("missing excess".into()))?;
.ok_or_else(|| ErrorKind::RequestError("missing excess".into()))?;
let excess = util::from_hex(excess.to_owned())
.map_err(|_| ErrorKind::RequestError("invalid excess hex".into()))?;
if excess.len() != 33 {
Expand Down Expand Up @@ -447,7 +447,7 @@ impl KernelHandler {
min_height: Option<u64>,
max_height: Option<u64>,
) -> Result<LocatedTxKernel, Error> {
let excess = util::from_hex(excess.to_owned())
let excess = util::from_hex(excess)
.map_err(|_| ErrorKind::RequestError("invalid excess hex".into()))?;
if excess.len() != 33 {
return Err(ErrorKind::RequestError("invalid excess length".into()).into());
Expand Down
8 changes: 4 additions & 4 deletions api/src/handlers/pool_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ impl PoolHandler {
.blockchain
.chain_head()
.context(ErrorKind::Internal("Failed to get chain head".to_owned()))?;
let res = tx_pool
tx_pool
.add_to_pool(source, tx, !fluff.unwrap_or(false), &header)
.context(ErrorKind::Internal("Failed to update pool".to_owned()))?;
Ok(res)
Ok(())
}
}
/// Dummy wrapper for the hex-encoded serialized transaction.
Expand Down Expand Up @@ -141,10 +141,10 @@ impl PoolPushHandler {
.blockchain
.chain_head()
.context(ErrorKind::Internal("Failed to get chain head".to_owned()))?;
let res = tx_pool
tx_pool
.add_to_pool(source, tx, !fluff, &header)
.context(ErrorKind::Internal("Failed to update pool".to_owned()))?;
Ok(res)
Ok(())
}),
)
}
Expand Down
2 changes: 1 addition & 1 deletion api/src/handlers/server_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl Handler for KernelDownloadHandler {
} else {
response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("requesting kernel data from peer failed (no peers)"),
"requesting kernel data from peer failed (no peers)".to_string(),
)
}
}
Expand Down
15 changes: 8 additions & 7 deletions api/src/handlers/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub fn get_output(
}
}
}
Err(ErrorKind::NotFound)?
Err(ErrorKind::NotFound.into())
}

/// Retrieves an output from the chain given a commit id (a tiny bit iteratively)
Expand Down Expand Up @@ -102,10 +102,11 @@ pub fn get_output_v2(
match res {
Ok(output_pos) => match chain.get_unspent_output_at(output_pos.position) {
Ok(output) => {
let mut header = None;
if include_merkle_proof && output.is_coinbase() {
header = chain.get_header_by_height(output_pos.height).ok();
}
let header = if include_merkle_proof && output.is_coinbase() {
chain.get_header_by_height(output_pos.height).ok()
} else {
None
};
match OutputPrintable::from_output(
&output,
chain.clone(),
Expand All @@ -124,7 +125,7 @@ pub fn get_output_v2(
}
}
}
Err(_) => return Err(ErrorKind::NotFound)?,
Err(_) => return Err(ErrorKind::NotFound.into()),
},
Err(e) => {
trace!(
Expand All @@ -136,5 +137,5 @@ pub fn get_output_v2(
}
}
}
Err(ErrorKind::NotFound)?
Err(ErrorKind::NotFound.into())
}
2 changes: 1 addition & 1 deletion api/src/handlers/version_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::web::*;
use hyper::{Body, Request};
use std::sync::Weak;

const CRATE_VERSION: &'static str = env!("CARGO_PKG_VERSION");
const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Version handler. Get running node API version
/// GET /v1/version
Expand Down
10 changes: 5 additions & 5 deletions api/src/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,7 @@ impl TLSConfig {
let keys = pemfile::pkcs8_private_keys(&mut reader)
.map_err(|_| ErrorKind::Internal("failed to load private key".to_string()))?;
if keys.len() != 1 {
return Err(ErrorKind::Internal(
"expected a single private key".to_string(),
))?;
return Err(ErrorKind::Internal("expected a single private key".to_string()).into());
}
Ok(keys[0].clone())
}
Expand Down Expand Up @@ -193,7 +191,8 @@ impl ApiServer {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
"Can't start HTTP API server, it's running already".to_string(),
))?;
)
.into());
}
let (tx, _rx) = oneshot::channel::<()>();
self.shutdown_sender = Some(tx);
Expand Down Expand Up @@ -222,7 +221,8 @@ impl ApiServer {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
"Can't start HTTPS API server, it's running already".to_string(),
))?;
)
.into());
}

let tls_conf = conf.build_server_config()?;
Expand Down
20 changes: 10 additions & 10 deletions api/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,16 @@ pub trait Handler {
req: Request<Body>,
mut _handlers: Box<dyn Iterator<Item = HandlerObj>>,
) -> ResponseFuture {
match req.method() {
&Method::GET => self.get(req),
&Method::POST => self.post(req),
&Method::PUT => self.put(req),
&Method::DELETE => self.delete(req),
&Method::PATCH => self.patch(req),
&Method::OPTIONS => self.options(req),
&Method::CONNECT => self.connect(req),
&Method::TRACE => self.trace(req),
&Method::HEAD => self.head(req),
match *req.method() {
Method::GET => self.get(req),
Method::POST => self.post(req),
Method::PUT => self.put(req),
Method::DELETE => self.delete(req),
Method::PATCH => self.patch(req),
Method::OPTIONS => self.options(req),
Method::CONNECT => self.connect(req),
Method::TRACE => self.trace(req),
Method::HEAD => self.head(req),
_ => not_found(),
}
}
Expand Down
Loading

0 comments on commit 04a0123

Please sign in to comment.