Skip to content

Add initializing wallet configuration with bdk-cli wallet init #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 85 additions & 2 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ log = "0.4"
serde_json = "1.0"
thiserror = "2.0.11"
tokio = { version = "1", features = ["full"] }
toml = "0.8.23"
serde= {version = "1.0", features = ["derive"]}

# Optional dependencies
bdk_bitcoind_rpc = { version = "0.20.0", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,4 @@ descriptors private wallet=default_wallet:
# run any bitcoin-cli rpc command
[group('rpc')]
rpc command wallet=default_wallet:
bitcoin-cli -datadir={{default_datadir}} -regtest -rpcwallet={{wallet}} -rpcuser={{rpc_user}} -rpcpassword={{rpc_password}} {{command}}
bitcoin-cli -datadir={{default_datadir}} -regtest -rpcwallet={{wallet}} -rpcuser={{rpc_user}} -rpcpassword={{rpc_password}} {{command}}
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,46 @@ Note: You can modify the `Justfile` to reflect your nodes' configuration values.
cargo run --features rpc -- wallet -u "127.0.0.1:18443" -c rpc -a user:password balance
```

### Initializing Wallet Configurations with `bdk-cli wallet init`

The `bdk-cli wallet init` command simplifies wallet setup by saving configuration parameters to `config.toml` in the data directory (default `~/.bdk-bitcoin/config.toml`). This allows you to run subsequent `bdk-cli` wallet commands without repeatedly specifying configuration details, easing wallet operations.

To initialize a wallet configuration, use the following command structure:

```shell
cargo run --features <list-of-features> -- -n <network> wallet init --wallet <wallet_name> --ext-descriptor <ext_descriptor> --int-descriptor <int_descriptor> --client-type <client_type> --url <server_url> [--database-type <database_type>] [--rpc-user <rpc_user>]
[--rpc-password <rpc_password>]
```

For example, to initialize a wallet named `my_wallet` with `electrum` as the backend on `signet` network:

```shell
cargo run --features electrum -- -n signet wallet init -w my_wallet -e "tr(tprv8Z.../0/*)#dtdqk3dx" -i "tr(tprv8Z.../1/*)#ulgptya7" -d sqlite -c electrum -u "ssl://mempool.space:60602"
```

To overwrite an existing wallet configuration, use the `--force` flag at the end of the command.

You can omit the following arguments to use their default values:

`network`: Defaults to `testnet`

`database_type`: Defaults to `sqlite`

#### Using Saved Configuration

After a wallet is initialized, you can then run `bdk-cli` wallet commands without specifying the parameters, referencing only the wallet subcommand.

For example, with the wallet `my_wallet` initialized, generate a new address and sync the wallet as follow:

```shell
cargo run wallet -w my_wallet new_address

cargo run --features electrum wallet -w my_wallet sync
```

Note that each wallet has its own configuration, allowing multiple wallets with different configurations.


## Minimum Supported Rust Version (MSRV)

This library should always compile with any valid combination of features on Rust **1.75.0**.
83 changes: 76 additions & 7 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@

#![allow(clippy::large_enum_variant)]

use crate::config::WalletConfig;
use crate::error::BDKCliError as Error;
use bdk_wallet::bitcoin::{
bip32::{DerivationPath, Xpriv},
Address, Network, OutPoint, ScriptBuf,
};
use clap::{value_parser, Args, Parser, Subcommand, ValueEnum};
use std::path::Path;

#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
use crate::utils::parse_proxy_auth;
Expand Down Expand Up @@ -109,6 +112,14 @@ pub enum CliSubCommand {
/// Wallet operation subcommands.
#[derive(Debug, Subcommand, Clone, PartialEq)]
pub enum WalletSubCommand {
/// Initialize a wallet configuration and save to `config.toml`.
Init {
#[command(flatten)]
wallet_opts: WalletOpts,
/// Overwrite existing wallet configuration if it exists.
#[arg(long = "force", default_value_t = false)]
force: bool,
},
#[cfg(any(
feature = "electrum",
feature = "esplora",
Expand Down Expand Up @@ -167,15 +178,15 @@ pub struct WalletOpts {
feature = "rpc",
feature = "cbf"
))]
#[arg(env = "CLIENT_TYPE", short = 'c', long, value_enum, required = true)]
pub client_type: ClientType,
#[arg(env = "CLIENT_TYPE", short = 'c', long, value_enum)]
pub client_type: Option<ClientType>,
#[cfg(feature = "sqlite")]
#[arg(env = "DATABASE_TYPE", short = 'd', long, value_enum, required = true)]
pub database_type: DatabaseType,
#[arg(env = "DATABASE_TYPE", short = 'd', long, value_enum)]
pub database_type: Option<DatabaseType>,
/// Sets the server url.
#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
#[arg(env = "SERVER_URL", short = 'u', long, required = true)]
pub url: String,
#[arg(env = "SERVER_URL", short = 'u', long)]
pub url: Option<String>,
/// Electrum batch size.
#[cfg(feature = "electrum")]
#[arg(env = "ELECTRUM_BATCH_SIZE", short = 'b', long, default_value = "10")]
Expand All @@ -198,7 +209,7 @@ pub struct WalletOpts {
value_parser = parse_proxy_auth,
default_value = "user:password",
)]
pub basic_auth: (String, String),
pub basic_auth: Option<(String, String)>,
#[cfg(feature = "rpc")]
/// Sets an optional cookie authentication.
#[arg(env = "COOKIE")]
Expand All @@ -208,6 +219,64 @@ pub struct WalletOpts {
pub compactfilter_opts: CompactFilterOpts,
}

impl WalletOpts {
/// Load configuration from TOML file and merge with CLI options
pub fn load_config(&mut self, wallet_name: &str, datadir: &Path) -> Result<(), Error> {
if let Some(config) = WalletConfig::load(datadir)? {
if let Ok(config_opts) = config.get_wallet_opts(wallet_name) {
self.wallet = self.wallet.take().or(config_opts.wallet);
self.verbose = self.verbose || config_opts.verbose;
self.ext_descriptor = self.ext_descriptor.take().or(config_opts.ext_descriptor);
self.int_descriptor = self.int_descriptor.take().or(config_opts.int_descriptor);
#[cfg(any(
feature = "electrum",
feature = "esplora",
feature = "rpc",
feature = "cbf"
))]
{
self.client_type = self.client_type.clone().or(config_opts.client_type);
}
#[cfg(feature = "sqlite")]
{
// prioritizing the config.toml value for database type as it has a default value
self.database_type = config_opts.database_type.or(self.database_type.clone());
}
#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
{
self.url = self.url.take().or(config_opts.url);
}
#[cfg(feature = "electrum")]
{
self.batch_size = if self.batch_size != 10 {
config_opts.batch_size
} else {
self.batch_size
};
}
#[cfg(feature = "esplora")]
{
self.parallel_requests = if self.parallel_requests != 5 {
config_opts.parallel_requests
} else {
self.parallel_requests
};
}
#[cfg(feature = "rpc")]
{
self.basic_auth = self.basic_auth.take().or(config_opts.basic_auth);
self.cookie = self.cookie.take().or(config_opts.cookie);
}
#[cfg(feature = "cbf")]
{
self.compactfilter_opts = config_opts.compactfilter_opts;
}
}
}
Ok(())
}
}

/// Options to configure a SOCKS5 proxy for a blockchain client connection.
#[cfg(any(feature = "electrum", feature = "esplora"))]
#[derive(Debug, Args, Clone, PartialEq, Eq)]
Expand Down
Loading
Loading