Reduce number of unwwaps in api crate (#2681)
* Reduce number of unwwaps in api crate * Format use section
This commit is contained in:
@@ -41,7 +41,7 @@ impl HeaderHandler {
|
||||
return Ok(h);
|
||||
}
|
||||
if let Ok(height) = input.parse() {
|
||||
match w(&self.chain).get_header_by_height(height) {
|
||||
match w(&self.chain)?.get_header_by_height(height) {
|
||||
Ok(header) => return Ok(BlockHeaderPrintable::from_header(&header)),
|
||||
Err(_) => return Err(ErrorKind::NotFound)?,
|
||||
}
|
||||
@@ -50,7 +50,7 @@ impl HeaderHandler {
|
||||
let vec = util::from_hex(input)
|
||||
.map_err(|e| ErrorKind::Argument(format!("invalid input: {}", e)))?;
|
||||
let h = Hash::from_vec(&vec);
|
||||
let header = w(&self.chain)
|
||||
let header = w(&self.chain)?
|
||||
.get_block_header(&h)
|
||||
.context(ErrorKind::NotFound)?;
|
||||
Ok(BlockHeaderPrintable::from_header(&header))
|
||||
@@ -58,7 +58,7 @@ impl HeaderHandler {
|
||||
|
||||
fn get_header_for_output(&self, commit_id: String) -> Result<BlockHeaderPrintable, Error> {
|
||||
let oid = get_output(&self.chain, &commit_id)?.1;
|
||||
match w(&self.chain).get_header_for_output(&oid) {
|
||||
match w(&self.chain)?.get_header_for_output(&oid) {
|
||||
Ok(header) => Ok(BlockHeaderPrintable::from_header(&header)),
|
||||
Err(_) => Err(ErrorKind::NotFound)?,
|
||||
}
|
||||
@@ -85,22 +85,23 @@ pub struct BlockHandler {
|
||||
|
||||
impl BlockHandler {
|
||||
fn get_block(&self, h: &Hash) -> Result<BlockPrintable, Error> {
|
||||
let block = w(&self.chain).get_block(h).context(ErrorKind::NotFound)?;
|
||||
Ok(BlockPrintable::from_block(&block, w(&self.chain), false))
|
||||
let chain = w(&self.chain)?;
|
||||
let block = chain.get_block(h).context(ErrorKind::NotFound)?;
|
||||
BlockPrintable::from_block(&block, chain, false)
|
||||
.map_err(|_| ErrorKind::Internal("chain error".to_owned()).into())
|
||||
}
|
||||
|
||||
fn get_compact_block(&self, h: &Hash) -> Result<CompactBlockPrintable, Error> {
|
||||
let block = w(&self.chain).get_block(h).context(ErrorKind::NotFound)?;
|
||||
Ok(CompactBlockPrintable::from_compact_block(
|
||||
&block.into(),
|
||||
w(&self.chain),
|
||||
))
|
||||
let chain = w(&self.chain)?;
|
||||
let block = chain.get_block(h).context(ErrorKind::NotFound)?;
|
||||
CompactBlockPrintable::from_compact_block(&block.into(), chain)
|
||||
.map_err(|_| ErrorKind::Internal("chain error".to_owned()).into())
|
||||
}
|
||||
|
||||
// Try to decode the string as a height or a hash.
|
||||
fn parse_input(&self, input: String) -> Result<Hash, Error> {
|
||||
if let Ok(height) = input.parse() {
|
||||
match w(&self.chain).get_header_by_height(height) {
|
||||
match w(&self.chain)?.get_header_by_height(height) {
|
||||
Ok(header) => return Ok(header.hash()),
|
||||
Err(_) => return Err(ErrorKind::NotFound)?,
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use crate::types::*;
|
||||
use crate::util;
|
||||
use crate::util::secp::pedersen::Commitment;
|
||||
use crate::web::*;
|
||||
use failure::ResultExt;
|
||||
use hyper::{Body, Request, StatusCode};
|
||||
use std::sync::Weak;
|
||||
|
||||
@@ -32,7 +33,7 @@ pub struct ChainHandler {
|
||||
|
||||
impl ChainHandler {
|
||||
fn get_tip(&self) -> Result<Tip, Error> {
|
||||
let head = w(&self.chain)
|
||||
let head = w(&self.chain)?
|
||||
.head()
|
||||
.map_err(|e| ErrorKind::Internal(format!("can't get head: {}", e)))?;
|
||||
Ok(Tip::from_tip(head))
|
||||
@@ -53,7 +54,7 @@ pub struct ChainValidationHandler {
|
||||
|
||||
impl Handler for ChainValidationHandler {
|
||||
fn get(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
match w(&self.chain).validate(true) {
|
||||
match w_fut!(&self.chain).validate(true) {
|
||||
Ok(_) => response(StatusCode::OK, "{}"),
|
||||
Err(e) => response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -72,7 +73,7 @@ pub struct ChainCompactHandler {
|
||||
|
||||
impl Handler for ChainCompactHandler {
|
||||
fn post(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
match w(&self.chain).compact() {
|
||||
match w_fut!(&self.chain).compact() {
|
||||
Ok(_) => response(StatusCode::OK, "{}"),
|
||||
Err(e) => response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -118,13 +119,14 @@ impl OutputHandler {
|
||||
commitments: Vec<Commitment>,
|
||||
include_proof: bool,
|
||||
) -> Result<BlockOutputs, Error> {
|
||||
let header = w(&self.chain)
|
||||
let header = w(&self.chain)?
|
||||
.get_header_by_height(block_height)
|
||||
.map_err(|_| ErrorKind::NotFound)?;
|
||||
|
||||
// TODO - possible to compact away blocks we care about
|
||||
// in the period between accepting the block and refreshing the wallet
|
||||
let block = w(&self.chain)
|
||||
let chain = w(&self.chain)?;
|
||||
let block = chain
|
||||
.get_block(&header.hash())
|
||||
.map_err(|_| ErrorKind::NotFound)?;
|
||||
let outputs = block
|
||||
@@ -132,9 +134,10 @@ impl OutputHandler {
|
||||
.iter()
|
||||
.filter(|output| commitments.is_empty() || commitments.contains(&output.commit))
|
||||
.map(|output| {
|
||||
OutputPrintable::from_output(output, w(&self.chain), Some(&header), include_proof)
|
||||
OutputPrintable::from_output(output, chain.clone(), Some(&header), include_proof)
|
||||
})
|
||||
.collect();
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(ErrorKind::Internal("cain error".to_owned()))?;
|
||||
|
||||
Ok(BlockOutputs {
|
||||
header: BlockHeaderInfo::from_header(&header),
|
||||
|
||||
@@ -26,7 +26,7 @@ pub struct PeersAllHandler {
|
||||
|
||||
impl Handler for PeersAllHandler {
|
||||
fn get(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
let peers = &w(&self.peers).all_peers();
|
||||
let peers = &w_fut!(&self.peers).all_peers();
|
||||
json_response_pretty(&peers)
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ pub struct PeersConnectedHandler {
|
||||
|
||||
impl Handler for PeersConnectedHandler {
|
||||
fn get(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
let peers: Vec<PeerInfoDisplay> = w(&self.peers)
|
||||
let peers: Vec<PeerInfoDisplay> = w_fut!(&self.peers)
|
||||
.connected_peers()
|
||||
.iter()
|
||||
.map(|p| p.info.clone().into())
|
||||
@@ -73,7 +73,7 @@ impl Handler for PeerHandler {
|
||||
);
|
||||
}
|
||||
|
||||
match w(&self.peers).get_peer(peer_addr) {
|
||||
match w_fut!(&self.peers).get_peer(peer_addr) {
|
||||
Ok(peer) => json_response(&peer),
|
||||
Err(_) => response(StatusCode::NOT_FOUND, "peer not found"),
|
||||
}
|
||||
@@ -101,8 +101,8 @@ impl Handler for PeerHandler {
|
||||
};
|
||||
|
||||
match command {
|
||||
"ban" => w(&self.peers).ban_peer(addr, ReasonForBan::ManualBan),
|
||||
"unban" => w(&self.peers).unban_peer(addr),
|
||||
"ban" => w_fut!(&self.peers).ban_peer(addr, ReasonForBan::ManualBan),
|
||||
"unban" => w_fut!(&self.peers).unban_peer(addr),
|
||||
_ => return response(StatusCode::BAD_REQUEST, "invalid command"),
|
||||
};
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ use crate::util;
|
||||
use crate::util::RwLock;
|
||||
use crate::web::*;
|
||||
use failure::ResultExt;
|
||||
use futures::future::ok;
|
||||
use futures::future::{err, ok};
|
||||
use futures::Future;
|
||||
use hyper::{Body, Request, StatusCode};
|
||||
use std::sync::Weak;
|
||||
@@ -37,7 +37,7 @@ pub struct PoolInfoHandler {
|
||||
|
||||
impl Handler for PoolInfoHandler {
|
||||
fn get(&self, _req: Request<Body>) -> ResponseFuture {
|
||||
let pool_arc = w(&self.tx_pool);
|
||||
let pool_arc = w_fut!(&self.tx_pool);
|
||||
let pool = pool_arc.read();
|
||||
|
||||
json_response(&PoolInfo {
|
||||
@@ -63,7 +63,11 @@ impl PoolPushHandler {
|
||||
let params = QueryParams::from(req.uri().query());
|
||||
|
||||
let fluff = params.get("fluff").is_some();
|
||||
let pool_arc = w(&self.tx_pool).clone();
|
||||
let pool_arc = match w(&self.tx_pool) {
|
||||
//w(&self.tx_pool).clone();
|
||||
Ok(p) => p,
|
||||
Err(e) => return Box::new(err(e)),
|
||||
};
|
||||
|
||||
Box::new(
|
||||
parse_body(req)
|
||||
|
||||
@@ -45,12 +45,12 @@ pub struct StatusHandler {
|
||||
|
||||
impl StatusHandler {
|
||||
fn get_status(&self) -> Result<Status, Error> {
|
||||
let head = w(&self.chain)
|
||||
let head = w(&self.chain)?
|
||||
.head()
|
||||
.map_err(|e| ErrorKind::Internal(format!("can't get head: {}", e)))?;
|
||||
Ok(Status::from_tip_and_peers(
|
||||
head,
|
||||
w(&self.peers).peer_count(),
|
||||
w(&self.peers)?.peer_count(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,23 +45,26 @@ pub struct TxHashSetHandler {
|
||||
|
||||
impl TxHashSetHandler {
|
||||
// gets roots
|
||||
fn get_roots(&self) -> TxHashSet {
|
||||
TxHashSet::from_head(w(&self.chain))
|
||||
fn get_roots(&self) -> Result<TxHashSet, Error> {
|
||||
Ok(TxHashSet::from_head(w(&self.chain)?))
|
||||
}
|
||||
|
||||
// gets last n outputs inserted in to the tree
|
||||
fn get_last_n_output(&self, distance: u64) -> Vec<TxHashSetNode> {
|
||||
TxHashSetNode::get_last_n_output(w(&self.chain), distance)
|
||||
fn get_last_n_output(&self, distance: u64) -> Result<Vec<TxHashSetNode>, Error> {
|
||||
Ok(TxHashSetNode::get_last_n_output(w(&self.chain)?, distance))
|
||||
}
|
||||
|
||||
// gets last n outputs inserted in to the tree
|
||||
fn get_last_n_rangeproof(&self, distance: u64) -> Vec<TxHashSetNode> {
|
||||
TxHashSetNode::get_last_n_rangeproof(w(&self.chain), distance)
|
||||
fn get_last_n_rangeproof(&self, distance: u64) -> Result<Vec<TxHashSetNode>, Error> {
|
||||
Ok(TxHashSetNode::get_last_n_rangeproof(
|
||||
w(&self.chain)?,
|
||||
distance,
|
||||
))
|
||||
}
|
||||
|
||||
// gets last n outputs inserted in to the tree
|
||||
fn get_last_n_kernel(&self, distance: u64) -> Vec<TxHashSetNode> {
|
||||
TxHashSetNode::get_last_n_kernel(w(&self.chain), distance)
|
||||
fn get_last_n_kernel(&self, distance: u64) -> Result<Vec<TxHashSetNode>, Error> {
|
||||
Ok(TxHashSetNode::get_last_n_kernel(w(&self.chain)?, distance))
|
||||
}
|
||||
|
||||
// allows traversal of utxo set
|
||||
@@ -70,18 +73,21 @@ impl TxHashSetHandler {
|
||||
if max > 1000 {
|
||||
max = 1000;
|
||||
}
|
||||
let outputs = w(&self.chain)
|
||||
let chain = w(&self.chain)?;
|
||||
let outputs = chain
|
||||
.unspent_outputs_by_insertion_index(start_index, max)
|
||||
.context(ErrorKind::NotFound)?;
|
||||
Ok(OutputListing {
|
||||
let out = OutputListing {
|
||||
last_retrieved_index: outputs.0,
|
||||
highest_index: outputs.1,
|
||||
outputs: outputs
|
||||
.2
|
||||
.iter()
|
||||
.map(|x| OutputPrintable::from_output(x, w(&self.chain), None, true))
|
||||
.collect(),
|
||||
})
|
||||
.map(|x| OutputPrintable::from_output(x, chain.clone(), None, true))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(ErrorKind::Internal("cain error".to_owned()))?,
|
||||
};
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// return a dummy output with merkle proof for position filled out
|
||||
@@ -92,10 +98,9 @@ impl TxHashSetHandler {
|
||||
id
|
||||
)))?;
|
||||
let commit = Commitment::from_vec(c);
|
||||
let output_pos = w(&self.chain)
|
||||
.get_output_pos(&commit)
|
||||
.context(ErrorKind::NotFound)?;
|
||||
let merkle_proof = chain::Chain::get_merkle_proof_for_pos(&w(&self.chain), commit)
|
||||
let chain = w(&self.chain)?;
|
||||
let output_pos = chain.get_output_pos(&commit).context(ErrorKind::NotFound)?;
|
||||
let merkle_proof = chain::Chain::get_merkle_proof_for_pos(&chain, commit)
|
||||
.map_err(|_| ErrorKind::NotFound)?;
|
||||
Ok(OutputPrintable {
|
||||
output_type: OutputType::Coinbase,
|
||||
@@ -120,10 +125,10 @@ impl Handler for TxHashSetHandler {
|
||||
let id = parse_param_no_err!(params, "id", "".to_owned());
|
||||
|
||||
match right_path_element!(req) {
|
||||
"roots" => json_response_pretty(&self.get_roots()),
|
||||
"lastoutputs" => json_response_pretty(&self.get_last_n_output(last_n)),
|
||||
"lastrangeproofs" => json_response_pretty(&self.get_last_n_rangeproof(last_n)),
|
||||
"lastkernels" => json_response_pretty(&self.get_last_n_kernel(last_n)),
|
||||
"roots" => result_to_response(self.get_roots()),
|
||||
"lastoutputs" => result_to_response(self.get_last_n_output(last_n)),
|
||||
"lastrangeproofs" => result_to_response(self.get_last_n_rangeproof(last_n)),
|
||||
"lastkernels" => result_to_response(self.get_last_n_kernel(last_n)),
|
||||
"outputs" => result_to_response(self.outputs(start_index, max)),
|
||||
"merkleproof" => result_to_response(self.get_merkle_proof_for_output(&id)),
|
||||
_ => response(StatusCode::BAD_REQUEST, ""),
|
||||
|
||||
@@ -24,8 +24,9 @@ use std::sync::{Arc, Weak};
|
||||
// All handlers use `Weak` references instead of `Arc` to avoid cycles that
|
||||
// can never be destroyed. These 2 functions are simple helpers to reduce the
|
||||
// boilerplate of dealing with `Weak`.
|
||||
pub fn w<T>(weak: &Weak<T>) -> Arc<T> {
|
||||
weak.upgrade().unwrap()
|
||||
pub fn w<T>(weak: &Weak<T>) -> Result<Arc<T>, Error> {
|
||||
weak.upgrade()
|
||||
.ok_or_else(|| ErrorKind::Internal("failed to upgrade weak refernce".to_owned()).into())
|
||||
}
|
||||
|
||||
/// Retrieves an output from the chain given a commit id (a tiny bit iteratively)
|
||||
@@ -48,14 +49,16 @@ pub fn get_output(
|
||||
OutputIdentifier::new(OutputFeatures::Coinbase, &commit),
|
||||
];
|
||||
|
||||
for x in outputs.iter().filter(|x| w(chain).is_unspent(x).is_ok()) {
|
||||
let block_height = w(chain)
|
||||
let chain = w(chain)?;
|
||||
|
||||
for x in outputs.iter().filter(|x| chain.is_unspent(x).is_ok()) {
|
||||
let block_height = chain
|
||||
.get_header_for_output(&x)
|
||||
.context(ErrorKind::Internal(
|
||||
"Can't get header for output".to_owned(),
|
||||
))?
|
||||
.height;
|
||||
let output_pos = w(chain).get_output_pos(&x.commit).unwrap_or(0);
|
||||
let output_pos = chain.get_output_pos(&x.commit).unwrap_or(0);
|
||||
return Ok((Output::new(&commit, block_height, output_pos), x.clone()));
|
||||
}
|
||||
Err(ErrorKind::NotFound)?
|
||||
|
||||
Reference in New Issue
Block a user