]> Untitled Git - bdk-cli/commitdiff
refactor(key): move derive_master_key_from_mnemonic to utils
authorVihiga Tyonum <withtvpeter@gmail.com>
Tue, 1 Dec 2026 11:08:54 +0000 (12:08 +0100)
committerVihiga Tyonum <withtvpeter@gmail.com>
Tue, 1 Dec 2026 18:20:43 +0000 (19:20 +0100)
It returns domain values (Xpriv, Fingerprint) and is not tied to a
command, so it belongs with the other helpers in src/utils, next to
is_mnemonic.

Cargo.lock
Cargo.toml
NEW_FEATURE.md
src/handlers/config.rs
src/handlers/key.rs
src/handlers/offline.rs
src/utils/common.rs

index 1bc7186aed7089997e2d4ee3610c5e4e1021638a..203206f2e5d2bf634090d9ef78801726f6aeb35d 100644 (file)
@@ -3885,6 +3885,7 @@ version = "1.0.150"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
 dependencies = [
+ "indexmap",
  "itoa",
  "memchr",
  "serde",
index 827d0f1f34d58244e76003259767c8de45bf0bf7..f1b7fdfc85473b14d74666f7d7061eea9c254f6e 100644 (file)
@@ -18,7 +18,7 @@ clap_complete = "4.6"
 dirs = {  version = "6.0.0" }
 env_logger = "0.11.10"
 log = "0.4"
-serde_json = "1.0"
+serde_json = { version = "1.0", features = ["preserve_order"] }
 thiserror = "2.0.18"
 tokio = { version = "1", features = ["full"] }
 toml = "1.1.0"
index b2c7890134632169abeacf867e774be9797bc5a8..ac9c2a9acf24171f57b437e77c949151157ec765 100644 (file)
@@ -56,7 +56,7 @@ pub struct WalletDetailsCommand {
 
 Every command prints JSON, and that JSON is built in exactly one place: the command's own `execute` method. To find what a command prints, read its `execute`.
 - Helpers in `src/utils/` return domain values (bdk/bitcoin types, `String`s, small structs such as `KeychainDescriptors`) so they can be reused. They never build JSON.
-- `execute` turns those values into the output with `serde_json::json!`. 
+- `execute` turns those values into the output with `serde_json::json!`. Keys are printed in the order they are written.
 
 ##### Step 3: Implement the AppCommand Trait
 
@@ -70,13 +70,12 @@ use crate::error::BDKCliError as Error;
 use serde_json::{Value, json};
 
 impl AppCommand<AppContext<OfflineOperations<'_>>> for WalletDetailsCommand {
-    
     // 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 mut output = json!({
+        let mut output = json!({
             "network": wallet.network(),
             "fingerprint": wallet.fingerprint().to_string(),
         });
index 4ed38d3eaf7d1fe2ddf147f7039d2cec915fcbee..bb9e2f1ce580726f58e75681ffa553313493849d 100644 (file)
@@ -69,8 +69,7 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
 
         if config.wallets.contains_key(wallet_name.as_str()) && !self.force {
             return Err(Error::Generic(format!(
-                "Wallet '{}' already exists. Use --force to overwrite.",
-                wallet_name
+                "Wallet '{wallet_name}' already exists. Use --force to overwrite."
             )));
         };
 
@@ -78,8 +77,8 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
             && existing.network != ctx.network.to_string()
         {
             return Err(Error::Generic(format!(
-                "Wallet '{}' is configured for network '{}', and --force cannot change it to '{}'.",
-                wallet_name, existing.network, ctx.network
+                "Wallet '{wallet_name}' is configured for network '{}', and --force cannot change it to '{}'.",
+                existing.network, ctx.network
             )));
         }
 
@@ -157,11 +156,10 @@ impl AppCommand<AppContext<Init>> for SaveConfigCommand {
             .map_err(|error| Error::Generic(error.to_string()))?;
 
         Ok(json!({
-           "message": format!(
-                 "Wallet '{}' initialized successfully in {:?}",
-                 wallet_name,
-                 ctx.datadir.join("config.toml")
-             ),
+            "message": format!(
+                "Wallet '{wallet_name}' initialized successfully in {:?}",
+                ctx.datadir.join("config.toml")
+            ),
         }))
     }
 }
@@ -230,9 +228,9 @@ impl AppCommand<AppContext<Init>> for DeleteWalletConfigCommand {
 
         Ok(json!({
             "message": format!(
-                 "Wallet configuration '{}' deleted successfully",
-                 self.wallet_name
-             ),
+                "Wallet configuration '{}' deleted successfully",
+                self.wallet_name
+            ),
         }))
     }
 }
index 6a25a40fe781d907f8e854c35aede6467183d8e5..a863047d74052d40129860056a1216ca2a4b664f 100644 (file)
@@ -1,12 +1,12 @@
 use crate::commands::KeySubCommand;
 use crate::error::BDKCliError as Error;
 use crate::handlers::{AppCommand, AppContext, Init};
-use crate::utils::output::FormatOutput;
+use crate::utils::{derive_master_key_from_mnemonic, output::FormatOutput};
 use bdk_wallet::bip39::{Language, Mnemonic};
-use bdk_wallet::bitcoin::bip32::{DerivationPath, Fingerprint, KeySource, Xpriv};
-use bdk_wallet::bitcoin::{Network, key::Secp256k1};
+use bdk_wallet::bitcoin::bip32::{DerivationPath, KeySource, Xpriv};
+use bdk_wallet::bitcoin::key::Secp256k1;
 use bdk_wallet::keys::{
-    DerivableKey, DescriptorKey, ExtendedKey, GeneratableKey, GeneratedKey, bip39::WordCount,
+    DerivableKey, DescriptorKey, GeneratableKey, GeneratedKey, bip39::WordCount,
 };
 use bdk_wallet::miniscript::{self, Segwitv0};
 use clap::{Parser, ValueEnum};
@@ -145,19 +145,3 @@ impl AppCommand<AppContext<Init>> for RestoreKeyCommand {
         }))
     }
 }
-
-/// Derives the master key from a mnemonic and optional passphrase.
-fn derive_master_key_from_mnemonic(
-    mnemonic: &Mnemonic,
-    password: Option<String>,
-    network: Network,
-) -> Result<(Xpriv, Fingerprint), Error> {
-    let secp = Secp256k1::new();
-    let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
-    let xprv = xkey
-        .into_xprv(network.into())
-        .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?;
-    let fingerprint = xprv.fingerprint(&secp);
-
-    Ok((xprv, fingerprint))
-}
index 31aee423decfe33d775da4a164aa806fd189bd97..15e1210d50551a0103ae277c9b7ae05503c82a98 100644 (file)
@@ -155,7 +155,7 @@ impl AppCommand<AppContext<OfflineOperations<'_>>> for TransactionsCommand {
             .map(|tx| {
                 json!({
                     "txid": tx.tx_node.txid.to_string(),
-                   "is_coinbase": tx.tx_node.is_coinbase(),
+                    "is_coinbase": tx.tx_node.is_coinbase(),
                     "wtxid": tx.tx_node.compute_wtxid().to_string(),
                     "version": tx.tx_node.version,
                     "is_rbf": tx.tx_node.is_explicitly_rbf(),
index 1e3cbbe72588827e37f26845332b124f306f94c0..21514f0b2f32c8ee9f349810c7896317bb860901 100644 (file)
@@ -14,12 +14,15 @@ use bdk_wallet::Wallet;
     feature = "rpc"
 ))]
 use bdk_wallet::WalletEvent;
-use bdk_wallet::bitcoin::base64::Engine;
-use bdk_wallet::bitcoin::base64::prelude::BASE64_STANDARD;
+use bdk_wallet::bip39::Mnemonic;
+use bdk_wallet::bitcoin::base64::{Engine, prelude::BASE64_STANDARD};
+use bdk_wallet::bitcoin::bip32::{Fingerprint, Xpriv};
+use bdk_wallet::bitcoin::key::Secp256k1;
 use bdk_wallet::bitcoin::script::PushBytesBuf;
 use bdk_wallet::bitcoin::{
     Address, FeeRate, Network, OutPoint, Psbt, ScriptBuf, Transaction, Weight,
 };
+use bdk_wallet::keys::{DerivableKey, ExtendedKey};
 use std::{
     path::{Path, PathBuf},
     str::FromStr,
@@ -227,6 +230,22 @@ pub fn is_mnemonic(s: &str) -> bool {
     (12..=24).contains(&word_count) && s.chars().all(|c| c.is_alphanumeric() || c.is_whitespace())
 }
 
+/// Derives the master key from a mnemonic and optional passphrase.
+pub fn derive_master_key_from_mnemonic(
+    mnemonic: &Mnemonic,
+    password: Option<String>,
+    network: Network,
+) -> Result<(Xpriv, Fingerprint), Error> {
+    let secp = Secp256k1::new();
+    let xkey: ExtendedKey = (mnemonic.clone(), password).into_extended_key()?;
+    let xprv = xkey
+        .into_xprv(network.into())
+        .ok_or_else(|| Error::Generic("Private key info not found".to_string()))?;
+    let fingerprint = xprv.fingerprint(&secp);
+
+    Ok((xprv, fingerprint))
+}
+
 #[cfg(feature = "cbf")]
 pub async fn trace_logger(
     mut info_subcriber: Receiver<Info>,