- 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]
__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):
```
-##### 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!`.
##### Step 3: Implement the AppCommand Trait
```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)
}
}
```
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 {
}
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!");
}
.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")
+ ),
+ }))
}
}
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)?)
}
}
}
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())),
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
+ ),
+ }))
}
}
use crate::handlers::Init;
-use crate::utils::types::DescriptorResult;
use crate::{
error::BDKCliError as Error,
handlers::{AppCommand, AppContext},
},
};
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)
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)
}
}
#[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)
}
}
#[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() }))
}
}
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,
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.
}
impl AsyncAppCommand<AppContext<Init>> for ResolveDnsRecipientCommand {
- type Output = StatusResult;
-
- async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
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()? }))
}
}
}
impl AsyncAppCommand<AppContext<OfflineOperations<'_>>> for CreateDnsTxCommand {
- type Output = PsbtResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OfflineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ 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 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 }))
}
}
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;
}
impl AsyncAppCommand<AppContext<Init>> for HwiCommand {
- type Output = serde_json::Value;
-
- async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let network = ctx.network;
// Device-only commands operate without a wallet policy.
let hwi_wallet = HwiWallet::default();
&self,
ctx: &mut AppContext<OfflineOperations<'_>>,
wallet_name: &str,
- ) -> Result<serde_json::Value, Error> {
+ ) -> Result<Value, Error> {
let network = ctx.network;
let target_fp = self.fingerprint.as_deref();
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<Init>) -> Result<(), Error> {
}
impl AppCommand<AppContext<Init>> for GenerateKeyCommand {
- type Output = KeyResult;
-
- fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
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(),
+ }))
}
}
}
impl AppCommand<AppContext<Init>> for DeriveKeyCommand {
- type Output = KeyResult;
-
- fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
let secp = Secp256k1::new();
let derived_xprv = &self.xprv.derive_priv(&secp, &self.path)?;
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(),
}
impl AppCommand<AppContext<Init>> for RestoreKeyCommand {
- type Output = KeyResult;
-
- fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<Init>) -> Result<Value, Error> {
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<String>,
network: Network,
-) -> Result<KeyResult, Error> {
+) -> Result<(Xpriv, Fingerprint), Error> {
let secp = Secp256k1::new();
let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
let xprv = xkey
.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))
}
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;
}
pub trait AppCommand<C> {
- type Output: FormatOutput;
-
- fn execute(&self, ctx: &mut C) -> Result<Self::Output, Error>;
+ fn execute(&self, ctx: &mut C) -> Result<Value, Error>;
}
#[cfg(any(
feature = "hwi"
))]
pub trait AsyncAppCommand<C> {
- type Output: FormatOutput;
-
- async fn execute(&self, ctx: &mut C) -> Result<Self::Output, Error>;
+ async fn execute(&self, ctx: &mut C) -> Result<Value, Error>;
}
#[cfg(test)]
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 {
#[cfg(feature = "message_signer")]
use {
crate::utils::parse_signature_format,
- crate::utils::types::MessageResult,
bdk_message_signer::{MessageProof, MessageSigner},
};
pub struct NewAddressCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for NewAddressCommand {
- type Output = AddressResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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,
+ }))
}
}
pub struct UnusedAddressCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for UnusedAddressCommand {
- type Output = AddressResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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,
+ }))
}
}
pub struct UnspentCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for UnspentCommand {
- type Output = ListResult<UnspentDetails>;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let outputs: Vec<_> = wallet.list_unspent().collect();
- let utxos = outputs
+ let utxos: Vec<Value> = 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 }))
}
}
pub struct TransactionsCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for TransactionsCommand {
- type Output = ListResult<TransactionDetails>;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let transactions = &mut ctx.state.wallet.transactions();
- let txns: Vec<TransactionDetails> = transactions
+ let txns: Vec<Value> = transactions
.map(|tx| {
- let total_value = tx
- .tx_node
- .output
- .iter()
- .map(|output| output.value.to_sat())
- .sum::<u64>();
-
- 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 }))
}
}
pub struct BalanceCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for BalanceCommand {
- type Output = BalanceResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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)]
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateTxCommand {
- type Output = PsbtResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let mut tx_builder = ctx.state.wallet.build_tx();
if self.send_all {
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 }))
}
}
#[cfg(feature = "silent-payments")]
impl AppCommand<AppContext<OfflineOperations<'_>>> for CreateSpTxCommand {
- type Output = RawPsbt;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let mut tx_builder = ctx.state.wallet.build_tx();
let sp_recipients: Vec<SilentPaymentCode> = self
let raw_tx = psbt.extract_tx()?;
- Ok(RawPsbt::new(&raw_tx))
+ Ok(json!({ "raw_tx": serialize_hex(&raw_tx) }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for BumpFeeCommand {
- type Output = PsbtResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let mut tx_builder = wallet.build_fee_bump(self.txid)?;
check_standard_weight(max_signed_weight(wallet, &psbt)?)?;
- Ok(PsbtResult::new(&psbt, Some(false)))
+ Ok(json!({ "psbt": psbt.to_string(), "is_finalized": false }))
}
}
pub struct PoliciesCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for PoliciesCommand {
- type Output = KeychainPair<serde_json::Value>;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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 }))
}
}
pub struct PublicDescriptorCommand;
impl AppCommand<AppContext<OfflineOperations<'_>>> for PublicDescriptorCommand {
- type Output = KeychainPair<String>;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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(),
+ }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for SignCommand {
- type Output = PsbtResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
let mut psbt = Psbt::deserialize(&psbt_bytes)?;
..Default::default()
};
let finalized = wallet.sign(&mut psbt, signopt)?;
- Ok(PsbtResult::new(&psbt, Some(finalized)))
+ Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for ExtractPsbtCommand {
- type Output = RawPsbt;
-
- fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
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) }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for FinalizePsbtCommand {
- type Output = PsbtResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let psbt_bytes = BASE64_STANDARD.decode(&self.psbt)?;
let mut psbt = Psbt::deserialize(&psbt_bytes)?;
let finalized = wallet.finalize_psbt(&mut psbt, signopt)?;
- Ok(PsbtResult::new(&psbt, Some(finalized)))
+ Ok(json!({ "psbt": psbt.to_string(), "is_finalized": finalized }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for CombinePsbtCommand {
- type Output = PsbtResult;
-
- fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, _ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let mut psbts = self
.psbt
.iter()
Ok(acc)
})?;
- Ok(PsbtResult::new(&final_psbt, Some(false)))
+ Ok(json!({ "psbt": final_psbt.to_string(), "is_finalized": false }))
}
}
#[cfg(feature = "message_signer")]
impl AppCommand<AppContext<OfflineOperations<'_>>> for SignMessageCommand {
- type Output = MessageResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let address: Address = parse_address(&self.address)?;
let signature_format = parse_signature_format(&self.signature_type)?;
self.utxos.clone(),
)?;
- Ok(MessageResult {
- proof: Some(proof.to_base64()),
- ..Default::default()
- })
+ Ok(json!({ "proof": proof.to_base64() }))
}
}
#[cfg(feature = "message_signer")]
impl AppCommand<AppContext<OfflineOperations<'_>>> for VerifyMessageCommand {
- type Output = MessageResult;
-
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &ctx.state.wallet;
let address: Address = parse_address(&self.address)?;
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)
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for LockUtxoCommand {
- type Output = ListResult<String>;
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
for out_point in &self.utxos {
if wallet.get_utxo(*out_point).is_none() {
}
wallet.lock_outpoint(*out_point);
}
- let locked = wallet
+ let locked: Vec<String> = wallet
.list_locked_outpoints()
.map(|o| o.to_string())
.collect();
- Ok(ListResult::new(locked))
+ Ok(json!({ "count": locked.len(), "items": locked }))
}
}
}
impl AppCommand<AppContext<OfflineOperations<'_>>> for UnlockUtxoCommand {
- type Output = ListResult<String>;
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
for out_point in &self.utxos {
wallet.unlock_outpoint(*out_point);
}
- let locked = wallet
+ let locked: Vec<String> = wallet
.list_locked_outpoints()
.map(|o| o.to_string())
.collect();
- Ok(ListResult::new(locked))
+ Ok(json!({ "count": locked.len(), "items": locked }))
}
}
pub struct LockedUtxosCommand {}
impl AppCommand<AppContext<OfflineOperations<'_>>> for LockedUtxosCommand {
- type Output = ListResult<String>;
- fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Self::Output, Error> {
+ fn execute(&self, ctx: &mut AppContext<OfflineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
- let locked = wallet
+ let locked: Vec<String> = wallet
.list_locked_outpoints()
.map(|o| o.to_string())
.collect();
- Ok(ListResult::new(locked))
+ Ok(json!({ "count": locked.len(), "items": locked }))
}
}
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",
impl OnlineWalletSubCommand {
pub async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> 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())
}
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for FullScanCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let client = ctx.state.client;
sync_kyoto_client(wallet, client).await?;
}
}
- Ok(StatusResult {
- message: "Full scan completed successfully.".to_string(),
- })
+ Ok(json!({ "message": "Full scan completed successfully." }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SyncCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let wallet = &mut ctx.state.wallet;
let client = ctx.state.client;
#[cfg(any(feature = "electrum", feature = "esplora"))]
#[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." }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for BroadcastCommand {
- type Output = TransactionResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let client = ctx.state.client;
let tx = match (&self.psbt, &self.tx) {
let txid: Txid = client.broadcast(tx).await?;
- Ok(TransactionResult {
- txid: txid.to_string(),
- })
+ Ok(json!({ "txid": txid.to_string() }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ReceivePayjoinCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let wallet_name = ctx.state.wallet_name.clone();
let datadir = ctx.datadir.clone();
let wallet = &mut ctx.state.wallet;
)
.await?;
- Ok(StatusResult { message: result })
+ Ok(json!({ "message": result }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for SendPayjoinCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let wallet_name = ctx.state.wallet_name.clone();
let datadir = ctx.datadir.clone();
let wallet = &mut ctx.state.wallet;
)
.await?;
- Ok(StatusResult { message: result })
+ Ok(json!({ "message": result }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for ResumePayjoinCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
let wallet_name = ctx.state.wallet_name.clone();
let datadir = ctx.datadir.clone();
let wallet = &mut ctx.state.wallet;
)
.await?;
- Ok(StatusResult { message: result })
+ Ok(json!({ "message": result }))
}
}
feature = "rpc"
))]
impl AsyncAppCommand<AppContext<OnlineOperations<'_>>> for PayjoinHistoryCommand {
- type Output = StatusResult;
-
- async fn execute(
- &self,
- ctx: &mut AppContext<OnlineOperations<'_>>,
- ) -> Result<Self::Output, Error> {
+ async fn execute(&self, ctx: &mut AppContext<OnlineOperations<'_>>) -> Result<Value, Error> {
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 }))
}
}
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<DescriptorPublicKey>,
+ pub internal: Descriptor<DescriptorPublicKey>,
+ /// 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<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
let is_private = key.starts_with("xprv") || key.starts_with("tprv");
if is_private {
desc_type: &str,
key: &str,
network: NetworkKind,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
use bdk_wallet::template::{Bip44, Bip49, Bip84, Bip86};
let secp = Secp256k1::new();
}
};
- 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,
})
}
desc_type: &str,
key: &str,
derivation_path: &DerivationPath,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
let xpub: Xpub = key.parse()?;
let fingerprint = xpub.fingerprint();
- let build_descriptor = |branch: &str| -> Result<String, Error> {
+ let build_descriptor = |branch: &str| -> Result<Descriptor<DescriptorPublicKey>, Error> {
let branch_path = DerivationPath::from_str(branch)?;
let desc_xpub = DescriptorXKey {
origin: Some((fingerprint, derivation_path.clone())),
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,
})
}
pub fn generate_descriptor_with_mnemonic(
network: NetworkKind,
desc_type: &str,
-) -> Result<DescriptorResult, Error> {
+) -> Result<(Mnemonic, KeychainDescriptors), Error> {
let mnemonic: GeneratedKey<Mnemonic, Segwitv0> =
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
mnemonic_str: &str,
network: NetworkKind,
desc_type: &str,
-) -> Result<DescriptorResult, Error> {
+) -> Result<KeychainDescriptors, Error> {
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`.
#[cfg(feature = "hwi")]
pub mod hwi;
pub mod runtime;
-pub mod types;
}
impl<T: Serialize> FormatOutput for T {}
-
-/// A generic wrapper for commands that return a list of items.
-#[derive(Serialize)]
-pub struct ListResult<T> {
- pub count: usize,
- pub items: Vec<T>,
-}
-
-impl<T> ListResult<T> {
- pub fn new(items: Vec<T>) -> Self {
- Self {
- count: items.len(),
- items,
- }
- }
-}
+++ /dev/null
-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<AddressInfo> 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<bool>,
-}
-
-impl PsbtResult {
- pub fn new(psbt: &Psbt, finalized: Option<bool>) -> 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<T> {
- 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<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub valid: Option<bool>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub proven_amount: Option<u64>,
-}
-
-#[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<String, WalletConfigInner>);
-
-/// return type
-#[derive(Serialize)]
-pub struct DescriptorResult {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub descriptor: Option<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub multipath_descriptor: Option<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub public_descriptors: Option<KeychainPair<String>>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub private_descriptors: Option<KeychainPair<String>>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub mnemonic: Option<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub fingerprint: Option<String>,
-
- /// Randomness factor `r` used to derive the taproot unspendable internal key (H + rG).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub r: Option<String>,
-}
-
-#[derive(Serialize)]
-pub struct KeyResult {
- pub xprv: String,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub xpub: Option<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub mnemonic: Option<String>,
-
- #[serde(skip_serializing_if = "Option::is_none")]
- pub fingerprint: Option<String>,
-}
-
-/// 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<Balance> 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(),
- }
- }
-}