Skip to content
Open
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,83 @@
package org.bitcoindevkit


import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFalse
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.time.Duration.Companion.milliseconds

@RunWith(AndroidJUnit4::class)
class PsbtTest {
val conn: Persister = Persister.newInMemory()

@Test
fun signTaprootPsbt() {
runBlocking {
val regtestEnv = RegEnv.connectTo(
host = "10.0.2.2",
walletName = "faucet",
username = "regtest",
password = "password",
)

val wallet: Wallet = Wallet(
descriptor = BIP86_DESCRIPTOR,
changeDescriptor = BIP86_CHANGE_DESCRIPTOR,
network = Network.REGTEST,
persister = conn
)
val newAddress = wallet.revealNextAddress(KeychainKind.EXTERNAL).address

val txidString = regtestEnv.send(newAddress.toString(), 0.12345678, 2.0)
regtestEnv.mine(2)

val esploraClient = EsploraClient(ESPLORA_REGTEST_URL)
val txid = Txid.fromString(txidString)
// Wait for the Esplora client to see the transaction. Try 5x per second for 20 seconds.
for (i in 0..99) {
if (esploraClient.getTx(txid) != null) break
delay(200.milliseconds)
}

val fullScanRequest: FullScanRequest = wallet.startFullScan().build()
val update = esploraClient.fullScan(fullScanRequest, 10uL, 1uL)

wallet.applyUpdate(update)
wallet.persist(conn)

val balance = wallet.balance().total.toSat()

val recipient: Address = Address("bcrt1q645m0j78v9pajdfp0g0w6wacl4v8s7mvrwsjx5", Network.REGTEST)

val psbt: Psbt = TxBuilder()
.addRecipient(recipient.scriptPubkey(), Amount.fromSat(4420uL))
.feeRate(FeeRate.fromSatPerVb(22uL))
.finish(wallet)

val psbtSignedResult = psbt.sign(listOf(BIP86_DESCRIPTOR))

assertTrue(
psbtSignedResult.errors.isEmpty(),
"Signing failed with errors: ${psbtSignedResult.errors}"
)
assertTrue(psbtSignedResult.signedInputs.isNotEmpty(), "At least one input should be signed")

val inputs = psbt.input()
val tapKeySig = inputs[0].tapKeySig

assertTrue(tapKeySig != null, "tapKeySig should not be null after signing the PSBT input")

val finalized = psbt.finalize()
assertTrue(
finalized.couldFinalize,
"PSBT should finalize successfully, errors: ${finalized.errors}"
)
}
}
}
79 changes: 77 additions & 2 deletions bdk-ffi/src/bitcoin.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::error::{
AddressParseError, Bip32Error, ExtractTxError, FeeRateError, FromScriptError, HashParseError,
PsbtError, PsbtParseError, TransactionError,
PsbtError, PsbtParseError, PsbtSignError, TransactionError,
};
use crate::error::{ParseAmountError, PsbtFinalizeError};
use crate::keys::DerivationPath;
Expand All @@ -18,6 +18,7 @@ use bdk_wallet::bitcoin::hashes::sha256::Hash as BitcoinSha256Hash;
use bdk_wallet::bitcoin::hashes::sha256d::Hash as BitcoinDoubleSha256Hash;
use bdk_wallet::bitcoin::psbt::Input as BdkInput;
use bdk_wallet::bitcoin::psbt::Output as BdkOutput;
use bdk_wallet::bitcoin::psbt::SigningKeys as BdkSigningKeys;
use bdk_wallet::bitcoin::secp256k1::Secp256k1;
use bdk_wallet::bitcoin::taproot::LeafNode as BdkLeafNode;
use bdk_wallet::bitcoin::taproot::NodeInfo as BdkNodeInfo;
Expand All @@ -37,7 +38,8 @@ use bdk_wallet::bitcoin::Wtxid as BitcoinWtxid;
use bdk_wallet::miniscript::psbt::PsbtExt;
use bdk_wallet::serde_json;

use std::collections::HashMap;
use crate::descriptor::Descriptor;
use std::collections::{BTreeSet, HashMap};
use std::convert::TryFrom;
use std::fmt::Display;
use std::fs::File;
Expand Down Expand Up @@ -1579,6 +1581,60 @@ impl Psbt {
let psbt = self.0.lock().unwrap();
psbt.outputs.iter().map(|o| o.into()).collect()
}

/// Signs the inputs of this PSBT using the secret keys held by the given descriptors.
///
/// Pass every descriptor that may own inputs of this transaction (for example a wallet's
/// external and internal descriptors). Each descriptor is tried against every input, and keys
/// that do not match an input are ignored. This function does not support scripts that contain
/// `OP_CODESEPARATOR`.
///
/// # Returns
///
/// A `PsbtSignResult` listing the inputs that received a signature in this call and the errors
/// encountered while attempting to sign. An empty `signed_inputs` means nothing was signed, for
/// example because the descriptors do not match the inputs. Use `finalize` to check whether the
/// PSBT is complete.
///
/// # Errors
///
/// Returns `SignError::NoSecretKeys` if none of the descriptors contain secret keys.
pub fn sign(&self, descriptors: Vec<Arc<Descriptor>>) -> Result<PsbtSignResult, PsbtSignError> {
if descriptors.iter().all(|d| d.key_map.is_empty()) {
return Err(PsbtSignError::NoSecretKeys);
}

let mut psbt = self.0.lock().unwrap();
let secp = Secp256k1::new();
let mut signed_inputs = BTreeSet::new();
let mut errors = HashMap::new();

for descriptor in descriptors.iter().filter(|d| !d.key_map.is_empty()) {
let keys =
bdk_wallet::miniscript::descriptor::KeyMapWrapper::from(descriptor.key_map.clone());
let (used, errs) = match psbt.sign(&keys, &secp) {
Ok(used) => (used, Default::default()),
Err((used, errs)) => (used, errs),
};
signed_inputs.extend(
used.into_iter()
.filter(|(_, keys)| match keys {
BdkSigningKeys::Ecdsa(k) => !k.is_empty(),
BdkSigningKeys::Schnorr(k) => !k.is_empty(),
})
.map(|(index, _)| index as u64),
);
errors.extend(
errs.into_iter()
.map(|(index, error)| (index as u64, PsbtSignError::from(error))),
);
}

Ok(PsbtSignResult {
signed_inputs: signed_inputs.into_iter().collect(),
errors,
})
}
}

impl From<BdkPsbt> for Psbt {
Expand Down Expand Up @@ -1669,6 +1725,25 @@ impl From<TxOut> for BdkTxOut {
}
}

#[derive(uniffi::Record)]
#[uniffi::export(Display)]
pub struct PsbtSignResult {
/// Inputs that received at least one signature in this call.
pub signed_inputs: Vec<u64>,
/// Errors encountered while attempting to sign, keyed by input index.
pub errors: HashMap<u64, PsbtSignError>,
}

impl Display for PsbtSignResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Signed inputs: {:?}, Errors: {:?}",
self.signed_inputs, self.errors
)
}
}

/// A child number in a derivation path
#[derive(Copy, Clone, uniffi::Enum)]
pub enum ChildNumber {
Expand Down
74 changes: 74 additions & 0 deletions bdk-ffi/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use bdk_wallet::bitcoin::hex::DisplayHex;
use bdk_wallet::bitcoin::psbt::Error as BdkPsbtError;
use bdk_wallet::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_wallet::bitcoin::psbt::PsbtParseError as BdkPsbtParseError;
use bdk_wallet::bitcoin::psbt::SignError as BdkSignError;
use bdk_wallet::bitcoin::script::PushBytesError;
use bdk_wallet::chain::local_chain::CannotConnectError as BdkCannotConnectError;
use bdk_wallet::chain::rusqlite::Error as BdkSqliteError;
Expand Down Expand Up @@ -868,6 +869,79 @@ pub enum SignerError {
Psbt { error_message: String },
}

#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi::export(Debug, Display)]
pub enum PsbtSignError {
#[error("index out of bounds {error_message}")]
IndexOutOfBounds { error_message: String },
#[error("invalid sighash type")]
InvalidSighashType,
#[error("missing input utxo")]
MissingInputUtxo,
#[error("missing redeem script")]
MissingRedeemScript,
#[error("missing spending utxo")]
MissingSpendUtxo,
#[error("missing witness script")]
MissingWitnessScript,
#[error("signing algorithm and key type does not match")]
MismatchedAlgoKey,
#[error("attempted to ECDSA sign a non-ECDSA input")]
NotEcdsa,
#[error("the scriptPubkey is not a P2WPKH script")]
NotWpkh,
#[error("sighash computation error (segwit v0 input): {error_message}")]
SegwitV0Sighash { error_message: String },
#[error("sighash computation error (p2wpkh input): {error_message}")]
P2wpkhSighash { error_message: String },
#[error("sighash computation error (taproot input): {error_message}")]
TaprootError { error_message: String },
#[error("unable to determine the output type")]
UnknownOutputType,
#[error("unable to find key")]
KeyNotFound,
#[error("attempt to sign an input with the wrong signing algorithm")]
WrongSigningAlgorithm,
#[error("signing request currently unsupported")]
Unsupported,
#[error("none of the provided descriptors contain secret keys")]
NoSecretKeys,
#[error("unknown signing error")]
Unknown,
}

impl From<BdkSignError> for PsbtSignError {
fn from(error: BdkSignError) -> Self {
match error {
BdkSignError::IndexOutOfBounds(e) => Self::IndexOutOfBounds {
error_message: e.to_string(),
},
BdkSignError::InvalidSighashType => Self::InvalidSighashType,
BdkSignError::MissingInputUtxo => Self::MissingInputUtxo,
BdkSignError::MissingRedeemScript => Self::MissingRedeemScript,
BdkSignError::MissingSpendUtxo => Self::MissingSpendUtxo,
BdkSignError::MissingWitnessScript => Self::MissingWitnessScript,
BdkSignError::MismatchedAlgoKey => Self::MismatchedAlgoKey,
BdkSignError::NotEcdsa => Self::NotEcdsa,
BdkSignError::NotWpkh => Self::NotWpkh,
BdkSignError::SegwitV0Sighash(e) => Self::SegwitV0Sighash {
error_message: e.to_string(),
},
BdkSignError::P2wpkhSighash(e) => Self::P2wpkhSighash {
error_message: e.to_string(),
},
BdkSignError::TaprootError(e) => Self::TaprootError {
error_message: e.to_string(),
},
BdkSignError::UnknownOutputType => Self::UnknownOutputType,
BdkSignError::KeyNotFound => Self::KeyNotFound,
BdkSignError::WrongSigningAlgorithm => Self::WrongSigningAlgorithm,
BdkSignError::Unsupported => Self::Unsupported,
_ => Self::Unknown, // Catch all for any other errors not explicitly handled. Satisfies non-exhaustive.
}
}
}

#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi::export(Debug, Display)]
pub enum TransactionError {
Expand Down
Loading
Loading