Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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 {
Comment thread
thunderbiscuit marked this conversation as resolved.
Resolved
@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<FinalizeInputOutcome.CouldNotSatisfy>(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())
}
}
}
}
17 changes: 17 additions & 0 deletions bdk-ffi/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bdk_wallet::IndexOutOfBoundsError> 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 {
Expand Down
109 changes: 109 additions & 0 deletions bdk-ffi/src/tests/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
60 changes: 59 additions & 1 deletion bdk-ffi/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -835,6 +837,62 @@ impl From<BdkCondition> for Condition {
}
}

/// The finalization status of a single PSBT input.
#[derive(Debug, uniffi::Enum)]
pub enum FinalizeInputOutcome {
Comment thread
thunderbiscuit marked this conversation as resolved.
Resolved
/// 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<BdkFinalizeInputOutcome> 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.
Comment thread
thunderbiscuit marked this conversation as resolved.
Resolved
pub outcomes: HashMap<u64, FinalizeInputOutcome>,
}

impl From<BdkFinalizePsbtOutcome> 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
Expand Down
33 changes: 29 additions & 4 deletions bdk-ffi/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Psbt>,
) -> Result<FinalizePsbtOutcome, FinalizePsbtError> {
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
Expand Down
Loading
Loading