From cf5a3752d325472b64b16610db6a4cb12b1570bf Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Thu, 30 Sep 2021 17:19:24 +1000 Subject: [PATCH] Improve readability of special handling for electrum error The default path through the function would be to propagate every error. However, we want to inspect whether it is one very specific error. Make this clear in the code structure by having a dedicated `if let` for the special case but keep using `?` afterwards. --- daemon/src/wallet.rs | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/daemon/src/wallet.rs b/daemon/src/wallet.rs index c26fdad..c5ce40b 100644 --- a/daemon/src/wallet.rs +++ b/daemon/src/wallet.rs @@ -1,11 +1,11 @@ use crate::model::WalletInfo; -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result}; use bdk::bitcoin::util::bip32::ExtendedPrivKey; use bdk::bitcoin::util::psbt::PartiallySignedTransaction; use bdk::bitcoin::{Amount, PublicKey, Transaction, Txid}; use bdk::blockchain::{ElectrumBlockchain, NoopProgress}; use bdk::wallet::AddressIndex; -use bdk::{electrum_client, Error, KeychainKind, SignOptions}; +use bdk::{electrum_client, KeychainKind, SignOptions}; use cfd_protocol::{PartyParams, WalletExt}; use rocket::serde::json::Value; use std::path::Path; @@ -98,29 +98,24 @@ impl Wallet { let wallet = self.wallet.lock().await; // TODO: Optimize this match to be a map_err / more readable in general let txid = tx.txid(); - match wallet.broadcast(tx) { - Ok(txid) => Ok(txid), - Err(e) => { - if let Error::Electrum(electrum_client::Error::Protocol(ref value)) = e { - let error_code = match parse_rpc_protocol_error_code(value) { - Ok(error_code) => error_code, - Err(inner) => { - tracing::error!( - "Failed to parse error code from RPC message: {}", - inner - ); - return Err(anyhow!(e)); - } - }; - - if error_code == i64::from(RpcErrorCode::RpcVerifyAlreadyInChain) { - return Ok(txid); - } - } - - Err(anyhow!(e)) + + let result = wallet.broadcast(tx); + + if let Err(&bdk::Error::Electrum(electrum_client::Error::Protocol(ref value))) = + result.as_ref() + { + let error_code = parse_rpc_protocol_error_code(value).with_context(|| { + format!("Failed to parse electrum error response '{:?}'", value) + })?; + + if error_code == i64::from(RpcErrorCode::RpcVerifyAlreadyInChain) { + return Ok(txid); } } + + let txid = result?; + + Ok(txid) } }