]> Untitled Git - bdk-cli/commitdiff
Propagate PSBT decoding and parsing errors
authoremma31-dev <emmanuelfidel07@gmail.com>
Sat, 7 Nov 2026 16:15:39 +0000 (17:15 +0100)
committeremma31-dev <emmanuelfidel07@gmail.com>
Sat, 7 Nov 2026 16:15:40 +0000 (17:15 +0100)
- Decode Base64 and parse PSBTs without wrapping the error in `Error::Generic`
- Use the dedicated `Electrum`, `Esplora`, `BitcoinCoreRpcError` and `Chain`
  error variants in `BlockchainClient`
- Cover sign, finalize_psbt and broadcast error paths with integration tests

Related to #363.

src/client.rs
src/handlers/offline.rs
src/handlers/online.rs
tests/integration/offline.rs

index bce66a1892b2313affd363dbc8187bfa3587b083..8937178ff0ff40fb393ee7adb3e74514fb42c7fc 100644 (file)
@@ -83,21 +83,21 @@ impl BlockchainClient {
     pub async fn broadcast(&self, tx: Transaction) -> Result<Txid, Error> {
         match self {
             #[cfg(feature = "electrum")]
-            Self::Electrum { client, .. } => client
-                .transaction_broadcast(&tx)
-                .map_err(|e| Error::Generic(e.to_string())),
+            Self::Electrum { client, .. } => {
+                client.transaction_broadcast(&tx).map_err(Error::Electrum)
+            }
 
             #[cfg(feature = "esplora")]
             Self::Esplora { client, .. } => client
                 .broadcast(&tx)
                 .await
                 .map(|()| tx.compute_txid())
-                .map_err(|e| Error::Generic(e.to_string())),
+                .map_err(Error::Esplora),
 
             #[cfg(feature = "rpc")]
             Self::RpcClient { client } => client
                 .send_raw_transaction(&tx)
-                .map_err(|e| Error::Generic(e.to_string())),
+                .map_err(Error::BitcoinCoreRpcError),
 
             #[cfg(feature = "cbf")]
             Self::KyotoClient { client } => {
@@ -128,9 +128,7 @@ impl BlockchainClient {
                 client.populate_tx_cache(wallet.tx_graph().full_txs().map(|tx_node| tx_node.tx));
 
                 let update = client.sync(request, *batch_size, false)?;
-                wallet
-                    .apply_update(update)
-                    .map_err(|e| Error::Generic(e.to_string()))
+                wallet.apply_update(update).map_err(Error::Chain)
             }
             #[cfg(feature = "esplora")]
             Self::Esplora {
@@ -141,9 +139,7 @@ impl BlockchainClient {
                     .sync(request, *parallel_requests)
                     .await
                     .map_err(|e| *e)?;
-                wallet
-                    .apply_update(update)
-                    .map_err(|e| Error::Generic(e.to_string()))
+                wallet.apply_update(update).map_err(Error::Chain)
             }
             #[cfg(feature = "rpc")]
             Self::RpcClient { client } => {
@@ -190,9 +186,7 @@ impl BlockchainClient {
                 Ok(())
             }
             #[cfg(feature = "cbf")]
-            Self::KyotoClient { client } => sync_kyoto_client(wallet, client)
-                .await
-                .map_err(|e| Error::Generic(e.to_string())),
+            Self::KyotoClient { client } => sync_kyoto_client(wallet, client).await,
         }
     }
 }
@@ -307,7 +301,7 @@ pub(crate) fn new_blockchain_client(
                 ),
             };
             let client = bdk_bitcoind_rpc::bitcoincore_rpc::Client::new(url, auth)
-                .map_err(|e| Error::Generic(e.to_string()))?;
+                .map_err(Error::BitcoinCoreRpcError)?;
             BlockchainClient::RpcClient {
                 client: Box::new(client),
             }
@@ -364,9 +358,7 @@ pub async fn sync_kyoto_client(
 
     let update = handle.update_subscriber.lock().await.update().await?;
     tracing::info!("Received update: applying to wallet");
-    let events = wallet
-        .apply_update_events(update)
-        .map_err(|e| Error::Generic(format!("Failed to apply update: {e}")))?;
+    let events = wallet.apply_update_events(update).map_err(Error::Chain)?;
     crate::utils::print_wallet_events(&events);
 
     tracing::info!(
index 80a6de47683bba58e9610d5c16bc72ca332bab06..5250c67386c2bea63c934bb733fa14bb574d62ea 100644 (file)
@@ -654,10 +654,8 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for SignCommand {
 
     fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
         let wallet = &mut ctx.state.wallet;
-        let psbt_bytes = BASE64_STANDARD
-            .decode(&self.psbt)
-            .map_err(|e| Error::Generic(e.to_string()))?;
-        let mut psbt = Psbt::deserialize(&psbt_bytes).map_err(|e| Error::Generic(e.to_string()))?;
+        let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
+        let mut psbt = Psbt::deserialize(&psbt_bytes)?;
 
         let signopt = SignOptions {
             assume_height: self.assume_height,
@@ -708,10 +706,8 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for FinalizePsbtCommand {
 
     fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
         let wallet = &mut ctx.state.wallet;
-        let psbt_bytes = BASE64_STANDARD
-            .decode(&self.psbt)
-            .map_err(|e| Error::Generic(e.to_string()))?;
-        let mut psbt = Psbt::deserialize(&psbt_bytes).map_err(|e| Error::Generic(e.to_string()))?;
+        let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
+        let mut psbt = Psbt::deserialize(&psbt_bytes)?;
 
         let signopt = SignOptions {
             assume_height: self.assume_height,
index 25baf889711d04cfaed8da127c4cb41079e7d583..1a10f8572bce3fd194988a5ff4590b66f4f4b5e4 100644 (file)
@@ -296,9 +296,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SyncCommand {
                 print_wallet_events(&evicted_events);
             }
             #[cfg(feature = "cbf")]
-            KyotoClient { client } => sync_kyoto_client(wallet, client)
-                .await
-                .map_err(|e| Error::Generic(e.to_string()))?,
+            KyotoClient { client } => sync_kyoto_client(wallet, client).await?,
         }
         Ok(StatusResult {
             message: "Wallet synced successfully.".to_string(),
@@ -343,9 +341,7 @@ impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for BroadcastCommand {
 
         let tx = match (&self.psbt, &self.tx) {
             (Some(psbt), None) => {
-                let psbt = BASE64_STANDARD
-                    .decode(psbt)
-                    .map_err(|e| Error::Generic(e.to_string()))?;
+                let psbt = BASE64_STANDARD.decode(psbt)?;
                 let psbt: Psbt = Psbt::deserialize(&psbt)?;
                 is_final(&psbt)?;
                 psbt.extract_tx()?
index c4be0a21b38dc60f7edc0063f8d70be0572f06d2..772ff53f0968d2c8d63ed7358ff5df074ed20606 100644 (file)
@@ -45,6 +45,63 @@ mod test_offline {
         (cli, cmd_init)
     }
 
+    #[test]
+    fn test_sign_rejects_invalid_base64() {
+        let (cli, mut cmd_init) = setup_wallet_config();
+        cmd_init.assert().success();
+
+        cli.wallet_cmd(&["--wallet", WALLET_NAME, "sign", "!!!"])
+            .assert()
+            .code(1)
+            .stderr(predicate::str::contains("Base64 decoding error:"));
+    }
+
+    #[test]
+    fn test_sign_rejects_invalid_psbt() {
+        let (cli, mut cmd_init) = setup_wallet_config();
+        cmd_init.assert().success();
+
+        // Valid Base64 for "hello", which is not a serialized PSBT.
+        cli.wallet_cmd(&["--wallet", WALLET_NAME, "sign", "aGVsbG8="])
+            .assert()
+            .code(1)
+            .stderr(predicate::str::contains("PsbtError:"));
+    }
+
+    #[test]
+    fn test_finalize_psbt_rejects_invalid_base64() {
+        let (cli, mut cmd_init) = setup_wallet_config();
+        cmd_init.assert().success();
+
+        cli.wallet_cmd(&["--wallet", WALLET_NAME, "finalize_psbt", "!!!"])
+            .assert()
+            .code(1)
+            .stderr(predicate::str::contains("Base64 decoding error:"));
+    }
+
+    #[test]
+    fn test_finalize_psbt_rejects_invalid_psbt() {
+        let (cli, mut cmd_init) = setup_wallet_config();
+        cmd_init.assert().success();
+
+        // Valid Base64 for "hello", which is not a serialized PSBT.
+        cli.wallet_cmd(&["--wallet", WALLET_NAME, "finalize_psbt", "aGVsbG8="])
+            .assert()
+            .code(1)
+            .stderr(predicate::str::contains("PsbtError:"));
+    }
+
+    #[test]
+    fn test_broadcast_rejects_invalid_base64() {
+        let (cli, mut cmd_init) = setup_wallet_config();
+        cmd_init.assert().success();
+
+        cli.wallet_cmd(&["--wallet", WALLET_NAME, "broadcast", "--psbt", "!!!"])
+            .assert()
+            .code(1)
+            .stderr(predicate::str::contains("Base64 decoding error:"));
+    }
+
     #[test]
     fn test_new_and_unused_address() {
         let (cli, mut cmd_init) = setup_wallet_config();