Skip to content

Commit 28796ca

Browse files
committed
feat(wallet-init): add wallets command
- add wallets command - add warning for using priv descriptors - update readme - add loading network from config
1 parent 4f18243 commit 28796ca

File tree

7 files changed

+238
-220
lines changed

7 files changed

+238
-220
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ Changelog info is also documented on the [GitHub releases](https://github.com/bi
44
page. See [DEVELOPMENT_CYCLE.md](DEVELOPMENT_CYCLE.md) for more details.
55

66
## [Unreleased]
7-
- Add wallet configs initialization for initialiazing and saving wallet configs
87
- Add wallet subcommand `config` to save wallet configs
8+
- Add `wallets` command to list all wallets saved configs
99

1010
## [2.0.0]
1111

README.md

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -203,41 +203,43 @@ cargo run --pretty -n signet wallet -w {wallet_name} -d sqlite balance
203203
```
204204
This is available for wallet, key, repl and compile features. When ommitted, outputs default to `JSON`.
205205

206-
## Initializing Wallet Configurations with `init` Subcommand
206+
## Saving and using wallet configurations
207207

208-
The `wallet init` sub-command simplifies wallet operations 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.
208+
The `wallet config` sub-command allows you to save wallet settings to a `config.toml` file in the default directory (`~/.bdk-bitcoin/`) or custom directory specified with the `--datadir` flag. This eliminate the need to repeatedly specify descriptors, client types, and other parameters for each command. Once configured, you can use any wallet command by simply specifying the wallet name. All other parameters are automatically loaded from the saved configuration.
209209

210-
To initialize a wallet configuration, use the following command structure:
210+
To save a wallet settings:
211211

212212
```shell
213-
cargo run --features <list-of-features> -- -n <network> wallet --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>]
214-
[--rpc-password <rpc_password>] init
213+
cargo run --features <list-of-features> -- -n <network> wallet --wallet <wallet_name> config [ -f ] --ext-descriptor <ext_descriptor> --int-descriptor <int_descriptor> --client-type <client_type> --url <server_url> [--database-type <database_type>] [--rpc-user <rpc_user>]
214+
[--rpc-password <rpc_password>]
215215
```
216216

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

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

223-
To overwrite an existing wallet configuration, use the `--force` flag after the `init` sub-command.
223+
To overwrite an existing wallet configuration, use the `--force` flag after the `config` sub-command.
224224

225-
You can omit the following arguments to use their default values:
225+
#### Using a Configured Wallet
226226

227-
`network`: Defaults to `testnet`
227+
Once configured, use any wallet command with just the wallet name:
228228

229-
`database_type`: Defaults to `sqlite`
230-
231-
#### Using Saved Configuration
232-
233-
After a wallet is initialized, you can then run `bdk-cli` wallet commands without specifying the parameters, referencing only the wallet subcommand.
234-
235-
For example, with the wallet `my_wallet` initialized, generate a new address and sync the wallet as follow:
236229

237230
```shell
238-
cargo run wallet -w my_wallet --use-config new_address
231+
cargo run --features electrum wallet -w my_wallet new_address
239232

240-
cargo run --features electrum wallet -w my_wallet --use-config sync
233+
cargo run --features electrum wallet -w my_wallet full_scan
241234
```
242235

243236
Note that each wallet has its own configuration, allowing multiple wallets with different configurations.
237+
238+
#### View all saved Wallet Configs
239+
240+
To view all saved wallet configurations:
241+
242+
```shell
243+
cargo run wallets`
244+
```
245+
You can also use the `--pretty` flag for a formatted output.

src/commands.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,9 @@ pub enum CliSubCommand {
108108
/// Wallet name for this REPL session
109109
#[arg(env = "WALLET_NAME", short = 'w', long = "wallet", required = true)]
110110
wallet: String,
111-
112-
#[command(flatten)]
113-
wallet_opts: WalletOpts,
114111
},
112+
/// List all saved wallet configurations.
113+
Wallets,
115114
}
116115

117116
/// Wallet operation subcommands.

src/config.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ impl WalletConfig {
9090
"testnet" => Network::Testnet,
9191
"regtest" => Network::Regtest,
9292
"signet" => Network::Signet,
93+
"testnet4" => Network::Testnet4,
9394
_ => {
9495
return Err(Error::Generic("Invalid network".to_string()));
9596
}
@@ -105,7 +106,6 @@ impl WalletConfig {
105106
return Err(Error::Generic("Invalid database type".to_string()));
106107
}
107108
};
108-
109109
#[cfg(any(
110110
feature = "electrum",
111111
feature = "esplora",
@@ -144,9 +144,9 @@ impl WalletConfig {
144144
.clone()
145145
.ok_or_else(|| Error::Generic(format!("Server url not found")))?,
146146
#[cfg(feature = "electrum")]
147-
batch_size: 10,
147+
batch_size: wallet_config.batch_size.unwrap_or(10),
148148
#[cfg(feature = "esplora")]
149-
parallel_requests: 5,
149+
parallel_requests: wallet_config.parallel_requests.unwrap_or(5),
150150
#[cfg(feature = "rpc")]
151151
basic_auth: (
152152
wallet_config

src/handlers.rs

Lines changed: 176 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -876,6 +876,35 @@ pub fn handle_config_subcommand(
876876
wallet_opts: &WalletOpts,
877877
force: bool,
878878
) -> Result<String, Error> {
879+
if network == Network::Bitcoin {
880+
eprintln!(
881+
"WARNING: You are configuring a wallet for Bitcoin MAINNET.\n\
882+
This software is experimental and not recommended for use with real funds.\n\
883+
Consider using a testnet for testing purposes. \n"
884+
);
885+
}
886+
887+
let ext_descriptor = wallet_opts.ext_descriptor.clone();
888+
let int_descriptor = wallet_opts.int_descriptor.clone();
889+
890+
if ext_descriptor.contains("xprv") || ext_descriptor.contains("tprv") {
891+
eprintln!(
892+
"WARNING: Your external descriptor contains PRIVATE KEYS.\n\
893+
Private keys will be saved in PLAINTEXT in the config file.\n\
894+
This is a security risk. Consider using public descriptors instead."
895+
);
896+
}
897+
898+
if let Some(ref internal_desc) = int_descriptor {
899+
if internal_desc.contains("xprv") || internal_desc.contains("tprv") {
900+
eprintln!(
901+
"WARNING: Your internal descriptor contains PRIVATE KEYS.\n\
902+
Private keys will be saved in PLAINTEXT in the config file.\n\
903+
This is a security risk. Consider using public descriptors instead."
904+
);
905+
}
906+
}
907+
879908
let mut config = WalletConfig::load(datadir)?.unwrap_or(WalletConfig {
880909
network,
881910
wallets: HashMap::new(),
@@ -887,8 +916,6 @@ pub fn handle_config_subcommand(
887916
)));
888917
}
889918

890-
let ext_descriptor = wallet_opts.ext_descriptor.clone();
891-
let int_descriptor = wallet_opts.int_descriptor.clone();
892919
#[cfg(any(
893920
feature = "electrum",
894921
feature = "esplora",
@@ -1160,9 +1187,141 @@ pub(crate) fn handle_compile_subcommand(
11601187
}
11611188
}
11621189

1190+
/// Handle wallets command to show all saved wallet configurations
1191+
pub fn handle_wallets_subcommand(datadir: &Path, pretty: bool) -> Result<String, Error> {
1192+
let load_config = WalletConfig::load(datadir)?;
1193+
1194+
let config = match load_config {
1195+
Some(c) if !c.wallets.is_empty() => c,
1196+
_ => {
1197+
return Ok(if pretty {
1198+
"No wallet configurations found.".to_string()
1199+
} else {
1200+
serde_json::to_string_pretty(&json!({
1201+
"wallets": []
1202+
}))?
1203+
});
1204+
}
1205+
};
1206+
1207+
if pretty {
1208+
let mut rows: Vec<Vec<CellStruct>> = vec![];
1209+
1210+
for (name, wallet_config) in config.wallets.iter() {
1211+
let mut row = vec![name.cell(), wallet_config.network.clone().cell()];
1212+
1213+
#[cfg(any(feature = "sqlite", feature = "redb"))]
1214+
row.push(wallet_config.database_type.clone().cell());
1215+
1216+
#[cfg(any(
1217+
feature = "electrum",
1218+
feature = "esplora",
1219+
feature = "rpc",
1220+
feature = "cbf"
1221+
))]
1222+
{
1223+
let client_str = wallet_config.client_type.as_deref().unwrap_or("N/A");
1224+
row.push(client_str.cell());
1225+
}
1226+
1227+
#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
1228+
{
1229+
let url_str = wallet_config.server_url.as_deref().unwrap_or("N/A");
1230+
let display_url = if url_str.len() > 20 {
1231+
shorten(url_str, 15, 10)
1232+
} else {
1233+
url_str.to_string()
1234+
};
1235+
row.push(display_url.cell());
1236+
}
1237+
1238+
let ext_desc_display = if wallet_config.ext_descriptor.len() > 40 {
1239+
shorten(&wallet_config.ext_descriptor, 20, 15)
1240+
} else {
1241+
wallet_config.ext_descriptor.clone()
1242+
};
1243+
row.push(ext_desc_display.cell());
1244+
1245+
let has_int_desc = if wallet_config.int_descriptor.is_some() {
1246+
"Yes"
1247+
} else {
1248+
"No"
1249+
};
1250+
row.push(has_int_desc.cell());
1251+
1252+
rows.push(row);
1253+
}
1254+
1255+
let mut title_cells = vec!["Wallet Name".cell().bold(true), "Network".cell().bold(true)];
1256+
1257+
#[cfg(any(feature = "sqlite", feature = "redb"))]
1258+
title_cells.push("Database".cell().bold(true));
1259+
1260+
#[cfg(any(
1261+
feature = "electrum",
1262+
feature = "esplora",
1263+
feature = "rpc",
1264+
feature = "cbf"
1265+
))]
1266+
title_cells.push("Client".cell().bold(true));
1267+
1268+
#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
1269+
title_cells.push("Server URL".cell().bold(true));
1270+
1271+
title_cells.push("External Desc".cell().bold(true));
1272+
title_cells.push("Internal Desc".cell().bold(true));
1273+
1274+
let table = rows
1275+
.table()
1276+
.title(title_cells)
1277+
.display()
1278+
.map_err(|e| Error::Generic(e.to_string()))?;
1279+
1280+
Ok(format!("{table}"))
1281+
} else {
1282+
let wallets_summary: Vec<_> = config
1283+
.wallets
1284+
.iter()
1285+
.map(|(name, wallet_config)| {
1286+
let mut wallet_json = json!({
1287+
"name": name,
1288+
"network": wallet_config.network,
1289+
"ext_descriptor": wallet_config.ext_descriptor,
1290+
"int_descriptor": wallet_config.int_descriptor,
1291+
});
1292+
1293+
#[cfg(any(feature = "sqlite", feature = "redb"))]
1294+
{
1295+
wallet_json["database_type"] = json!(wallet_config.database_type.clone());
1296+
}
1297+
1298+
#[cfg(any(
1299+
feature = "electrum",
1300+
feature = "esplora",
1301+
feature = "rpc",
1302+
feature = "cbf"
1303+
))]
1304+
{
1305+
wallet_json["client_type"] = json!(wallet_config.client_type.clone());
1306+
}
1307+
1308+
#[cfg(any(feature = "electrum", feature = "esplora", feature = "rpc"))]
1309+
{
1310+
wallet_json["server_url"] = json!(wallet_config.server_url.clone());
1311+
}
1312+
1313+
wallet_json
1314+
})
1315+
.collect();
1316+
1317+
Ok(serde_json::to_string_pretty(&json!({
1318+
"wallets": wallets_summary
1319+
}))?)
1320+
}
1321+
}
1322+
11631323
/// The global top level handler.
11641324
pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
1165-
let network = cli_opts.network;
11661325
let pretty = cli_opts.pretty;
11671326
let subcommand = cli_opts.subcommand.clone();
11681327

@@ -1179,9 +1338,8 @@ pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
11791338
} => {
11801339
let home_dir = prepare_home_dir(cli_opts.datadir)?;
11811340

1182-
let config = WalletConfig::load(&home_dir)?
1183-
.ok_or(Error::Generic("No config found".to_string()))?;
1184-
let wallet_opts = config.get_wallet_opts(&wallet)?;
1341+
let (wallet_opts, network) = load_wallet_config(&home_dir, &wallet)?;
1342+
11851343
let database_path = prepare_wallet_db_dir(&home_dir, &wallet)?;
11861344

11871345
#[cfg(any(feature = "sqlite", feature = "redb"))]
@@ -1237,13 +1395,10 @@ pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
12371395
wallet: wallet_name,
12381396
subcommand: WalletSubCommand::OfflineWalletSubCommand(offline_subcommand),
12391397
} => {
1240-
let network = cli_opts.network;
12411398
let datadir = cli_opts.datadir.clone();
12421399
let home_dir = prepare_home_dir(datadir)?;
1243-
let config = WalletConfig::load(&home_dir)?.ok_or(Error::Generic(format!(
1244-
"No config found for wallet '{wallet_name}'"
1245-
)))?;
1246-
let wallet_opts = config.get_wallet_opts(&wallet_name)?;
1400+
let (wallet_opts, network) = load_wallet_config(&home_dir, &wallet_name)?;
1401+
12471402
#[cfg(any(feature = "sqlite", feature = "redb"))]
12481403
let result = {
12491404
let mut persister: Persister = match &wallet_opts.database_type {
@@ -1298,9 +1453,15 @@ pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
12981453
let result = handle_config_subcommand(&home_dir, network, wallet, &wallet_opts, force)?;
12991454
Ok(result)
13001455
}
1456+
CliSubCommand::Wallets => {
1457+
let home_dir = prepare_home_dir(cli_opts.datadir)?;
1458+
let result = handle_wallets_subcommand(&home_dir, pretty)?;
1459+
Ok(result)
1460+
}
13011461
CliSubCommand::Key {
13021462
subcommand: key_subcommand,
13031463
} => {
1464+
let network = cli_opts.network;
13041465
let result = handle_key_subcommand(network, key_subcommand, pretty)?;
13051466
Ok(result)
13061467
}
@@ -1309,27 +1470,20 @@ pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
13091470
policy,
13101471
script_type,
13111472
} => {
1473+
let network = cli_opts.network;
13121474
let result = handle_compile_subcommand(network, policy, script_type, pretty)?;
13131475
Ok(result)
13141476
}
13151477
#[cfg(feature = "repl")]
13161478
CliSubCommand::Repl {
13171479
wallet: wallet_name,
1318-
mut wallet_opts,
13191480
} => {
1320-
let network = cli_opts.network;
13211481
let home_dir = prepare_home_dir(cli_opts.datadir.clone())?;
1322-
wallet_opts.wallet = Some(wallet_name.clone());
1323-
1324-
let config = WalletConfig::load(&home_dir)?.ok_or(Error::Generic(format!(
1325-
"No config found for wallet {}",
1326-
wallet_name.clone()
1327-
)))?;
1328-
let loaded_wallet_opts = config.get_wallet_opts(&wallet_name)?;
1482+
let (wallet_opts, network) = load_wallet_config(&home_dir, &wallet_name)?;
13291483

13301484
#[cfg(any(feature = "sqlite", feature = "redb"))]
13311485
let (mut wallet, mut persister) = {
1332-
let mut persister: Persister = match &loaded_wallet_opts.database_type {
1486+
let mut persister: Persister = match &wallet_opts.database_type {
13331487
#[cfg(feature = "sqlite")]
13341488
DatabaseType::Sqlite => {
13351489
let database_path = prepare_wallet_db_dir(&home_dir, &wallet_name)?;
@@ -1348,7 +1502,7 @@ pub(crate) async fn handle_command(cli_opts: CliOpts) -> Result<String, Error> {
13481502
Persister::RedbStore(store)
13491503
}
13501504
};
1351-
let wallet = new_persisted_wallet(network, &mut persister, &loaded_wallet_opts)?;
1505+
let wallet = new_persisted_wallet(network, &mut persister, &wallet_opts)?;
13521506
(wallet, persister)
13531507
};
13541508
#[cfg(not(any(feature = "sqlite", feature = "redb")))]

0 commit comments

Comments
 (0)