From c9900317e8007b11ec571cc931de6b6ae9208490 Mon Sep 17 00:00:00 2001 From: Jeremiah Jacob Date: Thu, 15 Oct 2026 13:14:32 +0100 Subject: [PATCH] feat: expose wallet try_finalize_psbt outcomes Expose detailed per-input finalization outcomes without changing the existing finalize_psbt API. Preserve malformed input index and length errors and cover finalization, failure mapping, output metadata, and Swift/Kotlin binding round trips. --- .../org/bitcoindevkit/FinalizePsbtTest.kt | 109 ++++++++++++++++++ bdk-ffi/src/error.rs | 17 +++ bdk-ffi/src/tests/wallet.rs | 109 ++++++++++++++++++ bdk-ffi/src/types.rs | 60 +++++++++- bdk-ffi/src/wallet.rs | 33 +++++- .../BitcoinDevKitTests/WalletTests.swift | 23 ++++ 6 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/FinalizePsbtTest.kt diff --git a/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/FinalizePsbtTest.kt b/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/FinalizePsbtTest.kt new file mode 100644 index 000000000..6bc43a4ca --- /dev/null +++ b/bdk-android/lib/src/androidTest/kotlin/org/bitcoindevkit/FinalizePsbtTest.kt @@ -0,0 +1,109 @@ +package org.bitcoindevkit + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.junit.runner.RunWith +import org.kotlinbitcointools.regtesttoolbox.regenv.RegEnv +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds + +@RunWith(AndroidJUnit4::class) +class FinalizePsbtTest { + @Test + fun tryFinalizePsbtReportsInputOutcomes() { + val wallet = Wallet( + descriptor = BIP84_DESCRIPTOR, + changeDescriptor = BIP84_CHANGE_DESCRIPTOR, + network = Network.REGTEST, + persister = Persister.newInMemory() + ) + // Two unknown inputs: the second already has a final witness. + val psbt = Psbt("cHNidP8BAFwCAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAP////8AAAAAAAAAAQgDAQEBAA==") + val outcome = wallet.tryFinalizePsbt(psbt) + + assertFalse(outcome.isFinalized) + assertEquals(2, outcome.outcomes.size) + assertEquals(FinalizeInputOutcome.MissingDescriptor, outcome.outcomes[0uL]) + assertEquals(FinalizeInputOutcome.AlreadyFinalized, outcome.outcomes[1uL]) + assertFalse(outcome.outcomes.getValue(0uL).isFinalized()) + assertTrue(outcome.outcomes.getValue(1uL).isFinalized()) + } + + @Test + fun tryFinalizePsbtTransitionsFromUnsignedToFinalized() { + runBlocking { + val regtestEnv = RegEnv.connectTo( + host = "10.0.2.2", + walletName = "faucet", + username = "regtest", + password = "password", + ) + // Do not fund the shared descriptors: other tests expect them to have no history. + val secretKey = DescriptorSecretKey( + NetworkKind.TEST, + Mnemonic(WordCount.WORDS12), + null + ) + val wallet = Wallet( + descriptor = Descriptor.newBip84(secretKey, KeychainKind.EXTERNAL, NetworkKind.TEST), + changeDescriptor = Descriptor.newBip84(secretKey, KeychainKind.INTERNAL, NetworkKind.TEST), + network = Network.REGTEST, + persister = Persister.newInMemory() + ) + + val address = wallet.revealNextAddress(KeychainKind.EXTERNAL).address + val txid = Txid.fromString(regtestEnv.send(address.toString(), 0.001, 2.0)) + regtestEnv.mine(1) + val esploraClient = EsploraClient(ESPLORA_REGTEST_URL) + for (i in 0..99) { + if (esploraClient.getTx(txid) != null) break + delay(200.milliseconds) + } + assertNotNull(esploraClient.getTx(txid), "Funding transaction was not indexed in time") + wallet.applyUpdate(esploraClient.fullScan(wallet.startFullScan().build(), 10uL, 1uL)) + + val recipient = wallet.revealNextAddress(KeychainKind.EXTERNAL).address.scriptPubkey() + val psbt = TxBuilder() + .addRecipient(recipient, Amount.fromSat(10_000uL)) + .finish(wallet) + + val unsigned = wallet.tryFinalizePsbt(psbt) + assertFalse(unsigned.isFinalized) + assertTrue(unsigned.outcomes.isNotEmpty()) + unsigned.outcomes.values.forEach { + assertIs(it) + assertFalse(it.isFinalized()) + } + + wallet.sign(psbt, SignOptions( + trustWitnessUtxo = false, + assumeHeight = null, + allowAllSighashes = false, + tryFinalize = false, + signWithTapInternalKey = true, + allowGrinding = true, + )) + val signed = wallet.tryFinalizePsbt(psbt) + assertTrue(signed.isFinalized) + assertEquals(unsigned.outcomes.keys, signed.outcomes.keys) + signed.outcomes.values.forEach { + assertEquals(FinalizeInputOutcome.Finalized, it) + assertTrue(it.isFinalized()) + } + + val again = wallet.tryFinalizePsbt(psbt) + assertTrue(again.isFinalized) + assertEquals(signed.outcomes.keys, again.outcomes.keys) + again.outcomes.values.forEach { + assertEquals(FinalizeInputOutcome.AlreadyFinalized, it) + assertTrue(it.isFinalized()) + } + } + } +} diff --git a/bdk-ffi/src/error.rs b/bdk-ffi/src/error.rs index 2209a3f0d..d803106d0 100644 --- a/bdk-ffi/src/error.rs +++ b/bdk-ffi/src/error.rs @@ -769,6 +769,23 @@ pub enum PsbtFinalizeError { InputIdxOutofBounds { psbt_inp: u32, requested: u32 }, } +/// A malformed PSBT passed to `Wallet::try_finalize_psbt`. +#[derive(Debug, thiserror::Error, uniffi::Error)] +#[uniffi::export(Debug, Display)] +pub enum FinalizePsbtError { + #[error("PSBT input index {index} is out of bounds for {len} input maps")] + InputIndexOutOfBounds { index: u64, len: u64 }, +} + +impl From for FinalizePsbtError { + fn from(error: bdk_wallet::IndexOutOfBoundsError) -> Self { + Self::InputIndexOutOfBounds { + index: error.index as u64, + len: error.len as u64, + } + } +} + #[derive(Debug, thiserror::Error, uniffi::Error)] #[uniffi::export(Debug, Display)] pub enum PsbtParseError { diff --git a/bdk-ffi/src/tests/wallet.rs b/bdk-ffi/src/tests/wallet.rs index 970ae5a3a..4466fc4f0 100644 --- a/bdk-ffi/src/tests/wallet.rs +++ b/bdk-ffi/src/tests/wallet.rs @@ -82,6 +82,115 @@ fn funded_wallet() -> Wallet { wallet } +#[test] +fn test_finalize_input_outcome_is_finalized() { + use crate::error::MiniscriptError; + use crate::types::FinalizeInputOutcome; + + assert!(FinalizeInputOutcome::Finalized.is_finalized()); + assert!(FinalizeInputOutcome::AlreadyFinalized.is_finalized()); + assert!(!FinalizeInputOutcome::MissingDescriptor.is_finalized()); + assert!(!FinalizeInputOutcome::CouldNotSatisfy { + error: MiniscriptError::CouldNotSatisfy, + } + .is_finalized()); +} + +#[test] +fn test_try_finalize_psbt_signed_and_already_finalized() { + use crate::types::{FinalizeInputOutcome, SignOptions}; + let wallet = Arc::new(funded_wallet()); + let script = wallet + .next_unused_address(KeychainKind::External) + .address + .script_pubkey(); + let psbt = TxBuilder::new() + .add_recipient(&script, Arc::new(Amount::from_sat(10_000))) + .finish(&wallet) + .unwrap(); + wallet + .sign( + Arc::clone(&psbt), + Some(SignOptions { + trust_witness_utxo: false, + assume_height: None, + allow_all_sighashes: false, + try_finalize: false, + sign_with_tap_internal_key: true, + allow_grinding: true, + }), + ) + .unwrap(); + let outputs_before = psbt.0.lock().unwrap().outputs.clone(); + let outcome = wallet.try_finalize_psbt(Arc::clone(&psbt)).unwrap(); + assert!(outcome.is_finalized); + assert_eq!(outcome.outcomes.len(), 1); + assert!(matches!( + outcome.outcomes[&0], + FinalizeInputOutcome::Finalized + )); + assert!(!psbt.extract_tx().unwrap().input()[0].witness.is_empty()); + assert_eq!(psbt.0.lock().unwrap().outputs, outputs_before); + let outcome = wallet.try_finalize_psbt(psbt).unwrap(); + assert!(outcome.is_finalized); + assert!(matches!( + outcome.outcomes[&0], + FinalizeInputOutcome::AlreadyFinalized + )); +} + +#[test] +fn test_try_finalize_psbt_reports_each_input_failure() { + use crate::types::FinalizeInputOutcome; + let wallet = build_wallet(); + let script = wallet + .reveal_next_address(KeychainKind::External) + .address + .script_pubkey(); + let tx = BdkTransaction { + version: transaction::Version::TWO, + lock_time: absolute::LockTime::ZERO, + input: vec![bdk_wallet::bitcoin::TxIn::default(); 2], + output: vec![], + }; + let mut raw = bdk_wallet::bitcoin::psbt::Psbt::from_unsigned_tx(tx).unwrap(); + raw.inputs[0].witness_utxo = Some(BdkTxOut { + value: BdkAmount::from_sat(10_000), + script_pubkey: script.0.clone(), + }); + let psbt = Arc::new(crate::bitcoin::Psbt::from(raw.clone())); + let outcome = wallet.try_finalize_psbt(Arc::clone(&psbt)).unwrap(); + assert!(!outcome.is_finalized); + assert_eq!(outcome.outcomes.len(), 2); + assert!(matches!( + outcome.outcomes[&0], + FinalizeInputOutcome::CouldNotSatisfy { .. } + )); + assert!(matches!( + outcome.outcomes[&1], + FinalizeInputOutcome::MissingDescriptor + )); + assert_eq!(*psbt.0.lock().unwrap(), raw); +} + +#[test] +fn test_try_finalize_psbt_preserves_malformed_input_index() { + let wallet = build_wallet(); + let tx = BdkTransaction { + version: transaction::Version::TWO, + lock_time: absolute::LockTime::ZERO, + input: vec![bdk_wallet::bitcoin::TxIn::default(); 2], + output: vec![], + }; + let mut raw = bdk_wallet::bitcoin::psbt::Psbt::from_unsigned_tx(tx).unwrap(); + raw.inputs.pop(); + let psbt = Arc::new(crate::bitcoin::Psbt::from(raw)); + assert!(matches!( + wallet.try_finalize_psbt(psbt), + Err(crate::error::FinalizePsbtError::InputIndexOutOfBounds { index: 1, len: 1 }) + )); +} + #[test] fn test_tx_builder_invalid_current_height_returns_error() { let wallet = Arc::new(funded_wallet()); diff --git a/bdk-ffi/src/types.rs b/bdk-ffi/src/types.rs index 68642fe70..25a3ed81c 100644 --- a/bdk-ffi/src/types.rs +++ b/bdk-ffi/src/types.rs @@ -3,7 +3,7 @@ use crate::bitcoin::{ Transaction, TxOut, Txid, }; use crate::descriptor::Descriptor; -use crate::error::{CreateTxError, RequestBuilderError}; +use crate::error::{CreateTxError, MiniscriptError, RequestBuilderError}; use bdk_wallet::bitcoin::absolute::LockTime as BdkLockTime; use bdk_wallet::chain::spk_client::SyncItem; @@ -29,6 +29,8 @@ use bdk_wallet::miniscript::descriptor::Wildcard; use bdk_wallet::signer::{SignOptions as BdkSignOptions, TapLeavesOptions}; use bdk_wallet::AddressInfo as BdkAddressInfo; use bdk_wallet::Balance as BdkBalance; +use bdk_wallet::FinalizeInputOutcome as BdkFinalizeInputOutcome; +use bdk_wallet::FinalizePsbtOutcome as BdkFinalizePsbtOutcome; use bdk_wallet::LocalOutput as BdkLocalOutput; use bdk_wallet::Update as BdkUpdate; use bdk_wallet::WalletEvent as BdkWalletEvent; @@ -835,6 +837,62 @@ impl From for Condition { } } +/// The finalization status of a single PSBT input. +#[derive(Debug, uniffi::Enum)] +pub enum FinalizeInputOutcome { + /// The input was already finalized before this call. + AlreadyFinalized, + /// The input was finalized during this call. + Finalized, + /// The wallet could not derive a descriptor for the input. + MissingDescriptor, + /// The descriptor was found, but its spending conditions could not be satisfied. + CouldNotSatisfy { error: MiniscriptError }, +} + +#[uniffi::export] +impl FinalizeInputOutcome { + /// Whether the input is finalized after this call. + pub fn is_finalized(&self) -> bool { + matches!(self, Self::AlreadyFinalized | Self::Finalized) + } +} + +impl From for FinalizeInputOutcome { + fn from(outcome: BdkFinalizeInputOutcome) -> Self { + match outcome { + BdkFinalizeInputOutcome::AlreadyFinalized => Self::AlreadyFinalized, + BdkFinalizeInputOutcome::Finalized => Self::Finalized, + BdkFinalizeInputOutcome::MissingDescriptor => Self::MissingDescriptor, + BdkFinalizeInputOutcome::CouldNotSatisfy(error) => Self::CouldNotSatisfy { + error: error.into(), + }, + } + } +} + +/// The outcome of a PSBT finalization attempt. +#[derive(Debug, uniffi::Record)] +pub struct FinalizePsbtOutcome { + /// Whether all inputs are finalized after this call. + pub is_finalized: bool, + /// Outcomes keyed by the zero-based transaction input index. + pub outcomes: HashMap, +} + +impl From for FinalizePsbtOutcome { + fn from(outcome: BdkFinalizePsbtOutcome) -> Self { + Self { + is_finalized: outcome.is_finalized(), + outcomes: outcome + .into_outcomes() + .into_iter() + .map(|(index, outcome)| (index as u64, outcome.into())) + .collect(), + } + } +} + // This is a wrapper type around the bdk type [SignOptions](https://docs.rs/bdk_wallet/1.0.0/bdk_wallet/signer/struct.SignOptions.html) // because we did not want to expose the complexity behind the `TapLeavesOptions` type. When // transforming from a SignOption to a BdkSignOptions, we simply use the default values for diff --git a/bdk-ffi/src/wallet.rs b/bdk-ffi/src/wallet.rs index 699c12d9c..c73bf2e0e 100644 --- a/bdk-ffi/src/wallet.rs +++ b/bdk-ffi/src/wallet.rs @@ -4,14 +4,16 @@ use crate::bitcoin::{ use crate::descriptor::Descriptor; use crate::error::{ CalculateFeeError, CannotConnectError, CreateWithPersistError, DescriptorError, - LoadWithPersistError, PersistenceError, SignerError, SpkIndexError, TxidParseError, + FinalizePsbtError, LoadWithPersistError, PersistenceError, SignerError, SpkIndexError, + TxidParseError, }; use crate::signer::SignersContainer; use crate::store::{PersistenceType, Persister}; use crate::types::{ - AddressInfo, Balance, BlockId, CanonicalTx, ChangeSet, EvictedTx, FullScanRequestBuilder, - KeychainAndIndex, KeychainKind, LocalOutput, Policy, SentAndReceivedValues, SignOptions, - SyncRequestBuilder, UnconfirmedTx, Update, WalletEvent, WalletKeychain, + AddressInfo, Balance, BlockId, CanonicalTx, ChangeSet, EvictedTx, FinalizePsbtOutcome, + FullScanRequestBuilder, KeychainAndIndex, KeychainKind, LocalOutput, Policy, + SentAndReceivedValues, SignOptions, SyncRequestBuilder, UnconfirmedTx, Update, WalletEvent, + WalletKeychain, }; use bdk_wallet::bitcoin::{Network, ScriptBuf}; @@ -767,6 +769,29 @@ impl Wallet { .map_err(SignerError::from) } + /// Attempt to finalize each input of a PSBT and return per-input finalization results. + /// + /// Use this method when you need to inspect why a specific input could not be finalized. Read + /// [`FinalizePsbtOutcome::is_finalized`] on the returned value to check whether all inputs are + /// finalized after the call. + /// + /// Per-input finalization failures are reported as [`crate::types::FinalizeInputOutcome`] values. + /// This method only returns an error when the PSBT is malformed, for example if its inputs + /// are out of bounds. + /// + /// Timelock satisfaction is evaluated from the PSBT transaction fields. This method does not + /// redact or clear output metadata. + pub fn try_finalize_psbt( + &self, + psbt: Arc, + ) -> Result { + let mut psbt = psbt.0.lock().unwrap(); + self.get_wallet() + .try_finalize_psbt(&mut psbt) + .map(FinalizePsbtOutcome::from) + .map_err(FinalizePsbtError::from) + } + /// Compute the `tx`'s sent and received [`Amount`]s. /// /// This method returns a tuple `(sent, received)`. Sent is the sum of the txin amounts diff --git a/bdk-swift/Tests/BitcoinDevKitTests/WalletTests.swift b/bdk-swift/Tests/BitcoinDevKitTests/WalletTests.swift index 3a0ec76b4..296a7d2af 100644 --- a/bdk-swift/Tests/BitcoinDevKitTests/WalletTests.swift +++ b/bdk-swift/Tests/BitcoinDevKitTests/WalletTests.swift @@ -33,6 +33,29 @@ final class WalletTests: XCTestCase { XCTAssertEqual(addressInfo.address.description, "tb1qhjys9wxlfykmte7ftryptx975uqgd6kcm6a7z4") } + func testTryFinalizePsbtReportsInputOutcomes() throws { + let wallet = try Wallet( + descriptor: descriptor, + changeDescriptor: changeDescriptor, + network: .signet, + persister: Persister.newInMemory() + ) + // Two unknown inputs: the second already has a final witness. + let psbt = try Psbt(psbtBase64: "cHNidP8BAFwCAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAP////8AAAAAAAAAAQgDAQEBAA==") + let outcome = try wallet.tryFinalizePsbt(psbt: psbt) + + XCTAssertFalse(outcome.isFinalized) + XCTAssertEqual(outcome.outcomes.count, 2) + XCTAssertFalse(try XCTUnwrap(outcome.outcomes[0]).isFinalized()) + XCTAssertTrue(try XCTUnwrap(outcome.outcomes[1]).isFinalized()) + guard case .missingDescriptor? = outcome.outcomes[0] else { + return XCTFail("Expected a missing descriptor for input 0") + } + guard case .alreadyFinalized? = outcome.outcomes[1] else { + return XCTFail("Expected input 1 to remain finalized") + } + } + func testBalance() throws { let persister = try Persister.newInMemory() let wallet = try Wallet(