From cac3733ab02b4cc997cb6157a97c3bc055b7e512 Mon Sep 17 00:00:00 2001 From: Vihiga Tyonum Date: Mon, 30 Nov 2026 19:11:29 +0100 Subject: [PATCH 1/3] refactor: drop the types module and build JSON in each command JSON is the only output format, so the result structs in src/utils/types.rs were only intermediate shapes. execute() now returns serde_json::Value and each command builds its output with json! in its own handler, so a command's output is defined in one place. Helpers in src/utils return domain values instead of output structs: the descriptor helpers return KeychainDescriptors (descriptors, keymap, fingerprint), and the handler decides what to print. --- CHANGELOG.md | 1 + NEW_FEATURE.md | 57 ++++------ src/handlers/config.rs | 48 ++++----- src/handlers/descriptor.rs | 72 +++++++------ src/handlers/dns/mod.rs | 19 +--- src/handlers/hwi.rs | 8 +- src/handlers/key.rs | 57 +++++----- src/handlers/mod.rs | 11 +- src/handlers/offline.rs | 207 +++++++++++++++---------------------- src/handlers/online.rs | 128 ++++++++--------------- src/utils/descriptors.rs | 84 ++++++--------- src/utils/mod.rs | 1 - src/utils/output.rs | 16 --- src/utils/types.rs | 207 ------------------------------------- 14 files changed, 285 insertions(+), 631 deletions(-) delete mode 100644 src/utils/types.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 85926de9..e7a266cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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] diff --git a/NEW_FEATURE.md b/NEW_FEATURE.md index 543fc164..b2c78901 100644 --- a/NEW_FEATURE.md +++ b/NEW_FEATURE.md @@ -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):__ 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): @@ -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, -} -``` +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!`. ##### Step 3: Implement the AppCommand Trait @@ -78,31 +67,27 @@ 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>> 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>) -> Result { + + // Implement the execute function + fn execute(&self, context: &mut AppContext>) -> Result { // 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) } } ``` diff --git a/src/handlers/config.rs b/src/handlers/config.rs index bed4f13e..4ed38d3e 100644 --- a/src/handlers/config.rs +++ b/src/handlers/config.rs @@ -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 { @@ -32,9 +30,7 @@ pub struct SaveConfigCommand { } impl AppCommand> for SaveConfigCommand { - type Output = StatusResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { if ctx.network == Network::Bitcoin { eprintln!("WARNING: Configuring for Bitcoin MAINNET. Experimental software!"); } @@ -160,13 +156,13 @@ impl AppCommand> for SaveConfigCommand { .save(&ctx.datadir) .map_err(|error| Error::Generic(error.to_string()))?; - Ok(StatusResult { - message: format!( - "Wallet '{}' initialized successfully in {:?}", - wallet_name, - ctx.datadir.join("config.toml") - ), - }) + Ok(json!({ + "message": format!( + "Wallet '{}' initialized successfully in {:?}", + wallet_name, + ctx.datadir.join("config.toml") + ), + })) } } @@ -174,15 +170,13 @@ impl AppCommand> for SaveConfigCommand { pub struct ListWalletsCommand; impl AppCommand> for ListWalletsCommand { - type Output = WalletsListResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { 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)?) } } @@ -194,9 +188,7 @@ pub struct DeleteWalletConfigCommand { } impl AppCommand> for DeleteWalletConfigCommand { - type Output = StatusResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { let config = match WalletConfig::load(&ctx.datadir)? { Some(config) => config, None => return Err(Error::Generic("No wallets configured yet.".into())), @@ -236,12 +228,12 @@ impl AppCommand> for DeleteWalletConfigCommand { remove_wallet_from_config_file(&ctx.datadir, &self.wallet_name)?; - Ok(StatusResult { - message: format!( - "Wallet configuration '{}' deleted successfully", - self.wallet_name - ), - }) + Ok(json!({ + "message": format!( + "Wallet configuration '{}' deleted successfully", + self.wallet_name + ), + })) } } diff --git a/src/handlers/descriptor.rs b/src/handlers/descriptor.rs index 598617ae..5453010a 100644 --- a/src/handlers/descriptor.rs +++ b/src/handlers/descriptor.rs @@ -1,5 +1,4 @@ use crate::handlers::Init; -use crate::utils::types::DescriptorResult; use crate::{ error::BDKCliError as Error, handlers::{AppCommand, AppContext}, @@ -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) @@ -36,19 +33,38 @@ pub struct DescriptorCommand { key: Option, } impl AppCommand> for DescriptorCommand { - type Output = DescriptorResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { - 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) -> Result { + 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) } } @@ -76,24 +92,18 @@ pub struct CompileCommand { #[cfg(feature = "compiler")] impl AppCommand> for CompileCommand { - type Output = DescriptorResult; - - fn execute(&self, _ctx: &mut AppContext) -> Result { + fn execute(&self, _ctx: &mut AppContext) -> Result { let (descriptor, r) = if self.placeholders { compile_policy::(&self.policy, self.script_type)? } else { compile_policy::(&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) } } @@ -110,14 +120,10 @@ pub struct SilentPaymentCodeCommand { #[cfg(feature = "silent-payments")] impl AppCommand> for SilentPaymentCodeCommand { - type Output = StatusResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { 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() })) } } diff --git a/src/handlers/dns/mod.rs b/src/handlers/dns/mod.rs index e1c5b8df..2e3309ca 100644 --- a/src/handlers/dns/mod.rs +++ b/src/handlers/dns/mod.rs @@ -5,7 +5,6 @@ use crate::handlers::dns::dns_payment_instructions::{ parse_dns_instructions, process_instructions, resolve_dns_recipient, }; use crate::handlers::{AppContext, AsyncAppCommand, Init, OfflineOperations}; -use crate::utils::types::{PsbtResult, StatusResult}; 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, @@ -13,6 +12,7 @@ use crate::utils::{ use bdk_wallet::KeychainKind; use bdk_wallet::bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf}; use clap::Parser; +use serde_json::{Value, json}; use std::collections::BTreeMap; /// Resolves BIP-353 DNS payment instructions for a human-readable name. @@ -26,15 +26,11 @@ pub struct ResolveDnsRecipientCommand { } impl AsyncAppCommand> for ResolveDnsRecipientCommand { - type Output = StatusResult; - - async fn execute(&self, ctx: &mut AppContext) -> Result { + async fn execute(&self, ctx: &mut AppContext) -> Result { let resolved = resolve_dns_recipient(&self.hrn, ctx.network, &self.resolver) .await .map_err(|e| Error::Generic(format!("{:?}", e)))?; - Ok(StatusResult { - message: resolved.display()?, - }) + Ok(json!({ "message": resolved.display()? })) } } @@ -82,12 +78,7 @@ pub struct CreateDnsTxCommand { } impl AsyncAppCommand>> for CreateDnsTxCommand { - type Output = PsbtResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let network = ctx.network; let mut recipients: Vec<(ScriptBuf, u64)> = self.recipients.clone(); @@ -159,6 +150,6 @@ impl AsyncAppCommand>> for CreateDnsTxCommand { let psbt = tx_builder.finish()?; check_standard_weight(max_signed_weight(ctx.state.wallet, &psbt)?)?; - Ok(PsbtResult::new(&psbt, Some(false))) + Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false })) } } diff --git a/src/handlers/hwi.rs b/src/handlers/hwi.rs index 4bf285a4..ab1d555e 100644 --- a/src/handlers/hwi.rs +++ b/src/handlers/hwi.rs @@ -14,7 +14,7 @@ use async_hwi::AddressScript; use bdk_wallet::KeychainKind; use clap::{Parser, Subcommand}; -use serde_json::json; +use serde_json::{Value, json}; use std::str::FromStr; use crate::error::BDKCliError as Error; @@ -61,9 +61,7 @@ pub enum HwiSubCommand { } impl AsyncAppCommand> for HwiCommand { - type Output = serde_json::Value; - - async fn execute(&self, ctx: &mut AppContext) -> Result { + async fn execute(&self, ctx: &mut AppContext) -> Result { let network = ctx.network; // Device-only commands operate without a wallet policy. let hwi_wallet = HwiWallet::default(); @@ -198,7 +196,7 @@ impl WalletHwiCommand { &self, ctx: &mut AppContext>, wallet_name: &str, - ) -> Result { + ) -> Result { let network = ctx.network; let target_fp = self.fingerprint.as_deref(); diff --git a/src/handlers/key.rs b/src/handlers/key.rs index 4b67b11a..6a25a40f 100644 --- a/src/handlers/key.rs +++ b/src/handlers/key.rs @@ -1,15 +1,16 @@ use crate::commands::KeySubCommand; use crate::error::BDKCliError as Error; use crate::handlers::{AppCommand, AppContext, Init}; -use crate::utils::{output::FormatOutput, types::KeyResult}; +use crate::utils::output::FormatOutput; use bdk_wallet::bip39::{Language, Mnemonic}; -use bdk_wallet::bitcoin::bip32::{DerivationPath, KeySource, Xpriv}; +use bdk_wallet::bitcoin::bip32::{DerivationPath, Fingerprint, KeySource, Xpriv}; use bdk_wallet::bitcoin::{Network, key::Secp256k1}; use bdk_wallet::keys::{ DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, bip39::WordCount, }; use bdk_wallet::miniscript::{self, Segwitv0}; use clap::{Parser, ValueEnum}; +use serde_json::{Value, json}; impl KeySubCommand { pub fn execute(&self, ctx: &mut AppContext) -> Result<(), Error> { @@ -63,13 +64,19 @@ pub struct GenerateKeyCommand { } impl AppCommand> for GenerateKeyCommand { - type Output = KeyResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { let mnemonic: GeneratedKey<_, miniscript::BareCtx> = Mnemonic::generate((self.word_count.into(), Language::English)) .map_err(|_| Error::Generic("Mnemonic generation error".to_string()))?; - derive_master_key_from_mnemonic(mnemonic.into_key(), self.password.clone(), ctx.network) + let mnemonic = mnemonic.into_key(); + let (xprv, fingerprint) = + derive_master_key_from_mnemonic(&mnemonic, self.password.clone(), ctx.network)?; + + Ok(json!({ + "xprv": xprv.to_string(), + "mnemonic": mnemonic.to_string(), + "fingerprint": fingerprint.to_string(), + })) } } @@ -84,9 +91,7 @@ pub struct DeriveKeyCommand { } impl AppCommand> for DeriveKeyCommand { - type Output = KeyResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { let secp = Secp256k1::new(); let derived_xprv = &self.xprv.derive_priv(&secp, &self.path)?; @@ -105,12 +110,10 @@ impl AppCommand> for DeriveKeyCommand { if let DescriptorKey::Secret(desc_seckey, _, _) = derived_xprv_desc_key { let desc_pubkey = desc_seckey.to_public(&secp)?; - Ok(KeyResult { - xprv: desc_seckey.to_string(), - xpub: Some(desc_pubkey.to_string()), - mnemonic: None, - fingerprint: None, - }) + Ok(json!({ + "xprv": desc_seckey.to_string(), + "xpub": desc_pubkey.to_string(), + })) } else { Err(Error::Generic( "Derived key is not a secret key".to_string(), @@ -130,20 +133,25 @@ pub struct RestoreKeyCommand { } impl AppCommand> for RestoreKeyCommand { - type Output = KeyResult; - - fn execute(&self, ctx: &mut AppContext) -> Result { + fn execute(&self, ctx: &mut AppContext) -> Result { let mnemonic = Mnemonic::parse_in(Language::English, &self.mnemonic)?; - derive_master_key_from_mnemonic(mnemonic, self.password.clone(), ctx.network) + let (xprv, fingerprint) = + derive_master_key_from_mnemonic(&mnemonic, self.password.clone(), ctx.network)?; + + Ok(json!({ + "xprv": xprv.to_string(), + "mnemonic": mnemonic.to_string(), + "fingerprint": fingerprint.to_string(), + })) } } /// Derives the master key from a mnemonic and optional passphrase. fn derive_master_key_from_mnemonic( - mnemonic: Mnemonic, + mnemonic: &Mnemonic, password: Option, network: Network, -) -> Result { +) -> Result<(Xpriv, Fingerprint), Error> { let secp = Secp256k1::new(); let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?; let xprv = xkey @@ -151,10 +159,5 @@ fn derive_master_key_from_mnemonic( .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?; let fingerprint = xprv.fingerprint(&secp); - Ok(KeyResult { - xprv: xprv.to_string(), - mnemonic: Some(mnemonic.to_string()), - fingerprint: Some(fingerprint.to_string()), - xpub: None, - }) + Ok((xprv, fingerprint)) } diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index bf8be129..eb2fbe53 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -25,8 +25,9 @@ pub mod repl; use crate::client::BlockchainClient; use std::path::PathBuf; -use crate::{error::BDKCliError as Error, utils::output::FormatOutput}; +use crate::error::BDKCliError as Error; use bdk_wallet::{Wallet, bitcoin::Network}; +use serde_json::Value; // The state for no wallet, no client. pub struct Init; @@ -105,9 +106,7 @@ impl<'a> AppContext> { } pub trait AppCommand { - type Output: FormatOutput; - - fn execute(&self, ctx: &mut C) -> Result; + fn execute(&self, ctx: &mut C) -> Result; } #[cfg(any( @@ -119,9 +118,7 @@ pub trait AppCommand { feature = "hwi" ))] pub trait AsyncAppCommand { - type Output: FormatOutput; - - async fn execute(&self, ctx: &mut C) -> Result; + async fn execute(&self, ctx: &mut C) -> Result; } #[cfg(test)] diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 9aa15fcb..31aee423 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -1,22 +1,17 @@ use crate::commands::OfflineWalletSubCommand; use crate::error::BDKCliError as Error; use crate::handlers::{AppCommand, AppContext, OfflineOperations}; -use crate::utils::output::{FormatOutput, ListResult}; -use crate::utils::types::{ - AddressResult, BalanceResult, KeychainPair, PsbtResult, RawPsbt, TransactionDetails, - UnspentDetails, -}; +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, }; -use bdk_wallet::bitcoin::base64::Engine; -use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD; -use bdk_wallet::bitcoin::script::PushBytesBuf; +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::{KeychainKind, SignOptions}; use clap::Parser; -use serde_json::json; +use serde_json::{Value, json}; use std::collections::BTreeMap; #[cfg(feature = "silent-payments")] use { @@ -33,7 +28,6 @@ use { #[cfg(feature = "message_signer")] use { crate::utils::parse_signature_format, - crate::utils::types::MessageResult, bdk_message_signer::{MessageProof, MessageSigner}, }; @@ -100,12 +94,13 @@ impl OfflineWalletSubCommand { pub struct NewAddressCommand; impl AppCommand>> for NewAddressCommand { - type Output = AddressResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let address_info = wallet.reveal_next_address(KeychainKind::External); - Ok(AddressResult::from(address_info)) + Ok(json!({ + "address": address_info.address.to_string(), + "index": address_info.index, + })) } } @@ -113,12 +108,13 @@ impl AppCommand>> for NewAddressCommand { pub struct UnusedAddressCommand; impl AppCommand>> for UnusedAddressCommand { - type Output = AddressResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let address_info = wallet.next_unused_address(KeychainKind::External); - Ok(AddressResult::from(address_info)) + Ok(json!({ + "address": address_info.address.to_string(), + "index": address_info.index, + })) } } @@ -126,20 +122,25 @@ impl AppCommand>> for UnusedAddressCommand { pub struct UnspentCommand; impl AppCommand>> for UnspentCommand { - type Output = ListResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let outputs: Vec<_> = wallet.list_unspent().collect(); - let utxos = outputs + let utxos: Vec = outputs .into_iter() .map(|utxo| { - let is_locked = wallet.is_outpoint_locked(utxo.outpoint); - UnspentDetails::from_local_output(&utxo, ctx.network, is_locked) + json!({ + "outpoint": utxo.outpoint.to_string(), + "txout": utxo.txout, + "keychain": format!("{:?}", utxo.keychain), + "is_spent": utxo.is_spent, + "derivation_index": utxo.derivation_index, + "chain_position": utxo.chain_position, + "is_locked": wallet.is_outpoint_locked(utxo.outpoint), + }) }) .collect(); - Ok(ListResult::new(utxos)) + Ok(json!({ "count": utxos.len(), "items": utxos })) } } @@ -147,37 +148,24 @@ impl AppCommand>> for UnspentCommand { pub struct TransactionsCommand; impl AppCommand>> for TransactionsCommand { - type Output = ListResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let transactions = &mut ctx.state.wallet.transactions(); - let txns: Vec = transactions + let txns: Vec = transactions .map(|tx| { - let total_value = tx - .tx_node - .output - .iter() - .map(|output| output.value.to_sat()) - .sum::(); - - TransactionDetails { - txid: tx.tx_node.txid.to_string(), - is_coinbase: tx.tx_node.is_coinbase(), - wtxid: tx.tx_node.compute_wtxid().to_string(), - version: serde_json::to_value(tx.tx_node.version).unwrap_or(json!(1)), - version_display: tx.tx_node.version.to_string(), - is_rbf: tx.tx_node.is_explicitly_rbf(), - inputs: serde_json::to_value(&tx.tx_node.input).unwrap_or_default(), - outputs: serde_json::to_value(&tx.tx_node.output).unwrap_or_default(), - input_count: tx.tx_node.input.len(), - output_count: tx.tx_node.output.len(), - total_value, - } + json!({ + "txid": tx.tx_node.txid.to_string(), + "is_coinbase": tx.tx_node.is_coinbase(), + "wtxid": tx.tx_node.compute_wtxid().to_string(), + "version": tx.tx_node.version, + "is_rbf": tx.tx_node.is_explicitly_rbf(), + "inputs": tx.tx_node.input, + "outputs": tx.tx_node.output, + }) }) .collect(); - Ok(ListResult::new(txns)) + Ok(json!({ "count": txns.len(), "items": txns })) } } @@ -185,11 +173,15 @@ impl AppCommand>> for TransactionsCommand { pub struct BalanceCommand; impl AppCommand>> for BalanceCommand { - type Output = BalanceResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let balance = ctx.state.wallet.balance(); - Ok(BalanceResult::from(balance)) + Ok(json!({ + "total": balance.total().to_sat(), + "trusted_pending": balance.trusted_pending.to_sat(), + "untrusted_pending": balance.untrusted_pending.to_sat(), + "immature": balance.immature.to_sat(), + "confirmed": balance.confirmed.to_sat(), + })) } } #[derive(Debug, Parser, Clone, PartialEq)] @@ -252,9 +244,7 @@ pub struct CreateTxCommand { } impl AppCommand>> for CreateTxCommand { - type Output = PsbtResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let mut tx_builder = ctx.state.wallet.build_tx(); if self.send_all { @@ -319,7 +309,7 @@ impl AppCommand>> for CreateTxCommand { check_standard_weight(max_signed_weight(ctx.state.wallet, &psbt)?)?; - Ok(PsbtResult::new(&psbt, Some(false))) + Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false })) } } @@ -377,9 +367,7 @@ pub struct CreateSpTxCommand { #[cfg(feature = "silent-payments")] impl AppCommand>> for CreateSpTxCommand { - type Output = RawPsbt; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let mut tx_builder = ctx.state.wallet.build_tx(); let sp_recipients: Vec = self @@ -539,7 +527,7 @@ impl AppCommand>> for CreateSpTxCommand { let raw_tx = psbt.extract_tx()?; - Ok(RawPsbt::new(&raw_tx)) + Ok(json!({ "raw_tx": serialize_hex(&raw_tx) })) } } @@ -577,9 +565,7 @@ pub struct BumpFeeCommand { } impl AppCommand>> for BumpFeeCommand { - type Output = PsbtResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let mut tx_builder = wallet.build_fee_bump(self.txid)?; @@ -606,7 +592,7 @@ impl AppCommand>> for BumpFeeCommand { check_standard_weight(max_signed_weight(wallet, &psbt)?)?; - Ok(PsbtResult::new(&psbt, Some(false))) + Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false })) } } @@ -614,17 +600,12 @@ impl AppCommand>> for BumpFeeCommand { pub struct PoliciesCommand; impl AppCommand>> for PoliciesCommand { - type Output = KeychainPair; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let external_policy = wallet.policies(KeychainKind::External)?; let internal_policy = wallet.policies(KeychainKind::Internal)?; - Ok(KeychainPair { - external: serde_json::to_value(&external_policy).unwrap_or(serde_json::json!(null)), - internal: serde_json::to_value(&internal_policy).unwrap_or(serde_json::json!(null)), - }) + Ok(json!({ "external": external_policy, "internal": internal_policy })) } } @@ -632,14 +613,12 @@ impl AppCommand>> for PoliciesCommand { pub struct PublicDescriptorCommand; impl AppCommand>> for PublicDescriptorCommand { - type Output = KeychainPair; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; - Ok(KeychainPair { - external: wallet.public_descriptor(KeychainKind::External).to_string(), - internal: wallet.public_descriptor(KeychainKind::Internal).to_string(), - }) + Ok(json!({ + "external": wallet.public_descriptor(KeychainKind::External).to_string(), + "internal": wallet.public_descriptor(KeychainKind::Internal).to_string(), + })) } } @@ -659,9 +638,7 @@ pub struct SignCommand { } impl AppCommand>> for SignCommand { - type Output = PsbtResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?; let mut psbt = Psbt::deserialize(&psbt_bytes)?; @@ -672,7 +649,7 @@ impl AppCommand>> for SignCommand { ..Default::default() }; let finalized = wallet.sign(&mut psbt, signopt)?; - Ok(PsbtResult::new(&psbt, Some(finalized))) + Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized })) } } @@ -684,14 +661,12 @@ pub struct ExtractPsbtCommand { } impl AppCommand>> for ExtractPsbtCommand { - type Output = RawPsbt; - - fn execute(&self, _ctx: &mut AppContext>) -> Result { + fn execute(&self, _ctx: &mut AppContext>) -> Result { let psbt_serialized = BASE64_STANDARD.decode(self.psbt.clone())?; let psbt = Psbt::deserialize(&psbt_serialized)?; let raw_tx = psbt.extract_tx()?; - Ok(RawPsbt::new(&raw_tx)) + Ok(json!({ "raw_tx": serialize_hex(&raw_tx) })) } } @@ -711,9 +686,7 @@ pub struct FinalizePsbtCommand { } impl AppCommand>> for FinalizePsbtCommand { - type Output = PsbtResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?; let mut psbt = Psbt::deserialize(&psbt_bytes)?; @@ -726,7 +699,7 @@ impl AppCommand>> for FinalizePsbtCommand { let finalized = wallet.finalize_psbt(&mut psbt, signopt)?; - Ok(PsbtResult::new(&psbt, Some(finalized))) + Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized })) } } @@ -738,9 +711,7 @@ pub struct CombinePsbtCommand { } impl AppCommand>> for CombinePsbtCommand { - type Output = PsbtResult; - - fn execute(&self, _ctx: &mut AppContext>) -> Result { + fn execute(&self, _ctx: &mut AppContext>) -> Result { let mut psbts = self .psbt .iter() @@ -761,7 +732,7 @@ impl AppCommand>> for CombinePsbtCommand { Ok(acc) })?; - Ok(PsbtResult::new(&final_psbt, Some(false))) + Ok(json!({ "psbt": final_psbt.to_string(), "is_finalized": false })) } } @@ -787,9 +758,7 @@ pub struct SignMessageCommand { #[cfg(feature = "message_signer")] impl AppCommand>> for SignMessageCommand { - type Output = MessageResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let address: Address = parse_address(&self.address)?; let signature_format = parse_signature_format(&self.signature_type)?; @@ -808,10 +777,7 @@ impl AppCommand>> for SignMessageCommand { self.utxos.clone(), )?; - Ok(MessageResult { - proof: Some(proof.to_base64()), - ..Default::default() - }) + Ok(json!({ "proof": proof.to_base64() })) } } @@ -833,9 +799,7 @@ pub struct VerifyMessageCommand { #[cfg(feature = "message_signer")] impl AppCommand>> for VerifyMessageCommand { - type Output = MessageResult; - - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &ctx.state.wallet; let address: Address = parse_address(&self.address)?; @@ -845,11 +809,11 @@ impl AppCommand>> for VerifyMessageCommand { let is_valid = wallet.verify_message(&parsed_proof, &self.message, &address)?; - Ok(MessageResult { - valid: Some(is_valid.valid), - proven_amount: is_valid.proven_amount.map(|a| a.to_sat()), - ..Default::default() - }) + let mut output = json!({ "valid": is_valid.valid }); + if let Some(amount) = is_valid.proven_amount { + output["proven_amount"] = json!(amount.to_sat()); + } + Ok(output) } } @@ -861,8 +825,7 @@ pub struct LockUtxoCommand { } impl AppCommand>> for LockUtxoCommand { - type Output = ListResult; - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; for out_point in &self.utxos { if wallet.get_utxo(*out_point).is_none() { @@ -871,11 +834,11 @@ impl AppCommand>> for LockUtxoCommand { } wallet.lock_outpoint(*out_point); } - let locked = wallet + let locked: Vec = wallet .list_locked_outpoints() .map(|o| o.to_string()) .collect(); - Ok(ListResult::new(locked)) + Ok(json!({ "count": locked.len(), "items": locked })) } } @@ -887,17 +850,16 @@ pub struct UnlockUtxoCommand { } impl AppCommand>> for UnlockUtxoCommand { - type Output = ListResult; - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; for out_point in &self.utxos { wallet.unlock_outpoint(*out_point); } - let locked = wallet + let locked: Vec = wallet .list_locked_outpoints() .map(|o| o.to_string()) .collect(); - Ok(ListResult::new(locked)) + Ok(json!({ "count": locked.len(), "items": locked })) } } @@ -905,13 +867,12 @@ impl AppCommand>> for UnlockUtxoCommand { pub struct LockedUtxosCommand {} impl AppCommand>> for LockedUtxosCommand { - type Output = ListResult; - fn execute(&self, ctx: &mut AppContext>) -> Result { + fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; - let locked = wallet + let locked: Vec = wallet .list_locked_outpoints() .map(|o| o.to_string()) .collect(); - Ok(ListResult::new(locked)) + Ok(json!({ "count": locked.len(), "items": locked })) } } diff --git a/src/handlers/online.rs b/src/handlers/online.rs index 15ac2aee..7e11d84c 100644 --- a/src/handlers/online.rs +++ b/src/handlers/online.rs @@ -28,15 +28,12 @@ use { crate::commands::OnlineWalletSubCommand, crate::error::BDKCliError as Error, crate::handlers::{AppContext, AsyncAppCommand, OnlineOperations, payjoin::PayjoinManager}, - crate::utils::{ - is_final, - output::FormatOutput, - types::{StatusResult, TransactionResult}, - }, + crate::utils::{is_final, output::FormatOutput}, bdk_wallet::bitcoin::{ Psbt, Transaction, Txid, base64::Engine, base64::prelude::BASE64_STANDARD, consensus::Decodable, hex::FromHex, }, + serde_json::{Value, json}, }; #[cfg(any( feature = "electrum", @@ -47,33 +44,37 @@ use { impl OnlineWalletSubCommand { pub async fn execute(&self, ctx: &mut AppContext>) -> Result<(), Error> { match self { - OnlineWalletSubCommand::FullScan(full_scan_command) => { - let response: StatusResult = full_scan_command.execute(ctx).await?; - response.write_out(std::io::stdout()) - } - OnlineWalletSubCommand::Sync(sync_command) => { - let response: StatusResult = sync_command.execute(ctx).await?; - response.write_out(std::io::stdout()) - } - OnlineWalletSubCommand::Broadcast(broadcast_command) => { - let response: TransactionResult = broadcast_command.execute(ctx).await?; - response.write_out(std::io::stdout()) - } + OnlineWalletSubCommand::FullScan(full_scan_command) => full_scan_command + .execute(ctx) + .await? + .write_out(std::io::stdout()), + OnlineWalletSubCommand::Sync(sync_command) => sync_command + .execute(ctx) + .await? + .write_out(std::io::stdout()), + OnlineWalletSubCommand::Broadcast(broadcast_command) => broadcast_command + .execute(ctx) + .await? + .write_out(std::io::stdout()), OnlineWalletSubCommand::ReceivePayjoin(receive_payjoin_command) => { - let response: StatusResult = receive_payjoin_command.execute(ctx).await?; - response.write_out(std::io::stdout()) - } - OnlineWalletSubCommand::SendPayjoin(send_payjoin_command) => { - let response: StatusResult = send_payjoin_command.execute(ctx).await?; - response.write_out(std::io::stdout()) - } - OnlineWalletSubCommand::ResumePayjoin(resume_payjoin_command) => { - let response: StatusResult = resume_payjoin_command.execute(ctx).await?; - response.write_out(std::io::stdout()) + receive_payjoin_command + .execute(ctx) + .await? + .write_out(std::io::stdout()) } + OnlineWalletSubCommand::SendPayjoin(send_payjoin_command) => send_payjoin_command + .execute(ctx) + .await? + .write_out(std::io::stdout()), + OnlineWalletSubCommand::ResumePayjoin(resume_payjoin_command) => resume_payjoin_command + .execute(ctx) + .await? + .write_out(std::io::stdout()), OnlineWalletSubCommand::PayjoinHistory(payjoin_history_command) => { - let response: StatusResult = payjoin_history_command.execute(ctx).await?; - response.write_out(std::io::stdout()) + payjoin_history_command + .execute(ctx) + .await? + .write_out(std::io::stdout()) } } } @@ -143,12 +144,7 @@ impl FullScanCommand { feature = "rpc" ))] impl AsyncAppCommand>> for FullScanCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let client = ctx.state.client; @@ -242,9 +238,7 @@ impl AsyncAppCommand>> for FullScanCommand { sync_kyoto_client(wallet, client).await?; } } - Ok(StatusResult { - message: "Full scan completed successfully.".to_string(), - }) + Ok(json!({ "message": "Full scan completed successfully." })) } } @@ -279,12 +273,7 @@ pub struct SyncCommand; feature = "rpc" ))] impl AsyncAppCommand>> for SyncCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet = &mut ctx.state.wallet; let client = ctx.state.client; #[cfg(any(feature = "electrum", feature = "esplora"))] @@ -371,9 +360,7 @@ impl AsyncAppCommand>> for SyncCommand { #[cfg(feature = "cbf")] KyotoClient { client } => sync_kyoto_client(wallet, client).await?, } - Ok(StatusResult { - message: "Wallet synced successfully.".to_string(), - }) + Ok(json!({ "message": "Wallet synced successfully." })) } } @@ -404,12 +391,7 @@ pub struct BroadcastCommand { feature = "rpc" ))] impl AsyncAppCommand>> for BroadcastCommand { - type Output = TransactionResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let client = ctx.state.client; let tx = match (&self.psbt, &self.tx) { @@ -437,9 +419,7 @@ impl AsyncAppCommand>> for BroadcastCommand { let txid: Txid = client.broadcast(tx).await?; - Ok(TransactionResult { - txid: txid.to_string(), - }) + Ok(json!({ "txid": txid.to_string() })) } } @@ -468,12 +448,7 @@ pub struct ReceivePayjoinCommand { feature = "rpc" ))] impl AsyncAppCommand>> for ReceivePayjoinCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet_name = ctx.state.wallet_name.clone(); let datadir = ctx.datadir.clone(); let wallet = &mut ctx.state.wallet; @@ -490,7 +465,7 @@ impl AsyncAppCommand>> for ReceivePayjoinCommand ) .await?; - Ok(StatusResult { message: result }) + Ok(json!({ "message": result })) } } @@ -520,12 +495,7 @@ pub struct SendPayjoinCommand { feature = "rpc" ))] impl AsyncAppCommand>> for SendPayjoinCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet_name = ctx.state.wallet_name.clone(); let datadir = ctx.datadir.clone(); let wallet = &mut ctx.state.wallet; @@ -541,7 +511,7 @@ impl AsyncAppCommand>> for SendPayjoinCommand { ) .await?; - Ok(StatusResult { message: result }) + Ok(json!({ "message": result })) } } @@ -565,12 +535,7 @@ pub struct ResumePayjoinCommand { feature = "rpc" ))] impl AsyncAppCommand>> for ResumePayjoinCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet_name = ctx.state.wallet_name.clone(); let datadir = ctx.datadir.clone(); let wallet = &mut ctx.state.wallet; @@ -586,7 +551,7 @@ impl AsyncAppCommand>> for ResumePayjoinCommand ) .await?; - Ok(StatusResult { message: result }) + Ok(json!({ "message": result })) } } @@ -600,17 +565,12 @@ pub struct PayjoinHistoryCommand; feature = "rpc" ))] impl AsyncAppCommand>> for PayjoinHistoryCommand { - type Output = StatusResult; - - async fn execute( - &self, - ctx: &mut AppContext>, - ) -> Result { + async fn execute(&self, ctx: &mut AppContext>) -> Result { let wallet_name = ctx.state.wallet_name.clone(); let datadir = ctx.datadir.clone(); let result = PayjoinManager::history(Some(datadir), &wallet_name)?; - Ok(StatusResult { message: result }) + Ok(json!({ "message": result })) } } diff --git a/src/utils/descriptors.rs b/src/utils/descriptors.rs index 15e8bca7..fd34aa3f 100644 --- a/src/utils/descriptors.rs +++ b/src/utils/descriptors.rs @@ -25,26 +25,33 @@ use bdk_wallet::{ bip39::{Language, Mnemonic}, bitcoin::{ NetworkKind, - bip32::{DerivationPath, Xpriv, Xpub}, + bip32::{DerivationPath, Fingerprint, Xpriv, Xpub}, secp256k1::Secp256k1, }, keys::{GeneratedKey, bip39::WordCount}, miniscript::{ Descriptor, Miniscript, Segwitv0, Terminal, - descriptor::{DescriptorXKey, Wildcard}, + descriptor::{DescriptorXKey, KeyMap, Wildcard}, }, template::DescriptorTemplate, }; use crate::error::BDKCliError as Error; -use crate::utils::types::DescriptorResult; -use crate::utils::types::KeychainPair; + +/// External and internal descriptors generated from a single key. +pub struct KeychainDescriptors { + pub external: Descriptor, + pub internal: Descriptor, + /// Secret keys for both descriptors; empty when generated from an xpub. + pub keymap: KeyMap, + pub fingerprint: Fingerprint, +} pub fn generate_descriptors( desc_type: &str, key: &str, network: NetworkKind, -) -> Result { +) -> Result { let is_private = key.starts_with("xprv") || key.starts_with("tprv"); if is_private { @@ -71,7 +78,7 @@ fn generate_private_descriptors( desc_type: &str, key: &str, network: NetworkKind, -) -> Result { +) -> Result { use bdk_wallet::template::{Bip44, Bip49, Bip84, Bip86}; let secp = Secp256k1::new(); @@ -102,25 +109,14 @@ fn generate_private_descriptors( } }; - let external_priv = external_desc.to_string_with_secret(&external_keymap); - let external_pub = external_desc.to_string(); - let internal_priv = internal_desc.to_string_with_secret(&internal_keymap); - let internal_pub = internal_desc.to_string(); - - Ok(DescriptorResult { - descriptor: None, - multipath_descriptor: None, - public_descriptors: Some(KeychainPair { - external: external_pub, - internal: internal_pub, - }), - private_descriptors: Some(KeychainPair { - external: external_priv, - internal: internal_priv, - }), - mnemonic: None, - fingerprint: Some(fingerprint.to_string()), - r: None, + let mut keymap = external_keymap; + keymap.extend(internal_keymap); + + Ok(KeychainDescriptors { + external: external_desc, + internal: internal_desc, + keymap, + fingerprint, }) } @@ -129,11 +125,11 @@ pub fn generate_public_descriptors( desc_type: &str, key: &str, derivation_path: &DerivationPath, -) -> Result { +) -> Result { let xpub: Xpub = key.parse()?; let fingerprint = xpub.fingerprint(); - let build_descriptor = |branch: &str| -> Result { + let build_descriptor = |branch: &str| -> Result, Error> { let branch_path = DerivationPath::from_str(branch)?; let desc_xpub = DescriptorXKey { origin: Some((fingerprint, derivation_path.clone())), @@ -142,23 +138,14 @@ pub fn generate_public_descriptors( wildcard: Wildcard::Unhardened, }; let desc_pub = DescriptorPublicKey::XPub(desc_xpub); - let descriptor = build_public_descriptor(desc_type, desc_pub)?; - Ok(descriptor.to_string()) + build_public_descriptor(desc_type, desc_pub) }; - let external_pub = build_descriptor("0")?; - let internal_pub = build_descriptor("1")?; - Ok(DescriptorResult { - descriptor: None, - multipath_descriptor: None, - public_descriptors: Some(KeychainPair { - external: external_pub, - internal: internal_pub, - }), - private_descriptors: None, - mnemonic: None, - fingerprint: Some(fingerprint.to_string()), - r: None, + Ok(KeychainDescriptors { + external: build_descriptor("0")?, + internal: build_descriptor("1")?, + keymap: KeyMap::new(), + fingerprint, }) } @@ -188,16 +175,15 @@ pub fn build_public_descriptor( pub fn generate_descriptor_with_mnemonic( network: NetworkKind, desc_type: &str, -) -> Result { +) -> Result<(Mnemonic, KeychainDescriptors), Error> { let mnemonic: GeneratedKey = Mnemonic::generate((WordCount::Words12, Language::English)).map_err(Error::BIP39Error)?; let seed = mnemonic.to_seed(""); let xprv = Xpriv::new_master(network, &seed)?; - let mut result = generate_descriptors(desc_type, &xprv.to_string(), network)?; - result.mnemonic = Some(mnemonic.to_string()); - Ok(result) + let descriptors = generate_descriptors(desc_type, &xprv.to_string(), network)?; + Ok((mnemonic.into_key(), descriptors)) } /// Generate descriptors from existing mnemonic @@ -205,14 +191,12 @@ pub fn generate_descriptor_from_mnemonic( mnemonic_str: &str, network: NetworkKind, desc_type: &str, -) -> Result { +) -> Result { let mnemonic = Mnemonic::parse_in(Language::English, mnemonic_str)?; let seed = mnemonic.to_seed(""); let xprv = Xpriv::new_master(network, &seed)?; - let mut result = generate_descriptors(desc_type, &xprv.to_string(), network)?; - result.mnemonic = Some(mnemonic_str.to_string()); - Ok(result) + generate_descriptors(desc_type, &xprv.to_string(), network) } /// Returns the number of derivation paths in `descriptor`. diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 15138df5..cf9cee13 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -5,4 +5,3 @@ pub use common::*; #[cfg(feature = "hwi")] pub mod hwi; pub mod runtime; -pub mod types; diff --git a/src/utils/output.rs b/src/utils/output.rs index b2cd32a2..efbd4ffe 100644 --- a/src/utils/output.rs +++ b/src/utils/output.rs @@ -19,19 +19,3 @@ pub trait FormatOutput: Serialize { } impl FormatOutput for T {} - -/// A generic wrapper for commands that return a list of items. -#[derive(Serialize)] -pub struct ListResult { - pub count: usize, - pub items: Vec, -} - -impl ListResult { - pub fn new(items: Vec) -> Self { - Self { - count: items.len(), - items, - } - } -} diff --git a/src/utils/types.rs b/src/utils/types.rs deleted file mode 100644 index f6bd4cfd..00000000 --- a/src/utils/types.rs +++ /dev/null @@ -1,207 +0,0 @@ -use std::collections::HashMap; - -use crate::config::WalletConfigInner; -use bdk_wallet::Balance; -use bdk_wallet::bitcoin::{ - Network, Psbt, Transaction, base64::Engine, consensus::encode::serialize_hex, -}; -use bdk_wallet::{AddressInfo, LocalOutput}; -use serde::Serialize; -use serde_json::json; - -/// Represent address result -#[derive(Serialize)] -pub struct AddressResult { - pub address: String, - pub index: u32, -} - -impl From for AddressResult { - fn from(info: AddressInfo) -> Self { - Self { - address: info.address.to_string(), - index: info.index, - } - } -} - -#[allow(unused)] -/// Represents the data for a single transaction -#[derive(Serialize)] -pub struct TransactionDetails { - pub txid: String, - pub is_coinbase: bool, - pub wtxid: String, - pub version: serde_json::Value, - pub is_rbf: bool, - pub inputs: serde_json::Value, - pub outputs: serde_json::Value, - #[serde(skip)] - pub version_display: String, - #[serde(skip)] - pub input_count: usize, - #[serde(skip)] - pub output_count: usize, - #[serde(skip)] - pub total_value: u64, -} - -/// single UTXO -#[derive(Serialize)] -pub struct UnspentDetails { - pub outpoint: String, - pub txout: serde_json::Value, - pub keychain: String, - pub is_spent: bool, - pub derivation_index: u32, - pub chain_position: serde_json::Value, - pub is_locked: bool, -} - -impl UnspentDetails { - pub fn from_local_output(utxo: &LocalOutput, _network: Network, is_locked: bool) -> Self { - let outpoint_str = utxo.outpoint.to_string(); - - Self { - outpoint: outpoint_str.clone(), - txout: serde_json::to_value(&utxo.txout).unwrap_or(json!({})), - keychain: format!("{:?}", utxo.keychain), - is_spent: utxo.is_spent, - derivation_index: utxo.derivation_index, - chain_position: serde_json::to_value(utxo.chain_position).unwrap_or(json!({})), - is_locked, - } - } -} - -#[derive(Serialize)] -pub struct PsbtResult { - pub psbt: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub is_finalized: Option, -} - -impl PsbtResult { - pub fn new(psbt: &Psbt, finalized: Option) -> Self { - Self { - psbt: bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD.encode(psbt.serialize()), - is_finalized: finalized, - } - } -} - -#[derive(Serialize)] -pub struct RawPsbt { - pub raw_tx: String, -} - -impl RawPsbt { - pub fn new(tx: &Transaction) -> Self { - Self { - raw_tx: serialize_hex(tx), - } - } -} - -#[derive(Serialize)] -pub struct KeychainPair { - pub external: T, - pub internal: T, -} - -#[cfg(feature = "message_signer")] -#[derive(Serialize, Debug, Default)] -pub struct MessageResult { - #[serde(skip_serializing_if = "Option::is_none")] - pub proof: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub valid: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub proven_amount: Option, -} - -#[derive(Serialize, Debug)] -pub struct StatusResult { - pub message: String, -} - -#[cfg(any( - feature = "electrum", - feature = "esplora", - feature = "cbf", - feature = "rpc" -))] -#[derive(Serialize, Debug)] -pub struct TransactionResult { - pub txid: String, -} - -/// Return type definition -#[derive(Serialize)] -#[serde(transparent)] -pub struct WalletsListResult(pub HashMap); - -/// return type -#[derive(Serialize)] -pub struct DescriptorResult { - #[serde(skip_serializing_if = "Option::is_none")] - pub descriptor: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub multipath_descriptor: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub public_descriptors: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub private_descriptors: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub mnemonic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Randomness factor `r` used to derive the taproot unspendable internal key (H + rG). - #[serde(skip_serializing_if = "Option::is_none")] - pub r: Option, -} - -#[derive(Serialize)] -pub struct KeyResult { - pub xprv: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub xpub: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub mnemonic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, -} - -/// Balance representation -#[derive(Serialize)] -pub struct BalanceResult { - pub total: u64, - pub trusted_pending: u64, - pub untrusted_pending: u64, - pub immature: u64, - pub confirmed: u64, -} - -impl From for BalanceResult { - fn from(b: Balance) -> Self { - Self { - total: b.total().to_sat(), - confirmed: b.confirmed.to_sat(), - trusted_pending: b.trusted_pending.to_sat(), - untrusted_pending: b.untrusted_pending.to_sat(), - immature: b.immature.to_sat(), - } - } -} From 497d7f31f76161b06113dabca9193126e2a1f2a8 Mon Sep 17 00:00:00 2001 From: Vihiga Tyonum Date: Mon, 30 Nov 2026 19:13:51 +0100 Subject: [PATCH 2/3] fix(payjoin,dns): print JSON objects instead of JSON inside a message string receive_payjoin, send_payjoin, resume_payjoin, payjoin_history and resolve_dns_recipient serialized their result to a string and wrapped it in {"message": ...}, so consumers had to parse JSON twice. PayjoinManager now returns domain values (Txid, ResumeOutcome, Vec) and the handlers build the JSON. resolve_dns_recipient leaves out description, min_amount and max_amount when they are not set. --- src/handlers/dns/dns_payment_instructions.rs | 26 -------- src/handlers/dns/mod.rs | 28 +++++++- src/handlers/online.rs | 51 ++++++++++++--- src/handlers/payjoin/db.rs | 25 ++++--- src/handlers/payjoin/mod.rs | 69 ++++++++++---------- 5 files changed, 119 insertions(+), 80 deletions(-) diff --git a/src/handlers/dns/dns_payment_instructions.rs b/src/handlers/dns/dns_payment_instructions.rs index fc7f616f..607d1186 100644 --- a/src/handlers/dns/dns_payment_instructions.rs +++ b/src/handlers/dns/dns_payment_instructions.rs @@ -18,32 +18,6 @@ pub struct ResolvedPaymentInfo { pub notes: String, } -impl ResolvedPaymentInfo { - pub fn display(&self) -> Result { - let methods: Vec = 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, diff --git a/src/handlers/dns/mod.rs b/src/handlers/dns/mod.rs index 2e3309ca..1d1f7b5c 100644 --- a/src/handlers/dns/mod.rs +++ b/src/handlers/dns/mod.rs @@ -11,6 +11,7 @@ use crate::utils::{ }; use bdk_wallet::KeychainKind; use bdk_wallet::bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, Sequence, script::PushBytesBuf}; +use bitcoin_payment_instructions::PaymentMethod; use clap::Parser; use serde_json::{Value, json}; use std::collections::BTreeMap; @@ -30,7 +31,32 @@ impl AsyncAppCommand> for ResolveDnsRecipientCommand { let resolved = resolve_dns_recipient(&self.hrn, ctx.network, &self.resolver) .await .map_err(|e| Error::Generic(format!("{:?}", e)))?; - Ok(json!({ "message": resolved.display()? })) + let payment_methods: Vec = resolved + .payment_methods + .iter() + .map(|method| match method { + 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(cashu) => format!("Cashu payment ({cashu})"), + }) + .collect(); + + let mut output = json!({ + "hrn": resolved.hrn, + "payment_methods": payment_methods, + "notes": resolved.notes, + }); + if let Some(description) = resolved.description { + output["description"] = json!(description); + } + if let Some(min_amount) = resolved.min_amount { + output["min_amount"] = json!(min_amount.to_sat()); + } + if let Some(max_amount) = resolved.max_amount { + output["max_amount"] = json!(max_amount.to_sat()); + } + Ok(output) } } diff --git a/src/handlers/online.rs b/src/handlers/online.rs index 7e11d84c..816ce43d 100644 --- a/src/handlers/online.rs +++ b/src/handlers/online.rs @@ -27,7 +27,10 @@ use crate::utils::print_wallet_events; use { crate::commands::OnlineWalletSubCommand, crate::error::BDKCliError as Error, - crate::handlers::{AppContext, AsyncAppCommand, OnlineOperations, payjoin::PayjoinManager}, + crate::handlers::{ + AppContext, AsyncAppCommand, OnlineOperations, + payjoin::{PayjoinManager, ResumeOutcome}, + }, crate::utils::{is_final, output::FormatOutput}, bdk_wallet::bitcoin::{ Psbt, Transaction, Txid, base64::Engine, base64::prelude::BASE64_STANDARD, @@ -455,7 +458,7 @@ impl AsyncAppCommand>> for ReceivePayjoinCommand let client = ctx.state.client; let mut payjoin_manager = PayjoinManager::new(wallet, Some(datadir), &wallet_name)?; - let result = payjoin_manager + payjoin_manager .receive_payjoin( self.amount, self.directory.clone(), @@ -465,7 +468,7 @@ impl AsyncAppCommand>> for ReceivePayjoinCommand ) .await?; - Ok(json!({ "message": result })) + Ok(json!({})) } } @@ -502,7 +505,7 @@ impl AsyncAppCommand>> for SendPayjoinCommand { let client = ctx.state.client; let mut payjoin_manager = PayjoinManager::new(wallet, Some(datadir), &wallet_name)?; - let result = payjoin_manager + let txid = payjoin_manager .send_payjoin( self.uri.clone(), self.fee_rate, @@ -511,7 +514,7 @@ impl AsyncAppCommand>> for SendPayjoinCommand { ) .await?; - Ok(json!({ "message": result })) + Ok(json!({ "txid": txid.to_string() })) } } @@ -542,7 +545,7 @@ impl AsyncAppCommand>> for ResumePayjoinCommand let client = ctx.state.client; let mut payjoin_manager = PayjoinManager::new(wallet, Some(datadir), &wallet_name)?; - let result = payjoin_manager + let outcome = payjoin_manager .resume_payjoins( self.directory.clone(), self.ohttp_relay.clone(), @@ -551,7 +554,24 @@ impl AsyncAppCommand>> for ResumePayjoinCommand ) .await?; - Ok(json!({ "message": result })) + let output = match outcome { + ResumeOutcome::NoSessionWithId(session_id) => json!({ + "message": format!("No active session found for session_id {session_id}."), + }), + ResumeOutcome::NoSessions => json!({ "message": "No sessions to resume." }), + ResumeOutcome::Resumed { + total, + completed, + timed_out, + failed, + } => json!({ + "message": format!("Resumed polling for {total} session(s)."), + "outcome": format!( + "Completed: {completed}, timed out: {timed_out}, failed: {failed}." + ), + }), + }; + Ok(output) } } @@ -569,8 +589,19 @@ impl AsyncAppCommand>> for PayjoinHistoryCommand let wallet_name = ctx.state.wallet_name.clone(); let datadir = ctx.datadir.clone(); - let result = PayjoinManager::history(Some(datadir), &wallet_name)?; - - Ok(json!({ "message": result })) + let sessions: Vec = PayjoinManager::history(Some(datadir), &wallet_name)? + .into_iter() + .map(|row| { + // `completed_at` stays `null` for active sessions so every row has the same keys. + json!({ + "id": row.id, + "role": row.role, + "status": row.status, + "completed_at": row.completed_at, + }) + }) + .collect(); + + Ok(json!({ "sessions": sessions })) } } diff --git a/src/handlers/payjoin/db.rs b/src/handlers/payjoin/db.rs index f0e57bb1..59fd9635 100644 --- a/src/handlers/payjoin/db.rs +++ b/src/handlers/payjoin/db.rs @@ -813,17 +813,22 @@ mod tests { .get_inactive_recv_session_ids() .expect("inactive receiver ids should load"); - let table = + let rows = crate::handlers::payjoin::PayjoinManager::history(Some(datadir.clone()), wallet_name) - .expect("history should render"); - - assert!(table.contains("Sender")); - assert!(table.contains("Receiver")); - assert!(table.contains(&active_send_ids[0].to_string())); - assert!(table.contains(&active_recv_ids[0].to_string())); - assert!(table.contains(&inactive_send_ids[0].0.to_string())); - assert!(table.contains(&inactive_recv_ids[0].0.to_string())); - assert!(table.contains("\"completed_at\": null")); + .expect("history should load"); + // Send and receive sessions are numbered separately, so match on role and id. + let completed_at = |role: &str, id: String| { + rows.iter() + .find(|row| row.role == role && row.id == id) + .unwrap_or_else(|| panic!("{role} session {id} should be listed")) + .completed_at + .clone() + }; + + assert!(completed_at("Sender", active_send_ids[0].to_string()).is_none()); + assert!(completed_at("Receiver", active_recv_ids[0].to_string()).is_none()); + assert!(completed_at("Sender", inactive_send_ids[0].0.to_string()).is_some()); + assert!(completed_at("Receiver", inactive_recv_ids[0].0.to_string()).is_some()); drop(active_sender); drop(active_receiver); diff --git a/src/handlers/payjoin/mod.rs b/src/handlers/payjoin/mod.rs index 43516214..42a6eb95 100644 --- a/src/handlers/payjoin/mod.rs +++ b/src/handlers/payjoin/mod.rs @@ -20,8 +20,6 @@ use payjoin::send::v2::{ replay_event_log as replay_sender_event_log, }; use payjoin::{HpkePublicKey, ImplementationError, UriExt}; -use serde::Serialize; -use serde_json::{json, to_string_pretty}; use std::{path::PathBuf, sync::Arc}; use crate::handlers::payjoin::db::{ReceiverPersister, SenderPersister, open_payjoin_db}; @@ -92,17 +90,28 @@ impl StatusText for ReceiveSession { } } -#[derive(Serialize)] -struct SessionHistory<'a> { - sessions: Vec<&'a SessionHistoryRow>, +/// One payjoin session as listed by [`PayjoinManager::history`]. +pub(crate) struct SessionHistoryRow { + pub id: String, + pub role: &'static str, + pub status: String, + /// When the session completed; `None` while it is still active. + pub completed_at: Option, } -#[derive(Serialize)] -struct SessionHistoryRow { - id: String, - role: &'static str, - status: String, - completed_at: Option, +/// What [`PayjoinManager::resume_payjoins`] did. +pub(crate) enum ResumeOutcome { + /// `--session_id` was given but matches no active session. + NoSessionWithId(i64), + /// There were no active sessions to resume. + NoSessions, + /// Every active session was polled once. + Resumed { + total: usize, + completed: usize, + timed_out: usize, + failed: usize, + }, } impl<'a> PayjoinManager<'a> { @@ -128,7 +137,7 @@ impl<'a> PayjoinManager<'a> { max_fee_rate: Option, ohttp_relays: Vec, blockchain_client: &BlockchainClient, - ) -> Result { + ) -> Result<(), Error> { let address = self .wallet .next_unused_address(bdk_wallet::KeychainKind::External); @@ -172,7 +181,7 @@ impl<'a> PayjoinManager<'a> { ) .await?; - Ok(to_string_pretty(&json!({}))?) + Ok(()) } pub async fn send_payjoin( @@ -181,7 +190,7 @@ impl<'a> PayjoinManager<'a> { fee_rate: FeeRate, ohttp_relays: Vec, blockchain_client: &BlockchainClient, - ) -> Result { + ) -> Result { let uri = payjoin::Uri::try_from(uri) .map_err(|e| Error::Generic(format!("Failed parsing to Payjoin URI: {}", e)))?; let uri = uri.require_network(self.wallet.network()).map_err(|e| { @@ -287,7 +296,7 @@ impl<'a> PayjoinManager<'a> { } }; - Ok(to_string_pretty(&json!({ "txid": txid }))?) + Ok(txid) } async fn proceed_receiver_session( @@ -854,7 +863,7 @@ impl<'a> PayjoinManager<'a> { ohttp_relays: Vec, session_id: Option, blockchain_client: &BlockchainClient, - ) -> Result { + ) -> Result { let db = self.db.clone(); let mut recv_session_ids = db.get_recv_session_ids()?; let mut send_session_ids = db.get_send_session_ids()?; @@ -864,16 +873,12 @@ impl<'a> PayjoinManager<'a> { send_session_ids.retain(|id| id.as_i64() == session_id); if recv_session_ids.is_empty() && send_session_ids.is_empty() { - return Ok(serde_json::to_string_pretty(&json!({ - "message": format!("No active session found for session_id {}.", session_id) - }))?); + return Ok(ResumeOutcome::NoSessionWithId(session_id)); } } if recv_session_ids.is_empty() && send_session_ids.is_empty() { - return Ok(serde_json::to_string_pretty(&json!({ - "message": "No sessions to resume." - }))?); + return Ok(ResumeOutcome::NoSessions); } let ohttp_relays: Vec = ohttp_relays @@ -960,20 +965,19 @@ impl<'a> PayjoinManager<'a> { } } - Ok(serde_json::to_string_pretty(&json!({ - "message": format!("Resumed polling for {} session(s).", total_sessions), - "outcome": format!( - "Completed: {}, timed out: {}, failed: {}.", - completed, timed_out, failed - ) - }))?) + Ok(ResumeOutcome::Resumed { + total: total_sessions, + completed, + timed_out, + failed, + }) } /// Show payjoin session history pub fn history( datadir: Option, wallet_name: &str, - ) -> Result { + ) -> Result, Error> { let db = open_payjoin_db(datadir, wallet_name)?; let mut send_rows: Vec = Vec::new(); let mut recv_rows: Vec = Vec::new(); @@ -1056,8 +1060,7 @@ impl<'a> PayjoinManager<'a> { }); } - let sessions: Vec<&SessionHistoryRow> = send_rows.iter().chain(recv_rows.iter()).collect(); - - Ok(to_string_pretty(&SessionHistory { sessions })?) + send_rows.extend(recv_rows); + Ok(send_rows) } } From 537fbb914f3723dca8c1605c0df91f1320a5107e Mon Sep 17 00:00:00 2001 From: Vihiga Tyonum Date: Tue, 1 Dec 2026 12:08:54 +0100 Subject: [PATCH 3/3] refactor(key): move derive_master_key_from_mnemonic to utils It returns domain values (Xpriv, Fingerprint) and is not tied to a command, so it belongs with the other helpers in src/utils, next to is_mnemonic. --- Cargo.lock | 1 + Cargo.toml | 2 +- NEW_FEATURE.md | 5 ++--- src/handlers/config.rs | 22 ++++++++++------------ src/handlers/key.rs | 24 ++++-------------------- src/handlers/offline.rs | 2 +- src/utils/common.rs | 23 +++++++++++++++++++++-- 7 files changed, 40 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1bc7186a..203206f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3885,6 +3885,7 @@ version = "1.0.150" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" dependencies = [ + "indexmap", "itoa", "memchr", "serde", diff --git a/Cargo.toml b/Cargo.toml index 827d0f1f..f1b7fdfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/NEW_FEATURE.md b/NEW_FEATURE.md index b2c78901..ac9c2a9a 100644 --- a/NEW_FEATURE.md +++ b/NEW_FEATURE.md @@ -56,7 +56,7 @@ pub struct WalletDetailsCommand { 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!`. +- `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 @@ -70,13 +70,12 @@ use crate::error::BDKCliError as Error; use serde_json::{Value, json}; impl AppCommand>> for WalletDetailsCommand { - // Implement the execute function fn execute(&self, context: &mut AppContext>) -> Result { // Access the loaded wallet via the context state let wallet = &context.state.wallet; - let mut output = json!({ + let mut output = json!({ "network": wallet.network(), "fingerprint": wallet.fingerprint().to_string(), }); diff --git a/src/handlers/config.rs b/src/handlers/config.rs index 4ed38d3e..bb9e2f1c 100644 --- a/src/handlers/config.rs +++ b/src/handlers/config.rs @@ -69,8 +69,7 @@ impl AppCommand> 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." ))); }; @@ -78,8 +77,8 @@ impl AppCommand> for SaveConfigCommand { && 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 ))); } @@ -157,11 +156,10 @@ impl AppCommand> for SaveConfigCommand { .map_err(|error| Error::Generic(error.to_string()))?; Ok(json!({ - "message": format!( - "Wallet '{}' initialized successfully in {:?}", - wallet_name, - ctx.datadir.join("config.toml") - ), + "message": format!( + "Wallet '{wallet_name}' initialized successfully in {:?}", + ctx.datadir.join("config.toml") + ), })) } } @@ -230,9 +228,9 @@ impl AppCommand> for DeleteWalletConfigCommand { Ok(json!({ "message": format!( - "Wallet configuration '{}' deleted successfully", - self.wallet_name - ), + "Wallet configuration '{}' deleted successfully", + self.wallet_name + ), })) } } diff --git a/src/handlers/key.rs b/src/handlers/key.rs index 6a25a40f..a863047d 100644 --- a/src/handlers/key.rs +++ b/src/handlers/key.rs @@ -1,12 +1,12 @@ use crate::commands::KeySubCommand; use crate::error::BDKCliError as Error; use crate::handlers::{AppCommand, AppContext, Init}; -use crate::utils::output::FormatOutput; +use crate::utils::{derive_master_key_from_mnemonic, output::FormatOutput}; use bdk_wallet::bip39::{Language, Mnemonic}; -use bdk_wallet::bitcoin::bip32::{DerivationPath, Fingerprint, KeySource, Xpriv}; -use bdk_wallet::bitcoin::{Network, key::Secp256k1}; +use bdk_wallet::bitcoin::bip32::{DerivationPath, KeySource, Xpriv}; +use bdk_wallet::bitcoin::key::Secp256k1; use bdk_wallet::keys::{ - DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, bip39::WordCount, + DerivableKey, DescriptorKey, GeneratableKey, GeneratedKey, bip39::WordCount, }; use bdk_wallet::miniscript::{self, Segwitv0}; use clap::{Parser, ValueEnum}; @@ -145,19 +145,3 @@ impl AppCommand> for RestoreKeyCommand { })) } } - -/// Derives the master key from a mnemonic and optional passphrase. -fn derive_master_key_from_mnemonic( - mnemonic: &Mnemonic, - password: Option, - network: Network, -) -> Result<(Xpriv, Fingerprint), Error> { - let secp = Secp256k1::new(); - let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?; - let xprv = xkey - .into_xprv(network.into()) - .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?; - let fingerprint = xprv.fingerprint(&secp); - - Ok((xprv, fingerprint)) -} diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 31aee423..15e1210d 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -155,7 +155,7 @@ impl AppCommand>> for TransactionsCommand { .map(|tx| { json!({ "txid": tx.tx_node.txid.to_string(), - "is_coinbase": tx.tx_node.is_coinbase(), + "is_coinbase": tx.tx_node.is_coinbase(), "wtxid": tx.tx_node.compute_wtxid().to_string(), "version": tx.tx_node.version, "is_rbf": tx.tx_node.is_explicitly_rbf(), diff --git a/src/utils/common.rs b/src/utils/common.rs index 1e3cbbe7..21514f0b 100644 --- a/src/utils/common.rs +++ b/src/utils/common.rs @@ -14,12 +14,15 @@ use bdk_wallet::Wallet; feature = "rpc" ))] use bdk_wallet::WalletEvent; -use bdk_wallet::bitcoin::base64::Engine; -use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD; +use bdk_wallet::bip39::Mnemonic; +use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD}; +use bdk_wallet::bitcoin::bip32::{Fingerprint, Xpriv}; +use bdk_wallet::bitcoin::key::Secp256k1; use bdk_wallet::bitcoin::script::PushBytesBuf; use bdk_wallet::bitcoin::{ Address, FeeRate, Network, OutPoint, Psbt, ScriptBuf, Transaction, Weight, }; +use bdk_wallet::keys::{DerivableKey, ExtendedKey}; use std::{ path::{Path, PathBuf}, str::FromStr, @@ -227,6 +230,22 @@ pub fn is_mnemonic(s: &str) -> bool { (12..=24).contains(&word_count) && s.chars().all(|c| c.is_alphanumeric() || c.is_whitespace()) } +/// Derives the master key from a mnemonic and optional passphrase. +pub fn derive_master_key_from_mnemonic( + mnemonic: &Mnemonic, + password: Option, + network: Network, +) -> Result<(Xpriv, Fingerprint), Error> { + let secp = Secp256k1::new(); + let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?; + let xprv = xkey + .into_xprv(network.into()) + .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?; + let fingerprint = xprv.fingerprint(&secp); + + Ok((xprv, fingerprint)) +} + #[cfg(feature = "cbf")] pub async fn trace_logger( mut info_subcriber: Receiver,