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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details.
- Gated `full_scan`'s `--scan-stop-gap` to the Electrum and Esplora backends that use it; RPC and CBF wallets now reject the flag instead of silently ignoring it, while a `STOP_GAP` environment variable keeps working for supported backends and no longer breaks unsupported ones
- Changed `payjoin history` to return JSON instead of a rendered table
- Fixed `wallet config --force` silently changing an existing wallet's network, which left the wallet unable to load; it is now rejected
- Fixed transaction creation to reject addresses and silent payment codes from a different network instead of building an unspendable PSBT
- Changed `receive_payjoin`, `send_payjoin`, `resume_payjoin`, `payjoin_history` and `resolve_dns_recipient` to print their JSON directly instead of as a string inside a `message` field; `resolve_dns_recipient` now leaves out `description`, `min_amount` and `max_amount` when they are not set

## [4.0.0]
Expand Down
15 changes: 14 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub enum BDKCliError {
)]
NonStandardTxWeight { weight: Weight },

#[error("ParseError: {0}")]
#[error("ParseError: {}", display_parse_error(.0))]
ParseError(#[from] bdk_wallet::bitcoin::address::ParseError),

#[error("ParseOutPointError: {0}")]
Expand Down Expand Up @@ -256,3 +256,16 @@ where
BDKCliError::Generic(e.to_string())
}
}

/// Format an address parse error together with its underlying cause.
///
/// `rust-bitcoin`'s `ParseError` only prints a generic summary such as
/// "validation error"; the useful detail (e.g. which network an address belongs
/// to) lives in its source.
fn display_parse_error(error: &bdk_wallet::bitcoin::address::ParseError) -> String {
use std::error::Error as _;
match error.source() {
Some(source) => source.to_string(),
None => error.to_string(),
}
}
14 changes: 11 additions & 3 deletions src/handlers/dns/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@ use crate::handlers::{AppContext, AsyncAppCommand, Init, OfflineOperations};
use crate::utils::{
check_standard_weight, max_signed_weight, parse_dns_recipient, parse_fee_rate,
parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient,
recipient_script,
};
use bdk_wallet::KeychainKind;
use bdk_wallet::bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf};
use bdk_wallet::bitcoin::address::NetworkUnchecked;
use bdk_wallet::bitcoin::{
Address, Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf,
};
use bitcoin_payment_instructions::PaymentMethod;
use clap::Parser;
use serde_json::{Value, json};
Expand Down Expand Up @@ -64,7 +68,7 @@ impl AsyncAppCommand<AppContext<Init>> for ResolveDnsRecipientCommand {
#[derive(Parser, Debug, Clone, PartialEq)]
pub struct CreateDnsTxCommand {
#[arg(env = "ADDRESS_SAT", long = "to", value_parser = parse_recipient)]
pub recipients: Vec<(ScriptBuf, u64)>,
pub recipients: Vec<(Address<NetworkUnchecked>, u64)>,
#[arg(long = "to_dns", value_parser = parse_dns_recipient)]
pub dns_recipients: Vec<(String, u64)>,
#[arg(long = "dns_resolver", default_value = "8.8.8.8")]
Expand Down Expand Up @@ -106,7 +110,11 @@ pub struct CreateDnsTxCommand {
impl AsyncAppCommand<AppContext<OfflineOperations<'_>>> for CreateDnsTxCommand {
async fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let network = ctx.network;
let mut recipients: Vec<(ScriptBuf, u64)> = self.recipients.clone();
let mut recipients: Vec<(ScriptBuf, u64)> = self
.recipients
.iter()
.map(|(address, amount)| Ok((recipient_script(address, network)?, *amount)))
.collect::<Result<_, Error>>()?;

for (hrn, amount_sat) in &self.dns_recipients {
log::info!("Resolving DNS instructions for recipient {hrn}");
Expand Down
69 changes: 47 additions & 22 deletions src/handlers/offline.rs
Comment thread
vadim-anfv marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,34 @@ use crate::error::BDKCliError as Error;
use crate::handlers::{AppCommand, AppContext, OfflineOperations};
use crate::utils::output::FormatOutput;
use crate::utils::{
check_standard_weight, max_signed_weight, parse_address, parse_fee_rate,
parse_op_return_base64, parse_op_return_string, parse_outpoint, parse_recipient,
check_standard_weight, max_signed_weight, parse_fee_rate, parse_op_return_base64,
parse_op_return_string, parse_outpoint, parse_recipient, recipient_script,
};
use bdk_wallet::bitcoin::address::NetworkUnchecked;
use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD};
use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, ScriptBuf, Sequence, Txid};
use bdk_wallet::bitcoin::{consensus::encode::serialize_hex, script::PushBytesBuf};
use bdk_wallet::bitcoin::consensus::encode::serialize_hex;
use bdk_wallet::bitcoin::script::PushBytesBuf;
use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, Sequence, Txid};
use bdk_wallet::{KeychainKind, SignOptions};
use clap::Parser;
use serde_json::{Value, json};
use std::collections::BTreeMap;
#[cfg(feature = "silent-payments")]
use {
crate::utils::common::parse_sp_code_value_pairs,
crate::utils::common::{parse_sp_code_value_pairs, sp_code_valid_for_network},
bdk_sp::{
bitcoin::{PrivateKey, PublicKey},
encoding::SilentPaymentCode,
send::psbt::derive_sp,
},
bdk_wallet::bitcoin::ScriptBuf,
bdk_wallet::bitcoin::key::Secp256k1,
bdk_wallet::keys::{DescriptorPublicKey, DescriptorSecretKey, SinglePubKey},
std::collections::HashMap,
};
#[cfg(feature = "message_signer")]
use {
crate::utils::parse_address,
crate::utils::parse_signature_format,
bdk_message_signer::{MessageProof, MessageSigner},
};
Expand Down Expand Up @@ -188,7 +192,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for BalanceCommand {
pub struct CreateTxCommand {
/// Adds a recipient to the transaction.
#[arg(env = "ADDRESS_SAT", long = "to", required = true, value_parser = parse_recipient)]
pub recipients: Vec<(ScriptBuf, u64)>,
pub recipients: Vec<(Address<NetworkUnchecked>, u64)>,

/// Sends all the funds (or all the selected utxos). Requires only one recipient with value 0.
#[arg(long = "send_all", short = 'a')]
Expand Down Expand Up @@ -245,13 +249,14 @@ pub struct CreateTxCommand {

impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateTxCommand {
fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let network = ctx.state.wallet.network();
let mut tx_builder = ctx.state.wallet.build_tx();

if self.send_all {
if self.recipients.len() == 1 {
tx_builder
.drain_wallet()
.drain_to(self.recipients[0].0.clone());
.drain_to(recipient_script(&self.recipients[0].0, network)?);
} else {
return Err(Error::Generic(
"Wallet can only be drained to a single output".to_string(),
Expand All @@ -260,10 +265,14 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateTxCommand {
} else {
let recipients = self
.recipients
.clone()
.into_iter()
.map(|(script, amount)| (script, Amount::from_sat(amount)))
.collect();
.iter()
.map(|(address, amount)| {
Ok((
recipient_script(address, network)?,
Amount::from_sat(*amount),
))
})
.collect::<Result<_, Error>>()?;
tx_builder.set_recipients(recipients);
}

Expand Down Expand Up @@ -320,7 +329,7 @@ pub struct CreateSpTxCommand {
// Clap Doesn't support complex vector parsing https://github.com/clap-rs/clap/issues/1704.
// Address and amount parsing is done at run time in handler function.
#[arg(env = "ADDRESS_SAT", long = "to", required = false, value_parser = parse_recipient)]
pub recipients: Option<Vec<(ScriptBuf, u64)>>,
pub recipients: Option<Vec<(Address<NetworkUnchecked>, u64)>>,
/// Parse silent payment recipients
#[arg(long = "to-sp", required = true, value_parser = parse_sp_code_value_pairs)]
pub silent_payment_recipients: Vec<(SilentPaymentCode, u64)>,
Expand Down Expand Up @@ -368,13 +377,21 @@ pub struct CreateSpTxCommand {
#[cfg(feature = "silent-payments")]
impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let network = ctx.state.wallet.network();
let mut tx_builder = ctx.state.wallet.build_tx();

let sp_recipients: Vec<SilentPaymentCode> = self
.silent_payment_recipients
.iter()
.map(|(sp_code, _)| sp_code.clone())
.collect();
.map(|(sp_code, _)| {
if !sp_code_valid_for_network(sp_code, network) {
return Err(Error::Generic(format!(
"Silent payment code {sp_code} is not valid for {network}"
)));
}
Ok(sp_code.clone())
})
.collect::<Result<_, Error>>()?;

if self.send_all {
if sp_recipients.len() == 1 && self.recipients.is_none() {
Expand All @@ -385,7 +402,9 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
&& sp_recipients.is_empty()
{
if recipients.len() == 1 {
tx_builder.drain_wallet().drain_to(recipients[0].0.clone());
tx_builder
.drain_wallet()
.drain_to(recipient_script(&recipients[0].0, network)?);
} else {
return Err(Error::Generic(
"Wallet can only be drain to a single output".to_string(),
Expand All @@ -409,7 +428,13 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
if let Some(recipients) = &self.recipients {
let recipients = recipients
.iter()
.map(|(script, amount)| (script.clone(), Amount::from_sat(*amount)));
.map(|(address, amount)| {
Ok((
recipient_script(address, network)?,
Amount::from_sat(*amount),
))
})
.collect::<Result<Vec<_>, Error>>()?;

outputs.extend(recipients);
}
Expand Down Expand Up @@ -538,8 +563,8 @@ pub struct BumpFeeCommand {
pub txid: Txid,

/// Allows the wallet to reduce the amount to the specified address in order to increase fees.
#[arg(env = "SHRINK_ADDRESS", long = "shrink", value_parser = parse_address)]
pub shrink_address: Option<Address>,
#[arg(env = "SHRINK_ADDRESS", long = "shrink")]
pub shrink_address: Option<Address<NetworkUnchecked>>,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also add a test case for bump_fee too. I think there is a test gap

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will include too. thanks!


/// Make a PSBT that can be signed by offline signers and hardware wallets. Forces the addition of `non_witness_utxo` and more details to let the signer identify the change output.
#[arg(long = "offline_signer")]
Expand All @@ -566,14 +591,14 @@ pub struct BumpFeeCommand {

impl AppCommand<AppContext<OfflineOperations<'_>>> for BumpFeeCommand {
fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let network = ctx.state.wallet.network();
let wallet = &mut ctx.state.wallet;

let mut tx_builder = wallet.build_fee_bump(self.txid)?;
tx_builder.fee_rate(self.fee_rate);

if let Some(address) = &self.shrink_address {
let script_pubkey = address.script_pubkey();
tx_builder.drain_to(script_pubkey);
tx_builder.drain_to(recipient_script(address, network)?);
}

if self.offline_signer {
Expand Down Expand Up @@ -760,7 +785,7 @@ pub struct SignMessageCommand {
impl AppCommand<AppContext<OfflineOperations<'_>>> for SignMessageCommand {
fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let address: Address = parse_address(&self.address)?;
let address: Address = parse_address(&self.address, wallet.network())?;
let signature_format = parse_signature_format(&self.signature_type)?;

if !wallet.is_mine(address.script_pubkey()) {
Expand Down Expand Up @@ -802,7 +827,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for VerifyMessageCommand {
fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &ctx.state.wallet;

let address: Address = parse_address(&self.address)?;
let address: Address = parse_address(&self.address, wallet.network())?;

let parsed_proof = MessageProof::from_base64(&self.proof)
.map_err(|e| Error::Generic(format!("Invalid proof format: {e}")))?;
Expand Down
Loading
Loading