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
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
- 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ clap_complete = "4.6"
dirs = { version = "6.0.0" }
env_logger = "0.11.10"
log = "0.4"
serde_json = "1.0"
serde_json = { version = "1.0", features = ["preserve_order"] }
thiserror = "2.0.18"
tokio = { version = "1", features = ["full"] }
toml = "1.1.0"
Expand Down
56 changes: 20 additions & 36 deletions NEW_FEATURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Before writing code, it helps to understand the three major components of a bdk-

__Clap Parser:__ Defines the CLI arguments the user types.

__The AppCommand Trait__: The trait every command must implement to define its execution logic and return a formatted output. It has the `execute` method and a type `FormatOutput` for formatting the command's response. If the command involves I/O, there is an AsyncAppCommand to use.
__The AppCommand Trait__: The trait every command must implement to define its execution logic. Its `execute` method returns the command's output as a `serde_json::Value`. If the command involves I/O, there is an AsyncAppCommand to use.

__The Typestate (AppContext<T>):__ Defines the environment your command runs in. Every command is a struct that implements the AppCommand's trait execute method against a typestate context. There are three context (src/handlers/mod):

Expand Down Expand Up @@ -52,22 +52,11 @@ pub struct WalletDetailsCommand {

```

##### Step 2: Define the Output Type
##### Step 2: Decide where the output is built

Every command must return a structured result that can be serialized into standard JSON. Define a struct that implements serde::Serialize ( placed in `src/utils/types.rs`).

```Rust
use serde::Serialize;
use bdk_wallet::bitcoin::Network;

#[derive(Debug, Serialize)]
pub struct WalletDetailsResult {
pub network: Network,
pub fingerprint: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_descriptor: Option<String>,
}
```
Every command prints JSON, and that JSON is built in exactly one place: the command's own `execute` method. To find what a command prints, read its `execute`.
- Helpers in `src/utils/` return domain values (bdk/bitcoin types, `String`s, small structs such as `KeychainDescriptors`) so they can be reused. They never build JSON.
- `execute` turns those values into the output with `serde_json::json!`. Keys are printed in the order they are written.

##### Step 3: Implement the AppCommand Trait

Expand All @@ -78,31 +67,26 @@ Because our command needs to read wallet data, we will use the OfflineOperations
```Rust
use crate::handlers::{AppCommand, AppContext, OfflineOperations};
use crate::error::BDKCliError as Error;
use serde_json::{Value, json};

impl AppCommand<AppContext<OfflineOperations<'_>>> for WalletDetailsCommand {
// 1. Declare the output type we defined in Step 2
type Output = WalletDetailsResult;

// 2. Implement the execute function
fn execute(&self, context: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
// Implement the execute function
fn execute(&self, context: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
// Access the loaded wallet via the context state
let wallet = &context.state.wallet;

let network = wallet.network();
let fingerprint = wallet.fingerprint().to_string();

let external_descriptor = if self.show_descriptors {
Some(wallet.public_descriptor(bdk_wallet::KeychainKind::External).to_string())
} else {
None
};

// Return the structured Result
Ok(WalletDetailsResult {
network,
fingerprint,
external_descriptor,
})
let mut output = json!({
"network": wallet.network(),
"fingerprint": wallet.fingerprint().to_string(),
});

// Only include the descriptor when it was asked for
if self.show_descriptors {
output["external_descriptor"] =
json!(wallet.public_descriptor(bdk_wallet::KeychainKind::External).to_string());
}

Ok(output)
}
}
```
Expand Down
44 changes: 17 additions & 27 deletions src/handlers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@ use crate::client::ClientType;
use crate::commands::{WalletOpts, WalletsSubCommand};
use crate::config::{WalletConfig, WalletConfigInner, remove_wallet_from_config_file};
use crate::error::BDKCliError as Error;
use crate::handlers::Init;
use crate::handlers::{AppCommand, AppContext};
use crate::handlers::{AppCommand, AppContext, Init};
#[cfg(any(feature = "sqlite", feature = "redb"))]
use crate::persister::DatabaseType;
use crate::persister::wallet_data_exists;
use crate::utils::descriptors::validate_descriptor_pair;
use crate::utils::output::FormatOutput;
use crate::utils::types::{StatusResult, WalletsListResult};
use crate::utils::{descriptors::validate_descriptor_pair, output::FormatOutput};
use bdk_wallet::bitcoin::Network;
use clap::Args;
use serde_json::{Value, json};

#[derive(Args, Debug, Clone, PartialEq)]
pub struct SaveConfigCommand {
Expand All @@ -32,9 +30,7 @@ pub struct SaveConfigCommand {
}

impl AppCommand<AppContext<Init>> for SaveConfigCommand {
type Output = StatusResult;

fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
if ctx.network == Network::Bitcoin {
eprintln!("WARNING: Configuring for Bitcoin MAINNET. Experimental software!");
}
Expand Down Expand Up @@ -73,17 +69,16 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {

if config.wallets.contains_key(wallet_name.as_str()) && !self.force {
return Err(Error::Generic(format!(
"Wallet '{}' already exists. Use --force to overwrite.",
wallet_name
"Wallet '{wallet_name}' already exists. Use --force to overwrite."
)));
};

if let Some(existing) = config.wallets.get(wallet_name.as_str())
&& existing.network != ctx.network.to_string()
{
return Err(Error::Generic(format!(
"Wallet '{}' is configured for network '{}', and --force cannot change it to '{}'.",
wallet_name, existing.network, ctx.network
"Wallet '{wallet_name}' is configured for network '{}', and --force cannot change it to '{}'.",
existing.network, ctx.network
)));
}

Expand Down Expand Up @@ -160,29 +155,26 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
.save(&ctx.datadir)
.map_err(|error| Error::Generic(error.to_string()))?;

Ok(StatusResult {
message: format!(
"Wallet '{}' initialized successfully in {:?}",
wallet_name,
Ok(json!({
"message": format!(
"Wallet '{wallet_name}' initialized successfully in {:?}",
ctx.datadir.join("config.toml")
),
})
}))
Comment thread
vadim-anfv marked this conversation as resolved.
Resolved
}
}

#[derive(Args, Debug, Clone, PartialEq)]
pub struct ListWalletsCommand;

impl AppCommand<AppContext<Init>> for ListWalletsCommand {
type Output = WalletsListResult;

fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let config = match WalletConfig::load(&ctx.datadir)? {
Some(cfg) => cfg,
None => return Err(Error::Generic("No wallets configured yet.".into())),
};

Ok(WalletsListResult(config.wallets))
Ok(serde_json::to_value(config.wallets)?)
}
}

Expand All @@ -194,9 +186,7 @@ pub struct DeleteWalletConfigCommand {
}

impl AppCommand<AppContext<Init>> for DeleteWalletConfigCommand {
type Output = StatusResult;

fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let config = match WalletConfig::load(&ctx.datadir)? {
Some(config) => config,
None => return Err(Error::Generic("No wallets configured yet.".into())),
Expand Down Expand Up @@ -236,12 +226,12 @@ impl AppCommand<AppContext<Init>> for DeleteWalletConfigCommand {

remove_wallet_from_config_file(&ctx.datadir, &self.wallet_name)?;

Ok(StatusResult {
message: format!(
Ok(json!({
"message": format!(
"Wallet configuration '{}' deleted successfully",
self.wallet_name
),
})
}))
Comment thread
vadim-anfv marked this conversation as resolved.
Resolved
}
}

Expand Down
72 changes: 39 additions & 33 deletions src/handlers/descriptor.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::handlers::Init;
use crate::utils::types::DescriptorResult;
use crate::{
error::BDKCliError as Error,
handlers::{AppCommand, AppContext},
Expand All @@ -12,15 +11,13 @@ use crate::{
},
};
use clap::Parser;
use serde_json::{Value, json};
#[cfg(feature = "compiler")]
use {
crate::utils::descriptors::{CompileScriptType, compile_policy},
bdk_wallet::miniscript::descriptor::DescriptorPublicKey,
};

#[cfg(feature = "silent-payments")]
use crate::utils::types::StatusResult;

#[derive(Parser, Debug, Clone, PartialEq)]
pub struct DescriptorCommand {
/// Descriptor type (script type)
Expand All @@ -36,19 +33,38 @@ pub struct DescriptorCommand {
key: Option<String>,
}
impl AppCommand<AppContext<Init>> for DescriptorCommand {
type Output = DescriptorResult;

fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
match &self.key {
Some(key) => {
if is_mnemonic(key) {
generate_descriptor_from_mnemonic(key, ctx.network.into(), &self.desc_type)
} else {
generate_descriptors(&self.desc_type, key, ctx.network.into())
}
fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let network = ctx.network.into();
let (descriptors, mnemonic) = match &self.key {
Some(key) if is_mnemonic(key) => (
generate_descriptor_from_mnemonic(key, network, &self.desc_type)?,
Some(key.clone()),
),
Some(key) => (generate_descriptors(&self.desc_type, key, network)?, None),
None => {
let (mnemonic, descriptors) =
generate_descriptor_with_mnemonic(network, &self.desc_type)?;
(descriptors, Some(mnemonic.to_string()))
}
None => generate_descriptor_with_mnemonic(ctx.network.into(), &self.desc_type),
};

let mut output = json!({
"public_descriptors": {
"external": descriptors.external.to_string(),
"internal": descriptors.internal.to_string(),
},
});
if !descriptors.keymap.is_empty() {
output["private_descriptors"] = json!({
"external": descriptors.external.to_string_with_secret(&descriptors.keymap),
"internal": descriptors.internal.to_string_with_secret(&descriptors.keymap),
});
}
if let Some(mnemonic) = mnemonic {
output["mnemonic"] = json!(mnemonic);
}
output["fingerprint"] = json!(descriptors.fingerprint.to_string());
Ok(output)
}
}

Expand Down Expand Up @@ -76,24 +92,18 @@ pub struct CompileCommand {

#[cfg(feature = "compiler")]
impl AppCommand<AppContext<Init>> for CompileCommand {
type Output = DescriptorResult;

fn execute(&self, _ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
fn execute(&self, _ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let (descriptor, r) = if self.placeholders {
compile_policy::<String>(&self.policy, self.script_type)?
} else {
compile_policy::<DescriptorPublicKey>(&self.policy, self.script_type)?
};

Ok(DescriptorResult {
descriptor: Some(descriptor),
mnemonic: None,
multipath_descriptor: None,
public_descriptors: None,
private_descriptors: None,
fingerprint: None,
r,
})
let mut output = json!({ "descriptor": descriptor });
if let Some(r) = r {
output["r"] = json!(r);
}
Ok(output)
}
}

Expand All @@ -110,14 +120,10 @@ pub struct SilentPaymentCodeCommand {

#[cfg(feature = "silent-payments")]
impl AppCommand<AppContext<Init>> for SilentPaymentCodeCommand {
type Output = StatusResult;

fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let sp_code =
bdk_sp::encoding::SilentPaymentCode::new_v0(self.scan, self.spend, ctx.network);

Ok(StatusResult {
message: sp_code.to_string(),
})
Ok(json!({ "message": sp_code.to_string() }))
}
}
26 changes: 0 additions & 26 deletions src/handlers/dns/dns_payment_instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,6 @@ pub struct ResolvedPaymentInfo {
pub notes: String,
}

impl ResolvedPaymentInfo {
pub fn display(&self) -> Result<String, Error> {
let methods: Vec<String> = self
.payment_methods
.iter()
.map(|pm| match pm {
PaymentMethod::LightningBolt11(bolt11) => {
format!("Bolt 11 invoice ({})", bolt11)
}
PaymentMethod::LightningBolt12(offer) => format!("Bolt 12 invoice ({})", offer),
PaymentMethod::OnChain(address) => format!("On chain ({})", address),
PaymentMethod::Cashu(csh) => format!("Cashu payment ({})", csh),
})
.collect();

Ok(serde_json::to_string_pretty(&serde_json::json!({
"hrn": self.hrn,
"payment_methods": methods,
"description": self.description,
"min_amount": self.min_amount,
"max_amount": self.max_amount,
"notes": self.notes
}))?)
}
}

pub(crate) async fn parse_dns_instructions(
hrn: &str,
network: Network,
Expand Down
Loading
Loading