From 68c24a434f4f0a79152d20b0288efab29456fbeb Mon Sep 17 00:00:00 2001 From: musab1258 Date: Thu, 29 Oct 2026 09:36:50 +0100 Subject: [PATCH 1/4] feat(labels): add the label command --- Cargo.lock | 29 +++- Cargo.toml | 2 + src/commands.rs | 4 +- src/error.rs | 3 + src/handlers/mod.rs | 13 +- src/handlers/offline.rs | 103 +++++++++++- src/handlers/repl.rs | 13 +- src/main.rs | 8 +- src/utils/common.rs | 3 +- src/utils/labels.rs | 210 ++++++++++++++++++++++++ src/utils/mod.rs | 1 + src/utils/types.rs | 12 ++ tests/integration/offline.rs | 300 +++++++++++++++++++++++++++++++++++ 13 files changed, 680 insertions(+), 21 deletions(-) create mode 100644 src/utils/labels.rs diff --git a/Cargo.lock b/Cargo.lock index 29bd4886..447d5aca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -323,6 +323,7 @@ version = "4.0.0" dependencies = [ "assert_cmd", "async-hwi", + "bdk-labels", "bdk_bitcoind_rpc", "bdk_electrum", "bdk_esplora", @@ -354,6 +355,20 @@ dependencies = [ "url", ] +[[package]] +name = "bdk-labels" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d43dd04251494bd277de914aa2dc1e44fd865e122cd0790a2565cec0440ab0b" +dependencies = [ + "bdk_wallet", + "bip329", + "bitcoin", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "bdk_bitcoind_rpc" version = "0.22.0" @@ -519,6 +534,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "bip329" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "689260fce0f6e366877a624be4c87518e80f99951c421ae80c3be6523a51bc9d" +dependencies = [ + "bitcoin", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "bip39" version = "2.2.2" @@ -4207,7 +4234,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.4", "windows-sys 0.61.2", diff --git a/Cargo.toml b/Cargo.toml index 9319864d..49d80c3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,9 @@ reqwest = { version = "0.13.2", default-features = false, features = ["rustls"], url = { version = "2.5.8", optional = true } bdk_message_signer = { version = "0.2.0", optional = true } bitcoin-payment-instructions = { version = "0.7.0", optional = true} + async-hwi = { version = "0.0.35", features = ["specter", "coldcard", "ledger", "jade", "bitbox", "service"], optional = true} +bdk-labels = "0.2.1" [features] default = ["repl", "sqlite"] diff --git a/src/commands.rs b/src/commands.rs index 2190f5d9..239020dc 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -21,7 +21,7 @@ use crate::handlers::{ key::{DeriveKeyCommand, GenerateKeyCommand, RestoreKeyCommand}, offline::{ BalanceCommand, BumpFeeCommand, CombinePsbtCommand, CreateTxCommand, ExtractPsbtCommand, - FinalizePsbtCommand, LockUtxoCommand, LockedUtxosCommand, NewAddressCommand, + FinalizePsbtCommand, LabelCommand, LockUtxoCommand, LockedUtxosCommand, NewAddressCommand, PoliciesCommand, PublicDescriptorCommand, SignCommand, TransactionsCommand, UnlockUtxoCommand, UnspentCommand, UnusedAddressCommand, }, @@ -489,6 +489,8 @@ pub enum OfflineWalletSubCommand { UnlockUtxo(UnlockUtxoCommand), /// List currently locked UTXOs. LockedUtxos(LockedUtxosCommand), + /// Attach a BIP-329 label to a transaction, a UTXO or an address. + Label(LabelCommand), /// Creates a new unsigned transaction from DNS payment instructions. #[cfg(feature = "dns_payment")] CreateDnsTx(CreateDnsTxCommand), diff --git a/src/error.rs b/src/error.rs index 76b31fd0..9fcdb947 100644 --- a/src/error.rs +++ b/src/error.rs @@ -49,6 +49,9 @@ pub enum BDKCliError { #[error("Key error: {0}")] KeyError(#[from] bdk_wallet::keys::KeyError), + #[error("Labels error: {0}")] + LabelsError(#[from] bdk_labels::Error), + #[cfg(feature = "hwi")] #[error("Hardware wallet error: {0}")] HwiError(#[from] async_hwi::Error), diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 7d3d7f8c..9b26b86c 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -35,6 +35,7 @@ pub struct Init; /// Requires only a wallet. pub struct OfflineOperations<'a> { pub wallet: &'a mut Wallet, + pub wallet_name: String, } #[cfg(any( @@ -70,11 +71,19 @@ impl AppContext { } impl<'a> AppContext> { - pub fn new_offline_wallet(network: Network, datadir: PathBuf, wallet: &'a mut Wallet) -> Self { + pub fn new_offline_wallet( + network: Network, + datadir: PathBuf, + wallet: &'a mut Wallet, + wallet_name: String, + ) -> Self { Self { network, datadir, - state: OfflineOperations { wallet }, + state: OfflineOperations { + wallet, + wallet_name, + }, } } } diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 15cdd26b..3c0399e7 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -1,19 +1,22 @@ use crate::commands::OfflineWalletSubCommand; use crate::error::BDKCliError as Error; use crate::handlers::{AppCommand, AppContext, OfflineOperations}; +use crate::utils::labels::LabelStore; use crate::utils::output::{FormatOutput, ListResult}; use crate::utils::parse_address; use crate::utils::types::{ - AddressResult, BalanceResult, KeychainPair, PsbtResult, RawPsbt, TransactionDetails, - UnspentDetails, + AddressResult, BalanceResult, KeychainPair, LabelResult, PsbtResult, RawPsbt, + TransactionDetails, UnspentDetails, }; use crate::utils::{parse_fee_rate, parse_outpoint, parse_recipient}; +use bdk_labels::{Bip329, LabelledWallet, OutputTarget}; +use bdk_wallet::bitcoin::address::NetworkUnchecked; use bdk_wallet::bitcoin::base64::Engine; use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD; use bdk_wallet::bitcoin::script::PushBytesBuf; use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, ScriptBuf, Sequence, Txid}; use bdk_wallet::{KeychainKind, SignOptions}; -use clap::Parser; +use clap::{ArgGroup, Parser}; use serde_json::json; use std::collections::BTreeMap; #[cfg(feature = "silent-payments")] @@ -86,6 +89,7 @@ impl OfflineWalletSubCommand { Self::LockedUtxos(locked_utxos) => { locked_utxos.execute(ctx)?.write_out(std::io::stdout()) } + Self::Label(label) => label.execute(ctx)?.write_out(std::io::stdout()), #[cfg(feature = "dns_payment")] Self::CreateDnsTx(_) => Err(Error::Generic( "CreateDnsTx is dispatched asynchronously through main".to_string(), @@ -908,3 +912,96 @@ impl AppCommand>> for LockedUtxosCommand { Ok(ListResult::new(locked)) } } + +#[derive(Parser, Debug, Clone, PartialEq)] +#[command(group( + ArgGroup::new("target") + .required(true) + .multiple(false) + .args(["txid", "utxo", "address"]) +))] +pub struct LabelCommand { + /// Transaction to label. It must be known to the wallet, sync first. + #[arg(long = "txid")] + pub txid: Option, + + /// Wallet UTXO to label, format TXID:VOUT. It must be known to the wallet, sync first. + #[arg(long = "utxo", value_parser = parse_outpoint)] + pub utxo: Option, + + /// Wallet address to label. It must belong to the wallet and match the network. + #[arg(long = "address")] + pub address: Option>, + + /// The label. + #[arg(long = "text", allow_hyphen_values = true)] + pub text: String, +} + +impl AppCommand>> for LabelCommand { + type Output = LabelResult; + + fn execute(&self, ctx: &mut AppContext>) -> Result { + if self.text.trim().is_empty() { + return Err(Error::Generic("The label must not be empty.".to_string())); + } + + let network = ctx.network; + let mut store = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name); + let mut labels = store.load()?; + let mut labelled = LabelledWallet { + wallet: &mut *ctx.state.wallet, + labels: &mut labels, + }; + + let (kind, reference) = match (&self.txid, &self.utxo, &self.address) { + (Some(txid), None, None) => { + labelled + .add_label(*txid, self.text.clone()) + .map_err(unknown_to_wallet)?; + ("tx", txid.to_string()) + } + (None, Some(outpoint), None) => { + labelled + .add_label(OutputTarget(*outpoint), self.text.clone()) + .map_err(unknown_to_wallet)?; + ("output", outpoint.to_string()) + } + (None, None, Some(address)) => { + // `add_label` only checks that the address is the wallet's, not its network. + let address = address.clone().require_network(network).map_err(|_| { + Error::Generic(format!( + "Address {} is not valid on {network}.", + address.assume_checked_ref() + )) + })?; + labelled.add_label(address.clone().into_unchecked(), self.text.clone())?; + ("addr", address.to_string()) + } + _ => { + return Err(Error::Generic( + "Exactly one of --txid, --utxo or --address is required.".to_string(), + )); + } + }; + + labelled.persist(&mut store)?; + + Ok(LabelResult { + kind, + reference, + label: self.text.clone(), + }) + } +} + +/// Explain what to do when a transaction or UTXO to label is unknown to the wallet. +fn unknown_to_wallet(error: bdk_labels::Error) -> Error { + match error { + bdk_labels::Error::Validation(message) => Error::Generic(format!( + "{message}. Transactions and UTXOs can only be labelled once the wallet knows about \ + them, sync the wallet first." + )), + other => Error::LabelsError(other), + } +} diff --git a/src/handlers/repl.rs b/src/handlers/repl.rs index b93916e9..80c0679c 100644 --- a/src/handlers/repl.rs +++ b/src/handlers/repl.rs @@ -33,12 +33,6 @@ pub(crate) async fn respond( client: Option<&BlockchainClient>, line: &str, datadir: std::path::PathBuf, - #[cfg(any( - feature = "electrum", - feature = "esplora", - feature = "rpc", - feature = "cbf" - ))] wallet_name: &str, ) -> Result { let args = shlex::split(line).ok_or("error: Invalid quoting".to_string())?; @@ -54,7 +48,12 @@ pub(crate) async fn respond( let response = match repl_subcommand { ReplSubCommand::Wallet { subcommand } => match subcommand { WalletSubCommand::OfflineWalletSubCommand(cmd) => { - let mut ctx = AppContext::new_offline_wallet(network, datadir, wallet); + let mut ctx = AppContext::new_offline_wallet( + network, + datadir, + wallet, + wallet_name.to_string(), + ); cmd.execute(&mut ctx).map_err(|e| e.to_string())?; Some(()) } diff --git a/src/main.rs b/src/main.rs index 7ed73d46..ce3c17d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -92,6 +92,7 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { runtime.network, runtime.home_dir.clone(), &mut wallet, + runtime.wallet_name.clone(), ); match cmd { @@ -124,6 +125,7 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { runtime.network, runtime.home_dir.clone(), &mut wallet, + runtime.wallet_name.clone(), ); cmd.run(&mut ctx, &wallet_name) @@ -191,12 +193,6 @@ async fn run(cli_opts: CliOpts) -> Result<(), Error> { client.as_ref(), &line, runtime.home_dir.clone(), - #[cfg(any( - feature = "electrum", - feature = "esplora", - feature = "rpc", - feature = "cbf" - ))] &wallet_name, ) .await diff --git a/src/utils/common.rs b/src/utils/common.rs index 7a2d8dba..72761678 100644 --- a/src/utils/common.rs +++ b/src/utils/common.rs @@ -271,7 +271,8 @@ pub fn command_requires_db(command: &OfflineWalletSubCommand) -> bool { | OfflineWalletSubCommand::CreateTx(_) | OfflineWalletSubCommand::LockUtxo(_) | OfflineWalletSubCommand::UnlockUtxo(_) - | OfflineWalletSubCommand::LockedUtxos(_) => true, + | OfflineWalletSubCommand::LockedUtxos(_) + | OfflineWalletSubCommand::Label(_) => true, OfflineWalletSubCommand::Policies(_) | OfflineWalletSubCommand::PublicDescriptor(_) diff --git a/src/utils/labels.rs b/src/utils/labels.rs new file mode 100644 index 00000000..b23a04be --- /dev/null +++ b/src/utils/labels.rs @@ -0,0 +1,210 @@ +//! Storage for BIP-329 wallet labels. +//! +//! Labels live in a BIP-329 JSONL file next to the wallet's database, +//! `//labels.jsonl`. The file is independent of the wallet's +//! sqlite/redb backend, and is only read by commands that use labels, so a bad +//! labels file can never break unrelated commands such as `balance`. + +use crate::error::BDKCliError as Error; +use crate::utils::write_file_content; +use bdk_labels::{LabelChangeset, LabelPersister, MergeStrategy}; +use std::fs::File; +use std::io::{self, BufReader}; +use std::path::{Path, PathBuf}; + +/// Name of the labels file inside the wallet's data directory. +pub(crate) const LABELS_FILE_NAME: &str = "labels.jsonl"; + +/// A wallet's labels file. +#[derive(Debug, Clone)] +pub struct LabelStore { + path: PathBuf, +} + +impl LabelStore { + /// The labels store of `wallet_name`, inside `datadir`. + pub fn new(datadir: &Path, wallet_name: &str) -> Self { + Self { + path: datadir.join(wallet_name).join(LABELS_FILE_NAME), + } + } + + /// Load the labels, an absent file is an empty set of labels. + /// + /// A file that cannot be read or parsed is an error naming the file. + pub fn load(&self) -> Result { + self.read_labels() + .map_err(|e| Error::LabelsError(bdk_labels::Error::Io(e))) + } + + /// An I/O error that names the labels file. + fn io_error(&self, cause: impl std::fmt::Display) -> io::Error { + io::Error::other(format!("{}: {cause}", self.path.display())) + } + + /// Path of the temporary file a write goes through. + fn temp_path(&self) -> PathBuf { + self.path.with_extension("jsonl.tmp") + } +} + +impl LabelPersister for LabelStore { + type Error = io::Error; + + fn read_labels(&self) -> Result { + let file = match File::open(&self.path) { + Ok(file) => file, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(LabelChangeset::new()), + Err(e) => return Err(self.io_error(e)), + }; + + let mut labels = bdk_labels::import(BufReader::new(file)).map_err(|e| self.io_error(e))?; + // `import` stages every line it reads, but these labels are already on disk. + labels.clear_staged(); + + Ok(labels) + } + + /// Merge `changeset` into the file, which is rewritten through a temporary + /// file and a rename, so an interrupted write cannot leave a truncated file. + fn append_changeset(&mut self, changeset: &LabelChangeset) -> Result<(), Self::Error> { + let mut labels = self.read_labels()?; + labels.merge(changeset.clone(), MergeStrategy::Overwrite); + + let mut jsonl = Vec::new(); + bdk_labels::export(&labels, &mut jsonl).map_err(|e| self.io_error(e))?; + let jsonl = String::from_utf8(jsonl).map_err(|e| self.io_error(e))?; + + let temp_path = self.temp_path(); + write_file_content(&temp_path, &jsonl).map_err(|e| self.io_error(e))?; + std::fs::rename(&temp_path, &self.path).map_err(|e| { + let _ = std::fs::remove_file(&temp_path); + self.io_error(e) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + use tempfile::TempDir; + + const TXID_A: &str = "5fe2524f0c46bb12767d1865114031cd631578ac05422a767c0edf23f5c0aeaa"; + const TXID_B: &str = "55d2b85dbf49d78c7070d83f20443e694d90a65498d44bbe84f3c7aa0b55a465"; + + /// A store in a fresh data directory with a wallet directory in it. + fn store() -> (TempDir, LabelStore) { + let datadir = TempDir::new().unwrap(); + std::fs::create_dir(datadir.path().join("wallet")).unwrap(); + let store = LabelStore::new(datadir.path(), "wallet"); + (datadir, store) + } + + /// Labels for the given transactions, all staged. + fn tx_labels(labels: &[(&str, &str)]) -> LabelChangeset { + let jsonl = labels + .iter() + .map(|(txid, label)| format!(r#"{{"type":"tx","ref":"{txid}","label":"{label}"}}"#)) + .collect::>() + .join("\n"); + + bdk_labels::import(Cursor::new(jsonl)).unwrap() + } + + #[test] + fn missing_file_loads_empty() { + let (_datadir, store) = store(); + + let labels = store.load().unwrap(); + + assert!(labels.is_empty()); + assert!(!store.path.exists()); + } + + #[test] + fn corrupt_file_is_an_error_naming_the_file() { + let (_datadir, store) = store(); + std::fs::write(&store.path, "this is not jsonl\n").unwrap(); + + let err = store.load().unwrap_err().to_string(); + + assert!(err.contains(LABELS_FILE_NAME), "unexpected error: {err}"); + } + + #[test] + fn loaded_labels_are_not_staged() { + let (_datadir, mut store) = store(); + store + .append_changeset(&tx_labels(&[(TXID_A, "rent")])) + .unwrap(); + + let labels = store.load().unwrap(); + + assert_eq!(labels.len(), 1); + assert!(!labels.has_staged_changes()); + } + + #[test] + fn appended_changesets_are_merged_with_the_file() { + let (_datadir, mut store) = store(); + + store + .append_changeset(&tx_labels(&[(TXID_A, "rent")])) + .unwrap(); + store + .append_changeset(&tx_labels(&[(TXID_B, "groceries")])) + .unwrap(); + // A later label for the same transaction replaces the earlier one. + store + .append_changeset(&tx_labels(&[(TXID_A, "rent, march")])) + .unwrap(); + + let file = std::fs::read_to_string(&store.path).unwrap(); + assert_eq!(file.lines().count(), 2); + assert!(file.contains("rent, march")); + assert!(!file.contains(r#""label":"rent""#)); + assert!(file.ends_with('\n'), "JSONL lines are newline terminated"); + } + + #[test] + fn no_temporary_file_is_left_behind() { + let (_datadir, mut store) = store(); + + store + .append_changeset(&tx_labels(&[(TXID_A, "rent")])) + .unwrap(); + + assert!(store.path.exists()); + assert!(!store.temp_path().exists()); + } + + #[test] + fn appending_to_a_corrupt_file_fails_and_leaves_it_untouched() { + let (_datadir, mut store) = store(); + std::fs::write(&store.path, "this is not jsonl\n").unwrap(); + + let result = store.append_changeset(&tx_labels(&[(TXID_A, "rent")])); + + assert!(result.is_err()); + assert_eq!( + std::fs::read_to_string(&store.path).unwrap(), + "this is not jsonl\n" + ); + } + + #[cfg(unix)] + #[test] + fn written_file_is_owner_only() { + use std::os::unix::fs::PermissionsExt; + + let (_datadir, mut store) = store(); + + store + .append_changeset(&tx_labels(&[(TXID_A, "rent")])) + .unwrap(); + + let mode = std::fs::metadata(&store.path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 15138df5..71f68fc4 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,5 +1,6 @@ pub mod common; pub mod descriptors; +pub mod labels; pub mod output; pub use common::*; #[cfg(feature = "hwi")] diff --git a/src/utils/types.rs b/src/utils/types.rs index f6bd4cfd..a3908a9b 100644 --- a/src/utils/types.rs +++ b/src/utils/types.rs @@ -128,6 +128,18 @@ pub struct StatusResult { pub message: String, } +/// The label that was set, shaped like the BIP-329 record it is stored as. +#[derive(Serialize, Debug)] +pub struct LabelResult { + /// The BIP-329 record type: `tx`, `output` or `addr`. + #[serde(rename = "type")] + pub kind: &'static str, + /// What was labelled: a txid, a `TXID:VOUT` outpoint or an address. + #[serde(rename = "ref")] + pub reference: String, + pub label: String, +} + #[cfg(any( feature = "electrum", feature = "esplora", diff --git a/tests/integration/offline.rs b/tests/integration/offline.rs index 417bf72b..fc1252ba 100644 --- a/tests/integration/offline.rs +++ b/tests/integration/offline.rs @@ -490,3 +490,303 @@ mod multipath_tests { .failure(); } } + +/// Label tests need a persisted wallet, and only an `rpc` or a backend-less config can be +/// created here without a running server. +#[cfg(all( + feature = "sqlite", + any( + feature = "rpc", + not(any(feature = "electrum", feature = "esplora", feature = "cbf")) + ) +))] +mod label_tests { + use crate::common::BdkCli; + use assert_cmd::Command; + use predicates::prelude::*; + use serde_json::Value; + use std::path::PathBuf; + use tempfile::TempDir; + + const WALLET_NAME: &str = "label_wallet"; + /// A valid regtest address that does not belong to the test wallet. + const FOREIGN_REGTEST_ADDRESS: &str = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"; + /// A valid mainnet address. + const MAINNET_ADDRESS: &str = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"; + /// A txid the wallet has never seen. + const UNKNOWN_TXID: &str = "5fe2524f0c46bb12767d1865114031cd631578ac05422a767c0edf23f5c0aeaa"; + + /// A regtest wallet in a fresh data directory. + fn setup() -> (BdkCli, TempDir) { + let temp_dir = TempDir::new().unwrap(); + let cli = BdkCli::new("regtest", Some(temp_dir.path().to_path_buf())); + + let desc = cli + .cmd("descriptor", &["--type", "tr"]) + .output() + .expect("Command to generate descriptors failed"); + let desc: Value = + serde_json::from_slice(&desc.stdout).expect("Invalid JSON from output descriptor"); + let ext_desc = desc["private_descriptors"]["external"].as_str().unwrap(); + let int_desc = desc["private_descriptors"]["internal"].as_str().unwrap(); + + let mut config = cli.build_base_cmd(); + config + .arg("wallet") + .args(["--wallet", WALLET_NAME]) + .arg("config") + .args(["--ext-descriptor", ext_desc]) + .args(["--int-descriptor", int_desc]) + .args(["--database-type", "sqlite"]); + #[cfg(feature = "rpc")] + config + .args(["--client-type", "rpc"]) + .args(["--url", "http://localhost:18443"]); + config.assert().success(); + + (cli, temp_dir) + } + + fn wallet(cli: &BdkCli, args: &[&str]) -> Command { + let mut all = vec!["--wallet", WALLET_NAME]; + all.extend_from_slice(args); + cli.wallet_cmd(&all) + } + + fn labels_file(temp_dir: &TempDir) -> PathBuf { + temp_dir.path().join(WALLET_NAME).join("labels.jsonl") + } + + fn new_address(cli: &BdkCli) -> String { + let output = wallet(cli, &["new_address"]).output().unwrap(); + let json: Value = serde_json::from_slice(&output.stdout).unwrap(); + json["address"].as_str().unwrap().to_string() + } + + #[test] + fn labels_an_address_and_writes_a_bip329_file() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + + let output = wallet( + &cli, + &["label", "--address", &address, "--text", "from Alice"], + ) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["type"], "addr"); + assert_eq!(result["ref"], address.as_str()); + assert_eq!(result["label"], "from Alice"); + + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert_eq!(file.lines().count(), 1); + let record: Value = serde_json::from_str(file.lines().next().unwrap()).unwrap(); + assert_eq!(record["type"], "addr"); + assert_eq!(record["ref"], address.as_str()); + assert_eq!(record["label"], "from Alice"); + } + + #[test] + fn relabelling_replaces_the_label() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + + for text in ["first", "second"] { + wallet(&cli, &["label", "--address", &address, "--text", text]) + .assert() + .success(); + } + + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert_eq!(file.lines().count(), 1); + assert!(file.contains("second")); + assert!(!file.contains("first")); + } + + #[test] + fn labels_for_different_addresses_accumulate() { + let (cli, temp_dir) = setup(); + let first = new_address(&cli); + let second = new_address(&cli); + + wallet(&cli, &["label", "--address", &first, "--text", "one"]) + .assert() + .success(); + wallet(&cli, &["label", "--address", &second, "--text", "two"]) + .assert() + .success(); + + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert_eq!(file.lines().count(), 2); + } + + #[test] + fn a_label_may_start_with_a_hyphen() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + + wallet(&cli, &["label", "--address", &address, "--text", "-5 sats"]) + .assert() + .success(); + + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert!(file.contains("-5 sats")); + } + + #[test] + fn rejects_an_address_of_another_network() { + let (cli, temp_dir) = setup(); + + wallet( + &cli, + &["label", "--address", MAINNET_ADDRESS, "--text", "wrong net"], + ) + .assert() + .failure() + .stderr(predicate::str::contains("is not valid on regtest")); + + assert!(!labels_file(&temp_dir).exists()); + } + + #[test] + fn rejects_an_address_that_is_not_the_wallets() { + let (cli, temp_dir) = setup(); + + wallet( + &cli, + &[ + "label", + "--address", + FOREIGN_REGTEST_ADDRESS, + "--text", + "not mine", + ], + ) + .assert() + .failure() + .stderr(predicate::str::contains("does not belong to this wallet")); + + assert!(!labels_file(&temp_dir).exists()); + } + + #[test] + fn an_unknown_transaction_asks_to_sync_first() { + let (cli, temp_dir) = setup(); + + wallet( + &cli, + &["label", "--txid", UNKNOWN_TXID, "--text", "mystery"], + ) + .assert() + .failure() + .stderr(predicate::str::contains("sync the wallet first")); + + assert!(!labels_file(&temp_dir).exists()); + } + + #[test] + fn an_unknown_utxo_asks_to_sync_first() { + let (cli, _temp_dir) = setup(); + let outpoint = format!("{UNKNOWN_TXID}:0"); + + wallet(&cli, &["label", "--utxo", &outpoint, "--text", "mystery"]) + .assert() + .failure() + .stderr(predicate::str::contains("sync the wallet first")); + } + + #[test] + fn exactly_one_target_is_required() { + let (cli, _temp_dir) = setup(); + let address = new_address(&cli); + + wallet(&cli, &["label", "--text", "no target"]) + .assert() + .failure() + .stderr(predicate::str::contains("--txid")); + + wallet( + &cli, + &[ + "label", + "--txid", + UNKNOWN_TXID, + "--address", + &address, + "--text", + "two targets", + ], + ) + .assert() + .failure() + .stderr(predicate::str::contains("cannot be used with")); + } + + #[test] + fn an_empty_label_is_rejected() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + + wallet(&cli, &["label", "--address", &address, "--text", " "]) + .assert() + .failure() + .stderr(predicate::str::contains("must not be empty")); + + assert!(!labels_file(&temp_dir).exists()); + } + + #[test] + fn a_corrupt_labels_file_fails_label_only() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + std::fs::write(labels_file(&temp_dir), "this is not jsonl\n").unwrap(); + + // The label command names the file it could not read... + wallet(&cli, &["label", "--address", &address, "--text", "x"]) + .assert() + .failure() + .stderr(predicate::str::contains("labels.jsonl")); + + // ...and does not touch it... + assert_eq!( + std::fs::read_to_string(labels_file(&temp_dir)).unwrap(), + "this is not jsonl\n" + ); + + // ...while commands that do not use labels keep working. + wallet(&cli, &["balance"]) + .assert() + .success() + .stdout(predicate::str::contains("\"total\":")); + } + + #[cfg(feature = "repl")] + #[test] + fn labels_can_be_set_in_the_repl() { + let (cli, temp_dir) = setup(); + let address = new_address(&cli); + + let output = cli + .build_base_cmd() + .args(["repl", "--wallet", WALLET_NAME]) + .write_stdin(format!( + "wallet label --address {address} --text \"from the repl\"\nexit\n" + )) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert!(file.contains("from the repl"), "labels file: {file}"); + } +} From 32b7574e6da40ea1f8df52e526e2d1f9c6ed9ab6 Mon Sep 17 00:00:00 2001 From: musab1258 Date: Fri, 30 Oct 2026 02:30:19 +0100 Subject: [PATCH 2/4] feat(labels): show labels in transactions, unspent and unused_address --- Cargo.toml | 2 +- src/handlers/offline.rs | 10 +- src/utils/labels.rs | 45 +++++++ src/utils/types.rs | 25 +++- tests/integration/offline.rs | 245 ++++++++++++++++++++++++++++++++++- 5 files changed, 322 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 49d80c3a..0d1e1489 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,7 +42,7 @@ bdk_message_signer = { version = "0.2.0", optional = true } bitcoin-payment-instructions = { version = "0.7.0", optional = true} async-hwi = { version = "0.0.35", features = ["specter", "coldcard", "ledger", "jade", "bitbox", "service"], optional = true} -bdk-labels = "0.2.1" +bdk-labels = "0.2.2" [features] default = ["repl", "sqlite"] diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 3c0399e7..23f86a47 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -118,9 +118,11 @@ impl AppCommand>> for UnusedAddressCommand { type Output = AddressResult; fn execute(&self, ctx: &mut AppContext>) -> Result { + let labels = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name).load_for_display(); let wallet = &mut ctx.state.wallet; let address_info = wallet.next_unused_address(KeychainKind::External); - Ok(AddressResult::from(address_info)) + let label = labels.address(&address_info.address); + Ok(AddressResult::from(address_info).with_label(label)) } } @@ -131,13 +133,15 @@ impl AppCommand>> for UnspentCommand { type Output = ListResult; fn execute(&self, ctx: &mut AppContext>) -> Result { + let labels = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name).load_for_display(); let wallet = &mut ctx.state.wallet; let outputs: Vec<_> = wallet.list_unspent().collect(); let utxos = outputs .into_iter() .map(|utxo| { let is_locked = wallet.is_outpoint_locked(utxo.outpoint); - UnspentDetails::from_local_output(&utxo, ctx.network, is_locked) + let label = labels.output(utxo.outpoint); + UnspentDetails::from_local_output(&utxo, ctx.network, is_locked, label) }) .collect(); @@ -152,6 +156,7 @@ impl AppCommand>> for TransactionsCommand { type Output = ListResult; fn execute(&self, ctx: &mut AppContext>) -> Result { + let labels = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name).load_for_display(); let transactions = &mut ctx.state.wallet.transactions(); let txns: Vec = transactions @@ -175,6 +180,7 @@ impl AppCommand>> for TransactionsCommand { input_count: tx.tx_node.input.len(), output_count: tx.tx_node.output.len(), total_value, + label: labels.tx(tx.tx_node.txid), } }) .collect(); diff --git a/src/utils/labels.rs b/src/utils/labels.rs index b23a04be..2ebecc61 100644 --- a/src/utils/labels.rs +++ b/src/utils/labels.rs @@ -7,7 +7,9 @@ use crate::error::BDKCliError as Error; use crate::utils::write_file_content; +use bdk_labels::bip329::LabelRef; use bdk_labels::{LabelChangeset, LabelPersister, MergeStrategy}; +use bdk_wallet::bitcoin::{Address, OutPoint, Txid}; use std::fs::File; use std::io::{self, BufReader}; use std::path::{Path, PathBuf}; @@ -37,6 +39,21 @@ impl LabelStore { .map_err(|e| Error::LabelsError(bdk_labels::Error::Io(e))) } + /// Load the labels to annotate the output of a command that merely displays them. + /// + /// A labels file that cannot be read is reported as a warning and the command + /// carries on without labels, as listing transactions should not need a healthy + /// labels file. Commands that set or change labels use [`Self::load`] instead. + pub fn load_for_display(&self) -> LabelLookup { + match self.load() { + Ok(labels) => LabelLookup(labels), + Err(e) => { + log::warn!("Not showing labels: {e}"); + LabelLookup(LabelChangeset::new()) + } + } + } + /// An I/O error that names the labels file. fn io_error(&self, cause: impl std::fmt::Display) -> io::Error { io::Error::other(format!("{}: {cause}", self.path.display())) @@ -48,6 +65,34 @@ impl LabelStore { } } +/// Labels, looked up by what they label. +#[derive(Debug)] +pub struct LabelLookup(LabelChangeset); + +impl LabelLookup { + /// The label of a transaction. + pub fn tx(&self, txid: Txid) -> Option { + self.label(&LabelRef::Txid(txid)) + } + + /// The label of an output (a UTXO, when it is unspent). + pub fn output(&self, outpoint: OutPoint) -> Option { + self.label(&LabelRef::Output(outpoint)) + } + + /// The label of an address. + pub fn address(&self, address: &Address) -> Option { + self.label(&LabelRef::Address(address.clone().into_unchecked())) + } + + fn label(&self, target: &LabelRef) -> Option { + self.0 + .get(target) + .and_then(|label| label.label()) + .map(str::to_string) + } +} + impl LabelPersister for LabelStore { type Error = io::Error; diff --git a/src/utils/types.rs b/src/utils/types.rs index a3908a9b..b0850d0e 100644 --- a/src/utils/types.rs +++ b/src/utils/types.rs @@ -14,6 +14,16 @@ use serde_json::json; pub struct AddressResult { pub address: String, pub index: u32, + /// The address' BIP-329 label, left out when it has none. + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, +} + +impl AddressResult { + pub fn with_label(mut self, label: Option) -> Self { + self.label = label; + self + } } impl From for AddressResult { @@ -21,6 +31,7 @@ impl From for AddressResult { Self { address: info.address.to_string(), index: info.index, + label: None, } } } @@ -44,6 +55,9 @@ pub struct TransactionDetails { pub output_count: usize, #[serde(skip)] pub total_value: u64, + /// The transaction's BIP-329 label, left out when it has none. + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, } /// single UTXO @@ -56,10 +70,18 @@ pub struct UnspentDetails { pub derivation_index: u32, pub chain_position: serde_json::Value, pub is_locked: bool, + /// The UTXO's BIP-329 label, left out when it has none. + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, } impl UnspentDetails { - pub fn from_local_output(utxo: &LocalOutput, _network: Network, is_locked: bool) -> Self { + pub fn from_local_output( + utxo: &LocalOutput, + _network: Network, + is_locked: bool, + label: Option, + ) -> Self { let outpoint_str = utxo.outpoint.to_string(); Self { @@ -70,6 +92,7 @@ impl UnspentDetails { derivation_index: utxo.derivation_index, chain_position: serde_json::to_value(utxo.chain_position).unwrap_or(json!({})), is_locked, + label, } } } diff --git a/tests/integration/offline.rs b/tests/integration/offline.rs index fc1252ba..129a1b82 100644 --- a/tests/integration/offline.rs +++ b/tests/integration/offline.rs @@ -503,6 +503,13 @@ mod multipath_tests { mod label_tests { use crate::common::BdkCli; use assert_cmd::Command; + use bdk_wallet::bitcoin::absolute::LockTime; + use bdk_wallet::bitcoin::hashes::Hash; + use bdk_wallet::bitcoin::transaction::Version; + use bdk_wallet::bitcoin::{ + Amount, Network, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness, + }; + use bdk_wallet::{KeychainKind, Wallet}; use predicates::prelude::*; use serde_json::Value; use std::path::PathBuf; @@ -518,6 +525,12 @@ mod label_tests { /// A regtest wallet in a fresh data directory. fn setup() -> (BdkCli, TempDir) { + let (cli, temp_dir, _, _) = setup_with_descriptors(); + (cli, temp_dir) + } + + /// Like [`setup`], also returning the wallet's external and internal descriptors. + fn setup_with_descriptors() -> (BdkCli, TempDir, String, String) { let temp_dir = TempDir::new().unwrap(); let cli = BdkCli::new("regtest", Some(temp_dir.path().to_path_buf())); @@ -544,7 +557,78 @@ mod label_tests { .args(["--url", "http://localhost:18443"]); config.assert().success(); - (cli, temp_dir) + (cli, temp_dir, ext_desc.to_string(), int_desc.to_string()) + } + + /// A transaction the wallet received, and the output it received it in. + struct Received { + txid: Txid, + outpoint: OutPoint, + } + + /// Writes `count` unconfirmed transactions, each paying 50 000 sats to a new address, into + /// the wallet's database, as if a sync had found them. No node is needed to do this. + fn receive(temp_dir: &TempDir, ext: &str, int: &str, count: u8) -> Vec { + let wallet_dir = temp_dir.path().join(WALLET_NAME); + std::fs::create_dir_all(&wallet_dir).unwrap(); + let db_file = wallet_dir.join("wallet.sqlite"); + let mut db = bdk_wallet::rusqlite::Connection::open(db_file).unwrap(); + let mut wallet = Wallet::create(ext.to_string(), int.to_string()) + .network(Network::Regtest) + .create_wallet(&mut db) + .unwrap(); + + let received: Vec<_> = (1..=count) + .map(|funding| { + let address = wallet.reveal_next_address(KeychainKind::External); + let tx = Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([funding; 32]), 0), + script_sig: ScriptBuf::new(), + sequence: Sequence::MAX, + witness: Witness::new(), + }], + output: vec![TxOut { + value: Amount::from_sat(50_000), + script_pubkey: address.script_pubkey(), + }], + }; + let txid = tx.compute_txid(); + wallet.apply_unconfirmed_txs([(tx, 1_700_000_000)]); + Received { + txid, + outpoint: OutPoint::new(txid, 0), + } + }) + .collect(); + + wallet.persist(&mut db).unwrap(); + received + } + + /// The `label` of the entry of a JSON `items` list that has the given `key` equal to `id`. + fn label_in(list: &Value, key: &str, id: &str) -> Option { + let entry = list["items"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry[key] == id) + .unwrap_or_else(|| panic!("{id} is not in {list}")); + entry + .get("label") + .map(|label| label.as_str().unwrap().to_string()) + } + + fn json(cli: &BdkCli, args: &[&str]) -> Value { + let output = wallet(cli, args).output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() } fn wallet(cli: &BdkCli, args: &[&str]) -> Command { @@ -789,4 +873,163 @@ mod label_tests { let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); assert!(file.contains("from the repl"), "labels file: {file}"); } + + #[test] + fn transactions_and_unspent_show_labels() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + let (txid, outpoint) = ( + received[0].txid.to_string(), + received[0].outpoint.to_string(), + ); + + wallet(&cli, &["label", "--txid", &txid, "--text", "salary"]) + .assert() + .success(); + wallet(&cli, &["label", "--utxo", &outpoint, "--text", "my coin"]) + .assert() + .success(); + + let transactions = json(&cli, &["transactions"]); + assert_eq!( + label_in(&transactions, "txid", &txid).as_deref(), + Some("salary") + ); + let unspent = json(&cli, &["unspent"]); + assert_eq!( + label_in(&unspent, "outpoint", &outpoint).as_deref(), + Some("my coin") + ); + } + + #[test] + fn unlabelled_items_have_no_label_field() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + + let transactions = json(&cli, &["transactions"]); + let unspent = json(&cli, &["unspent"]); + + assert_eq!( + label_in(&transactions, "txid", &received[0].txid.to_string()), + None + ); + assert_eq!( + label_in(&unspent, "outpoint", &received[0].outpoint.to_string()), + None + ); + } + + #[test] + fn a_dash_label_is_told_apart_from_no_label() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 2); + let (first, second) = (received[0].txid.to_string(), received[1].txid.to_string()); + + wallet(&cli, &["label", "--txid", &first, "--text", "\u{2014}"]) + .assert() + .success(); + + let transactions = json(&cli, &["transactions"]); + assert_eq!( + label_in(&transactions, "txid", &first).as_deref(), + Some("\u{2014}") + ); + assert_eq!(label_in(&transactions, "txid", &second), None); + } + + #[test] + fn labelling_a_utxo_keeps_it_spendable_or_frozen_as_it_was() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + let outpoint = received[0].outpoint.to_string(); + let output_record = |file: &str| -> Value { + file.lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .find(|record| record["type"] == "output") + .unwrap() + }; + + // Naming a coin does not freeze it... + wallet(&cli, &["label", "--utxo", &outpoint, "--text", "my coin"]) + .assert() + .success(); + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert_eq!(output_record(&file)["spendable"], true); + + // ...and renaming a coin that was frozen elsewhere does not unfreeze it. + let frozen = file.replace("\"spendable\":true", "\"spendable\":false"); + std::fs::write(labels_file(&temp_dir), frozen).unwrap(); + wallet(&cli, &["label", "--utxo", &outpoint, "--text", "renamed"]) + .assert() + .success(); + let file = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + assert_eq!(output_record(&file)["spendable"], false); + assert_eq!(output_record(&file)["label"], "renamed"); + } + + #[test] + fn unused_address_shows_its_label() { + let (cli, _temp_dir) = setup(); + let address = new_address(&cli); + + assert_eq!(json(&cli, &["unused_address"]).get("label"), None); + wallet( + &cli, + &["label", "--address", &address, "--text", "from Alice"], + ) + .assert() + .success(); + + let unused = json(&cli, &["unused_address"]); + assert_eq!(unused["address"], address.as_str()); + assert_eq!(unused["label"], "from Alice"); + } + + #[test] + fn a_corrupt_labels_file_does_not_break_display_commands() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + std::fs::write(labels_file(&temp_dir), "this is not jsonl\n").unwrap(); + + // Commands that show labels warn about the file and carry on without labels... + for command in ["transactions", "unspent", "unused_address"] { + wallet(&cli, &[command]) + .assert() + .success() + .stderr(predicate::str::contains("labels.jsonl")); + } + // ...and commands that have nothing to do with labels do not even look at it. + wallet(&cli, &["balance"]) + .assert() + .success() + .stderr(predicate::str::contains("labels.jsonl").not()); + + let unspent = json(&cli, &["unspent"]); + assert_eq!( + label_in(&unspent, "outpoint", &received[0].outpoint.to_string()), + None + ); + } + + #[cfg(feature = "repl")] + #[test] + fn labels_are_shown_in_the_repl() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + let outpoint = received[0].outpoint.to_string(); + wallet(&cli, &["label", "--utxo", &outpoint, "--text", "my coin"]) + .assert() + .success(); + + let output = cli + .build_base_cmd() + .args(["repl", "--wallet", WALLET_NAME]) + .write_stdin("wallet unspent\nexit\n") + .output() + .unwrap(); + + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("my coin"), "REPL output: {stdout}"); + } } From 8914e77c3a7442c9c417c5f92147fb2f1e171722 Mon Sep 17 00:00:00 2001 From: musab1258 Date: Fri, 30 Oct 2026 07:26:37 +0100 Subject: [PATCH 3/4] feat(labels): add import_labels and export_labels --- src/commands.rs | 13 +- src/handlers/offline.rs | 105 ++++++++++++++++- src/utils/common.rs | 4 +- src/utils/types.rs | 17 +++ tests/integration/offline.rs | 222 +++++++++++++++++++++++++++++++++++ 5 files changed, 351 insertions(+), 10 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 239020dc..ae09e715 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -20,10 +20,11 @@ use crate::handlers::{ descriptor::DescriptorCommand, key::{DeriveKeyCommand, GenerateKeyCommand, RestoreKeyCommand}, offline::{ - BalanceCommand, BumpFeeCommand, CombinePsbtCommand, CreateTxCommand, ExtractPsbtCommand, - FinalizePsbtCommand, LabelCommand, LockUtxoCommand, LockedUtxosCommand, NewAddressCommand, - PoliciesCommand, PublicDescriptorCommand, SignCommand, TransactionsCommand, - UnlockUtxoCommand, UnspentCommand, UnusedAddressCommand, + BalanceCommand, BumpFeeCommand, CombinePsbtCommand, CreateTxCommand, ExportLabelsCommand, + ExtractPsbtCommand, FinalizePsbtCommand, ImportLabelsCommand, LabelCommand, + LockUtxoCommand, LockedUtxosCommand, NewAddressCommand, PoliciesCommand, + PublicDescriptorCommand, SignCommand, TransactionsCommand, UnlockUtxoCommand, + UnspentCommand, UnusedAddressCommand, }, }; @@ -491,6 +492,10 @@ pub enum OfflineWalletSubCommand { LockedUtxos(LockedUtxosCommand), /// Attach a BIP-329 label to a transaction, a UTXO or an address. Label(LabelCommand), + /// Import labels from a BIP-329 JSONL file. + ImportLabels(ImportLabelsCommand), + /// Export the wallet's labels to a BIP-329 JSONL file. + ExportLabels(ExportLabelsCommand), /// Creates a new unsigned transaction from DNS payment instructions. #[cfg(feature = "dns_payment")] CreateDnsTx(CreateDnsTxCommand), diff --git a/src/handlers/offline.rs b/src/handlers/offline.rs index 23f86a47..fe97a720 100644 --- a/src/handlers/offline.rs +++ b/src/handlers/offline.rs @@ -5,20 +5,23 @@ use crate::utils::labels::LabelStore; use crate::utils::output::{FormatOutput, ListResult}; use crate::utils::parse_address; use crate::utils::types::{ - AddressResult, BalanceResult, KeychainPair, LabelResult, PsbtResult, RawPsbt, - TransactionDetails, UnspentDetails, + AddressResult, BalanceResult, ExportLabelsResult, ImportLabelsResult, KeychainPair, + LabelResult, PsbtResult, RawPsbt, TransactionDetails, UnspentDetails, }; -use crate::utils::{parse_fee_rate, parse_outpoint, parse_recipient}; -use bdk_labels::{Bip329, LabelledWallet, OutputTarget}; +use crate::utils::{parse_fee_rate, parse_outpoint, parse_recipient, write_file_content}; +use bdk_labels::{Bip329, LabelledWallet, MergeStrategy, OutputTarget}; use bdk_wallet::bitcoin::address::NetworkUnchecked; use bdk_wallet::bitcoin::base64::Engine; use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD; use bdk_wallet::bitcoin::script::PushBytesBuf; use bdk_wallet::bitcoin::{Address, Amount, FeeRate, OutPoint, Psbt, ScriptBuf, Sequence, Txid}; use bdk_wallet::{KeychainKind, SignOptions}; -use clap::{ArgGroup, Parser}; +use clap::{ArgGroup, Parser, ValueEnum}; use serde_json::json; use std::collections::BTreeMap; +use std::fs::File; +use std::io::BufReader; +use std::path::PathBuf; #[cfg(feature = "silent-payments")] use { crate::utils::common::parse_sp_code_value_pairs, @@ -90,6 +93,8 @@ impl OfflineWalletSubCommand { locked_utxos.execute(ctx)?.write_out(std::io::stdout()) } Self::Label(label) => label.execute(ctx)?.write_out(std::io::stdout()), + Self::ImportLabels(import) => import.execute(ctx)?.write_out(std::io::stdout()), + Self::ExportLabels(export) => export.execute(ctx)?.write_out(std::io::stdout()), #[cfg(feature = "dns_payment")] Self::CreateDnsTx(_) => Err(Error::Generic( "CreateDnsTx is dispatched asynchronously through main".to_string(), @@ -1011,3 +1016,93 @@ fn unknown_to_wallet(error: bdk_labels::Error) -> Error { other => Error::LabelsError(other), } } + +/// What to do with an imported label for something that already has a label. +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum LabelMergeStrategy { + /// Keep the wallet's label, ignore the imported one. + KeepExisting, + /// Replace the wallet's label with the imported one. + Overwrite, +} + +impl From for MergeStrategy { + fn from(strategy: LabelMergeStrategy) -> Self { + match strategy { + LabelMergeStrategy::KeepExisting => MergeStrategy::KeepExisting, + LabelMergeStrategy::Overwrite => MergeStrategy::Overwrite, + } + } +} + +#[derive(Parser, Debug, Clone, PartialEq)] +pub struct ImportLabelsCommand { + /// The BIP-329 JSONL file to import. + #[arg(value_name = "FILE")] + pub file: PathBuf, + + /// What to do with an imported label for something that already has a label. + #[arg(long = "strategy", value_enum, default_value_t = LabelMergeStrategy::KeepExisting)] + pub strategy: LabelMergeStrategy, +} + +impl AppCommand>> for ImportLabelsCommand { + type Output = ImportLabelsResult; + + fn execute(&self, ctx: &mut AppContext>) -> Result { + let mut store = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name); + let mut labels = store.load()?; + + let file = File::open(&self.file) + .map_err(|e| Error::Generic(format!("Cannot open {}: {e}", self.file.display())))?; + + let mut labelled = LabelledWallet { + wallet: &mut *ctx.state.wallet, + labels: &mut labels, + }; + // The whole file is read before any label is merged, so a bad file imports nothing. + labelled + .import_labels(BufReader::new(file), self.strategy.into()) + .map_err(|e| Error::Generic(format!("Cannot import {}: {e}", self.file.display())))?; + let imported = labelled.labels.diff().len(); + labelled.persist(&mut store)?; + + Ok(ImportLabelsResult { + file: self.file.display().to_string(), + imported, + total: labels.len(), + }) + } +} + +#[derive(Parser, Debug, Clone, PartialEq)] +pub struct ExportLabelsCommand { + /// The BIP-329 JSONL file to write, an existing file is replaced. + #[arg(value_name = "FILE")] + pub file: PathBuf, +} + +impl AppCommand>> for ExportLabelsCommand { + type Output = ExportLabelsResult; + + fn execute(&self, ctx: &mut AppContext>) -> Result { + let store = LabelStore::new(&ctx.datadir, &ctx.state.wallet_name); + let mut labels = store.load()?; + let labelled = LabelledWallet { + wallet: &mut *ctx.state.wallet, + labels: &mut labels, + }; + + let mut jsonl = Vec::new(); + labelled.export_labels(&mut jsonl)?; + let jsonl = String::from_utf8(jsonl).map_err(|e| Error::Generic(e.to_string()))?; + // Labels say what the wallet's owner spends on and with whom, so the export is owner-only. + write_file_content(&self.file, &jsonl) + .map_err(|e| Error::Generic(format!("Cannot write {}: {e}", self.file.display())))?; + + Ok(ExportLabelsResult { + file: self.file.display().to_string(), + exported: labels.len(), + }) + } +} diff --git a/src/utils/common.rs b/src/utils/common.rs index 72761678..00ad1a82 100644 --- a/src/utils/common.rs +++ b/src/utils/common.rs @@ -279,7 +279,9 @@ pub fn command_requires_db(command: &OfflineWalletSubCommand) -> bool { | OfflineWalletSubCommand::Sign(_) | OfflineWalletSubCommand::ExtractPsbt(_) | OfflineWalletSubCommand::FinalizePsbt(_) - | OfflineWalletSubCommand::CombinePsbt(_) => false, + | OfflineWalletSubCommand::CombinePsbt(_) + | OfflineWalletSubCommand::ImportLabels(_) + | OfflineWalletSubCommand::ExportLabels(_) => false, #[cfg(feature = "message_signer")] OfflineWalletSubCommand::SignMessage(_) => true, diff --git a/src/utils/types.rs b/src/utils/types.rs index b0850d0e..931e81e0 100644 --- a/src/utils/types.rs +++ b/src/utils/types.rs @@ -151,6 +151,23 @@ pub struct StatusResult { pub message: String, } +/// What importing a BIP-329 file did to the wallet's labels. +#[derive(Serialize, Debug)] +pub struct ImportLabelsResult { + pub file: String, + /// Labels added or replaced, which excludes the ones that were kept. + pub imported: usize, + /// All the wallet's labels, after the import. + pub total: usize, +} + +/// What exporting the wallet's labels to a BIP-329 file wrote. +#[derive(Serialize, Debug)] +pub struct ExportLabelsResult { + pub file: String, + pub exported: usize, +} + /// The label that was set, shaped like the BIP-329 record it is stored as. #[derive(Serialize, Debug)] pub struct LabelResult { diff --git a/tests/integration/offline.rs b/tests/integration/offline.rs index 129a1b82..57506eb8 100644 --- a/tests/integration/offline.rs +++ b/tests/integration/offline.rs @@ -1032,4 +1032,226 @@ mod label_tests { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains("my coin"), "REPL output: {stdout}"); } + + /// A BIP-329 file with the given lines, in a fresh directory. + fn bip329_file(lines: &[String]) -> (TempDir, PathBuf) { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("incoming.jsonl"); + std::fs::write(&path, lines.join("\n") + "\n").unwrap(); + (dir, path) + } + + fn addr_line(address: &str, label: &str) -> String { + format!(r#"{{"type":"addr","ref":"{address}","label":"{label}"}}"#) + } + + fn records(path: &PathBuf) -> Vec { + std::fs::read_to_string(path) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + } + + fn label_of(records: &[Value], reference: &str) -> Option { + records + .iter() + .find(|record| record["ref"] == reference) + .map(|record| record["label"].as_str().unwrap().to_string()) + } + + #[test] + fn exported_labels_can_be_imported_into_another_wallet() { + let (cli, _temp_dir) = setup(); + let (first, second) = (new_address(&cli), new_address(&cli)); + wallet(&cli, &["label", "--address", &first, "--text", "one"]) + .assert() + .success(); + wallet(&cli, &["label", "--address", &second, "--text", "two"]) + .assert() + .success(); + let out_dir = TempDir::new().unwrap(); + let backup = out_dir.path().join("backup.jsonl"); + + let exported = json(&cli, &["export_labels", backup.to_str().unwrap()]); + assert_eq!(exported["exported"], 2); + let content = std::fs::read_to_string(&backup).unwrap(); + assert!( + content.ends_with('\n'), + "JSONL lines are newline terminated" + ); + + // An empty wallet takes the backup, and exports the very same file again. + let (other, other_dir) = setup(); + let imported = json(&other, &["import_labels", backup.to_str().unwrap()]); + assert_eq!(imported["imported"], 2); + assert_eq!(imported["total"], 2); + let again = out_dir.path().join("again.jsonl"); + wallet(&other, &["export_labels", again.to_str().unwrap()]) + .assert() + .success(); + assert_eq!(std::fs::read_to_string(&again).unwrap(), content); + assert_eq!(records(&labels_file(&other_dir)).len(), 2); + } + + #[test] + fn import_keeps_existing_labels_by_default() { + let (cli, temp_dir) = setup(); + let mine = new_address(&cli); + wallet(&cli, &["label", "--address", &mine, "--text", "mine"]) + .assert() + .success(); + let (_dir, incoming) = bip329_file(&[ + addr_line(&mine, "theirs"), + addr_line(FOREIGN_REGTEST_ADDRESS, "new"), + ]); + + let result = json(&cli, &["import_labels", incoming.to_str().unwrap()]); + + assert_eq!(result["imported"], 1); + assert_eq!(result["total"], 2); + let stored = records(&labels_file(&temp_dir)); + assert_eq!(label_of(&stored, &mine).as_deref(), Some("mine")); + assert_eq!( + label_of(&stored, FOREIGN_REGTEST_ADDRESS).as_deref(), + Some("new") + ); + } + + #[test] + fn import_can_overwrite_existing_labels() { + let (cli, temp_dir) = setup(); + let mine = new_address(&cli); + wallet(&cli, &["label", "--address", &mine, "--text", "mine"]) + .assert() + .success(); + let (_dir, incoming) = bip329_file(&[ + addr_line(&mine, "theirs"), + addr_line(FOREIGN_REGTEST_ADDRESS, "new"), + ]); + + let result = json( + &cli, + &[ + "import_labels", + incoming.to_str().unwrap(), + "--strategy", + "overwrite", + ], + ); + + assert_eq!(result["imported"], 2); + let stored = records(&labels_file(&temp_dir)); + assert_eq!(label_of(&stored, &mine).as_deref(), Some("theirs")); + } + + #[test] + fn import_keeps_what_the_wallet_does_not_know_and_whether_a_coin_is_frozen() { + let (cli, temp_dir) = setup(); + let frozen = format!( + r#"{{"type":"output","ref":"{UNKNOWN_TXID}:1","label":"frozen","spendable":false}}"# + ); + let (_dir, incoming) = bip329_file(&[ + format!(r#"{{"type":"tx","ref":"{UNKNOWN_TXID}","label":"elsewhere"}}"#), + frozen, + ]); + + wallet(&cli, &["import_labels", incoming.to_str().unwrap()]) + .assert() + .success(); + + let stored = records(&labels_file(&temp_dir)); + assert_eq!(stored.len(), 2); + let output = stored.iter().find(|r| r["type"] == "output").unwrap(); + assert_eq!(output["spendable"], false); + } + + #[test] + fn a_bad_import_file_changes_nothing() { + let (cli, temp_dir) = setup(); + let mine = new_address(&cli); + wallet(&cli, &["label", "--address", &mine, "--text", "mine"]) + .assert() + .success(); + let before = std::fs::read_to_string(labels_file(&temp_dir)).unwrap(); + let (_dir, incoming) = bip329_file(&[ + addr_line(FOREIGN_REGTEST_ADDRESS, "fine"), + "this is not jsonl".to_string(), + ]); + + wallet(&cli, &["import_labels", incoming.to_str().unwrap()]) + .assert() + .failure() + .stderr(predicate::str::contains("incoming.jsonl")); + + assert_eq!( + std::fs::read_to_string(labels_file(&temp_dir)).unwrap(), + before + ); + } + + #[test] + fn importing_a_missing_file_names_it() { + let (cli, temp_dir) = setup(); + + wallet(&cli, &["import_labels", "/nonexistent/incoming.jsonl"]) + .assert() + .failure() + .stderr(predicate::str::contains("/nonexistent/incoming.jsonl")); + + assert!(!labels_file(&temp_dir).exists()); + } + + #[test] + fn exporting_without_labels_writes_an_empty_file() { + let (cli, _temp_dir) = setup(); + let out_dir = TempDir::new().unwrap(); + let backup = out_dir.path().join("backup.jsonl"); + + let exported = json(&cli, &["export_labels", backup.to_str().unwrap()]); + + assert_eq!(exported["exported"], 0); + assert_eq!(std::fs::read_to_string(&backup).unwrap(), ""); + } + + #[cfg(unix)] + #[test] + fn an_export_is_owner_only() { + use std::os::unix::fs::PermissionsExt; + + let (cli, _temp_dir) = setup(); + let address = new_address(&cli); + wallet(&cli, &["label", "--address", &address, "--text", "x"]) + .assert() + .success(); + let out_dir = TempDir::new().unwrap(); + let backup = out_dir.path().join("backup.jsonl"); + + wallet(&cli, &["export_labels", backup.to_str().unwrap()]) + .assert() + .success(); + + let mode = std::fs::metadata(&backup).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + + #[test] + fn imported_labels_survive_for_later_commands() { + let (cli, temp_dir, ext, int) = setup_with_descriptors(); + let received = receive(&temp_dir, &ext, &int, 1); + let txid = received[0].txid.to_string(); + let (_dir, incoming) = bip329_file(&[format!( + r#"{{"type":"tx","ref":"{txid}","label":"from a backup"}}"# + )]); + + wallet(&cli, &["import_labels", incoming.to_str().unwrap()]) + .assert() + .success(); + + let transactions = json(&cli, &["transactions"]); + assert_eq!( + label_in(&transactions, "txid", &txid).as_deref(), + Some("from a backup") + ); + } } From bd6792a9a393ee25462f37e199bada540b3b1067 Mon Sep 17 00:00:00 2001 From: musab1258 Date: Fri, 30 Oct 2026 09:09:27 +0100 Subject: [PATCH 4/4] docs(labels): document the label commands --- CHANGELOG.md | 1 + NEW_FEATURE.md | 2 +- README.md | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eca00a16..77fa9755 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details. - Fixed `compile` silently accepting placeholder keys/hashes instead of validating them; added `--placeholders` to opt back into the old permissive behavior - Fixed `compile` panicking instead of returning an error when a key is valid on its own but the wrong shape for the requested script type (e.g. an x-only key under `sh`/`wsh`/`sh-wsh`, or an uncompressed key under `tr`) - Updated dependencies to resolve RUSTSEC advisories in rustls, rustls-webpki, webpki-roots, quinn-proto, h2 and zstd-sys; bumped async-hwi to 0.0.35. +- Added BIP-329 wallet labels with the `label`, `import_labels` and `export_labels` wallet commands, and a `label` field on `transactions`, `unspent` and `unused_address` output. Labels are kept in a `labels.jsonl` file in the wallet's data directory, using the `bdk-labels` crate. Fixes #184. ## [4.0.0] diff --git a/NEW_FEATURE.md b/NEW_FEATURE.md index 543fc164..613b01d1 100644 --- a/NEW_FEATURE.md +++ b/NEW_FEATURE.md @@ -17,7 +17,7 @@ __The Typestate (AppContext):__ Defines the environment your command runs in. | Context | What it Holds | When to use | |------ |-------- |------- | AppContext | just network, datadir | needs no wallet and blockchain | -| AppContext | wallet | needs the wallet but not blockchain|  +| AppContext | wallet, wallet_name | needs the wallet but not blockchain|  | AppContext | wallet, client, wallet_name | needs a wallet, and a blockchain backend | The below table should aid your decision: diff --git a/README.md b/README.md index 702fa6a3..2238be4c 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,38 @@ To delete a saved wallet configuration: cargo run -- wallets delete ``` +## Wallet labels (BIP-329) + +`bdk-cli` can attach human-readable labels to a wallet's transactions, UTXOs and addresses, and import and export them in the [BIP-329](https://github.com/bitcoin/bips/blob/master/bip-0329.mediawiki) wallet labels format, so they can be moved to and from other wallets. + +Labels are stored in a `labels.jsonl` file in the wallet's data directory, for example `~/.bdk-bitcoin//labels.jsonl`. The file is only readable by its owner, and is independent of the wallet's database (sqlite or redb). Only the commands described here read it, so a damaged labels file cannot get in the way of other commands such as `balance`. + +To label a transaction, a UTXO (`:`) or an address, give exactly one of `--txid`, `--utxo` or `--address`, and the label with `--text`: + +```shell +cargo run --features -- wallet --wallet label --txid --text "March salary" +cargo run --features -- wallet --wallet label --utxo : --text "Cold storage coin" +cargo run --features -- wallet --wallet label --address
--text "From Alice" +``` + +Setting a label again replaces the previous one. A transaction or a UTXO can only be labelled once the wallet knows about it, so sync the wallet first. An address must belong to the wallet and to the wallet's network. + +The `transactions`, `unspent` and `unused_address` commands show a `label` field for the items that have a label, and leave it out for the others. If the labels file cannot be read, these commands print a warning and carry on without labels, while `label`, `import_labels` and `export_labels` fail and name the file. + +To write the wallet's labels to a BIP-329 file, and to read labels from one: + +```shell +cargo run --features -- wallet --wallet export_labels +cargo run --features -- wallet --wallet import_labels [--strategy ] +``` + +An exported file replaces any file already at that path, and is only readable by its owner. When an imported label is for something that already has a label, `--strategy keep-existing` (the default) keeps the wallet's label and `--strategy overwrite` replaces it. A file that cannot be read in full is rejected, and nothing is imported from it. Labels for things the wallet does not know about are kept, so a file from another wallet can be imported before the wallet has synced. + +> [!NOTE] +> BIP-329 output labels have a `spendable` flag, which other wallets use to mark a coin as frozen. `bdk-cli` stores and exports the flag, and labelling a UTXO never changes it, but importing `spendable: false` does not lock the coin in `bdk-cli`. To stop a UTXO from being spent, use the `lock_utxo` command. +> +> There is no command to remove a label yet. + ## Adding new features/command This [guide](./NEW_FEATURE.md) explains how to add a new command/feature to bdk-cli's modular architecture.