Skip to main content

bark_cli/
wallet.rs

1//! Wallet utilities
2//!
3//! Opens a Bark wallet and its on-chain companion from a data directory.
4//!
5//! ## Behavior
6//! - Reads a BIP-39 `mnemonic` file from the provided directory
7//! - Parses `config.toml` into a [`bark::Config`]
8//! - Opens `db.sqlite` as a [`bark::persist::sqlite::SqliteClient`] and loads persisted properties
9//! - Loads or creates the [`bark::onchain::OnchainWallet`], wraps it in
10//!   `Arc<RwLock<_>>`, and stores it inside the [`bark::Wallet`] via
11//!   [`bark::OpenWalletArgs::onchain`] - BDK-specific methods are accessed
12//!   via downcasting through [`bark::Wallet::onchain`]
13//! ## Errors
14//! Returns an [`anyhow::Error`] with context describing the failing step (I/O, parsing,
15//! database access, or wallet initialization).
16//!
17//! ## Example
18//! Open a wallet from a data directory:
19//!
20//! ```rust,no_run
21//! # use std::path::Path;
22//! # use bark_cli::wallet::open_wallet;
23//! # async fn example() -> anyhow::Result<()> {
24//!     let datadir = Path::new("./bark_data");
25//!     let bark_wallet = open_wallet(datadir, "myapp/1.0").await?.unwrap();
26//!     // Use the wallet...
27//!     Ok(())
28//! # }
29//! ```
30
31use std::fs;
32use std::path::Path;
33use std::sync::Arc;
34use std::str::FromStr;
35
36use anyhow::{Context, bail};
37use bark::chain::ChainSource;
38use bark::fs_perms;
39use bark::persist::adaptor::StorageAdaptorWrapper;
40use bitcoin::Network;
41use clap::Args;
42use log::{debug, info, warn};
43use tonic::transport::Uri;
44
45use bark::{BarkNetwork, Config, OpenWalletArgs, Wallet as BarkWallet, WalletSeed};
46use bark::lock_manager::{self, LockManager, PidLockError};
47use bark::lock_manager::pid_flock::LOCK_FILE;
48use bark::onchain::OnchainWallet;
49use bark::persist::BarkPersister;
50use bark::persist::sqlite::{SqliteClient, DEFAULT_DB_FILE};
51use bark::persist::adaptor::filestore::FileStorageAdaptor;
52
53use bitcoin_ext::BlockHeight;
54
55use crate::connection::{self, BARKD_LOCK_FILE, BARKD_URL_FILE};
56use crate::util;
57
58/// File name of the mnemonic file.
59const MNEMONIC_FILE: &str = "mnemonic";
60
61/// File name of the database file.
62const DB_FILE: &str = DEFAULT_DB_FILE;
63/// File name of the filestore database file.
64const FILESTORE_FILE: &str = "wallet.json";
65
66/// File name of the config file.
67const CONFIG_FILE: &str = "config.toml";
68
69/// File name of the debug log file.
70const DEBUG_LOG_FILE: &str = "debug.log";
71
72/// File name used to persist the auth token in the datadir.
73pub const AUTH_TOKEN_FILE: &str = "auth_token";
74
75/// Process log files that may be written into the datadir by the daemon
76/// framework during testing; they should be ignored like debug.log.
77const STDOUT_LOG_FILE: &str = "stdout.log";
78const STDERR_LOG_FILE: &str = "stderr.log";
79
80/// Take the datadir lock via [`lock_manager::platform_default`], surfacing
81/// the "already held" case as-is so the CLI prints a clean error.
82fn open_lock_manager(datadir: &Path) -> anyhow::Result<Box<dyn LockManager>> {
83	match lock_manager::platform_default(Some(datadir), None) {
84		Ok(m) => Ok(m),
85		Err(e) if e.is::<PidLockError>() => Err(e),
86		Err(e) => Err(e.context("failed to acquire datadir lock")),
87	}
88}
89
90/// Options to define the initial bark config
91#[derive(Clone, PartialEq, Eq, Default, clap::Args)]
92pub struct ConfigOpts {
93	/// The address of your Ark server.
94	#[arg(long)]
95	pub ark: Option<String>,
96
97	/// [DEPRECATED] The access token for a private server.
98	/// Access tokens are no longer enforced by the server; this flag will be removed.
99	#[arg(long, hide = true)]
100	pub access_token: Option<String>,
101
102	/// The address of the Esplora HTTP server to use.
103	///
104	/// Either this or the `bitcoind_address` field has to be provided.
105	#[arg(long)]
106	pub esplora: Option<String>,
107
108	/// The address of the bitcoind RPC server to use.
109	///
110	/// Either this or the `esplora_address` field has to be provided.
111	#[arg(long)]
112	pub bitcoind: Option<String>,
113
114	/// The path to the bitcoind rpc cookie file.
115	///
116	/// Only used with `bitcoind_address`.
117	#[arg(long)]
118	pub bitcoind_cookie: Option<String>,
119
120	/// The bitcoind RPC username.
121	///
122	/// Only used with `bitcoind_address`.
123	#[arg(long)]
124	pub bitcoind_user: Option<String>,
125
126	/// The bitcoind RPC password.
127	///
128	/// Only used with `bitcoind_address`.
129	#[arg(long)]
130	pub bitcoind_pass: Option<String>,
131
132	/// SOCKS5 proxy URL (e.g. socks5h://127.0.0.1:9050 for Tor).
133	/// Automatically bypassed for localhost connections.
134	#[arg(long)]
135	pub socks5_proxy: Option<String>,
136
137	/// How many consecutive unused key indices a VTXO key scan may cross before
138	/// it concludes the wallet doesn't own a recovered/imported VTXO.
139	#[arg(long)]
140	pub gap_limit: Option<u32>,
141}
142
143impl ConfigOpts {
144	/// Fill the default required config fields based on network
145	pub fn fill_network_defaults(&mut self, net: BarkNetwork) {
146		// Fallback to our default mainnet
147		if net == BarkNetwork::Mainnet {
148			// Only do it when the user did *not* specify either --esplora or --bitcoind.
149			if self.esplora.is_none() && self.bitcoind.is_none() {
150				self.esplora = Some("https://mempool.second.tech/api".to_owned());
151			}
152
153			if self.ark.is_none() {
154				self.ark = Some("https://ark.second.tech/".to_owned());
155			}
156		}
157
158		// Fallback to our default signet
159		if net == BarkNetwork::Signet {
160			// Only do it when the user did *not* specify either --esplora or --bitcoind.
161			if self.esplora.is_none() && self.bitcoind.is_none() {
162				self.esplora = Some("https://esplora.signet.2nd.dev/".to_owned());
163			}
164
165			if self.ark.is_none() {
166				self.ark = Some("https://ark.signet.2nd.dev/".to_owned());
167			}
168		}
169
170		// Fallback to Mutinynet community Esplora
171		// Only do it when the user did *not* specify either --esplora or --bitcoind.
172		if net == BarkNetwork::Mutinynet && self.esplora.is_none() && self.bitcoind.is_none() {
173			self.esplora = Some("https://mutinynet.com/api".to_owned());
174		}
175	}
176
177	/// Validate the config options are sane
178	fn validate(&self) -> anyhow::Result<()> {
179		if self.esplora.is_none() && self.bitcoind.is_none() {
180			bail!("You need to provide a chain source using either --esplora or --bitcoind");
181		}
182
183		match (
184			self.bitcoind.is_some(),
185			self.bitcoind_cookie.is_some(),
186			self.bitcoind_user.is_some(),
187			self.bitcoind_pass.is_some(),
188		) {
189			(false, false, false, false) => {},
190			(false, _, _, _) => bail!("Provided bitcoind auth args without bitcoind address"),
191			(_, true, false, false) => {},
192			(_, true, _, _) => bail!("Bitcoind user/pass shouldn't be provided together with cookie file"),
193			(_, _, true, true) => {},
194			_ => bail!("When providing --bitcoind, you need to provide auth args as well."),
195		}
196
197		if let Some(gap_limit) = self.gap_limit {
198			if gap_limit > bark::MAX_VTXO_KEY_GAP_LIMIT {
199				bail!("--gap-limit {} is above the maximum of {}",
200					gap_limit, bark::MAX_VTXO_KEY_GAP_LIMIT);
201			}
202		}
203
204		if let Some(ref proxy) = self.socks5_proxy {
205			let uri = proxy.parse::<Uri>().context("invalid socks5 proxy URI")?;
206			let scheme = uri.scheme_str().context("invalid socks5 proxy URI scheme")?;
207			if scheme != "socks5h" {
208				bail!("Only socks5h:// proxies are supported");
209			}
210		}
211
212		Ok(())
213	}
214
215	/// Will write the provided config options to the config
216	///
217	/// Will also load and return the config when loaded from the written file.
218	fn write_to_file(&self, network: Network, path: impl AsRef<Path>) -> anyhow::Result<Config> {
219		use std::fmt::Write;
220
221		let mut conf = String::new();
222		let ark = util::default_scheme("https", self.ark.as_ref().context("missing --ark arg")?)
223			.context("invalid ark server URL")?;
224		writeln!(conf, "server_address = \"{}\"", ark).unwrap();
225
226		if let Some(ref v) = self.access_token {
227			writeln!(conf, "server_access_token = \"{}\"", v).unwrap();
228		}
229		if let Some(ref v) = self.esplora {
230			let url = util::default_scheme("https", v).context("invalid esplora URL")?;
231			writeln!(conf, "esplora_address = \"{}\"", url).unwrap();
232		}
233		if let Some(ref v) = self.bitcoind {
234			let url = util::default_scheme("http", v).context("invalid bitcoind URL")?;
235			writeln!(conf, "bitcoind_address = \"{}\"", url).unwrap();
236		}
237		if let Some(ref v) = self.bitcoind_cookie {
238			writeln!(conf, "bitcoind_cookiefile = \"{}\"", v).unwrap();
239		}
240		if let Some(ref v) = self.bitcoind_user {
241			writeln!(conf, "bitcoind_user = \"{}\"", v).unwrap();
242		}
243		if let Some(ref v) = self.bitcoind_pass {
244			writeln!(conf, "bitcoind_pass = \"{}\"", v).unwrap();
245		}
246		if let Some(ref v) = self.socks5_proxy {
247			writeln!(conf, "socks5_proxy = \"{}\"", v).unwrap();
248		}
249		if let Some(v) = self.gap_limit {
250			writeln!(conf, "vtxo_key_gap_limit = {}", v).unwrap();
251		}
252
253		let path = path.as_ref();
254
255		fs_perms::write_atomic_owner_only(path, conf.as_bytes())?;
256
257		// new let's try load it to make sure it's sane
258		Ok(Config::load(network, path).context("problematic config flags provided")?)
259	}
260}
261
262#[derive(Args)]
263pub struct CreateOpts {
264	/// Force re-create the wallet even if it already exists.
265	/// Any funds in the old wallet will be lost
266	#[arg(long)]
267	pub force: bool,
268
269	/// Use filestore (JSON file) persistence instead of SQLite.
270	/// This creates a marker file so subsequent commands use the same backend.
271	///
272	/// Warning: do not use this for a production wallet.
273	#[arg(long)]
274	pub use_filestore: bool,
275
276	/// Use bitcoin mainnet
277	#[arg(long)]
278	pub mainnet: bool,
279	/// Use regtest network
280	#[arg(long)]
281	pub regtest: bool,
282	/// Use the official signet network
283	#[arg(long)]
284	pub signet: bool,
285	/// Use mutinynet
286	#[arg(long)]
287	pub mutinynet: bool,
288
289	/// Recover a wallet with an existing mnemonic.
290	/// This currently only works for on-chain funds.
291	#[arg(long)]
292	pub mnemonic: Option<bip39::Mnemonic>,
293
294	/// The wallet/mnemonic's birthday blockheight to start syncing when recovering.
295	#[arg(long)]
296	pub birthday_height: Option<BlockHeight>,
297
298	#[command(flatten)]
299	pub config: ConfigOpts,
300}
301
302/// Non-wallet files barkd leaves in the datadir; they must survive a wallet create.
303const EXPECTED_DATADIR_FILES: [&str; 7] = [
304	DEBUG_LOG_FILE,
305	STDOUT_LOG_FILE,
306	STDERR_LOG_FILE,
307	LOCK_FILE,
308	AUTH_TOKEN_FILE,
309	BARKD_LOCK_FILE,
310	BARKD_URL_FILE,
311];
312
313/// Whether `name` is an expected datadir file or an atomic-write temp
314/// sibling of one (`.<name>.temp.<nanos>.<n>.tmp`).
315fn is_expected_datadir_file(name: &str) -> bool {
316	EXPECTED_DATADIR_FILES.iter().chain(&[CONFIG_FILE]).any(|expected| {
317		name == *expected || name.strip_prefix('.')
318			.and_then(|s| s.strip_prefix(expected))
319			.and_then(|s| s.strip_prefix(".temp."))
320			.is_some_and(|s| s.ends_with(".tmp"))
321	})
322}
323
324/// Checks the config file and maybe cleans it
325/// - returns whether a config file was present
326/// - if clean is false, errors if any file not config or logs is present
327/// - if clean is true, removes all files not config or logs
328async fn check_clean_datadir(datadir: &Path, clean: bool) -> anyhow::Result<bool> {
329	let mut has_config = false;
330	if datadir.exists() {
331		for item in datadir.read_dir().context("error accessing datadir")? {
332			let item = item.context("error reading existing content of datadir")?;
333
334			if item.file_name() == CONFIG_FILE {
335				has_config = true;
336				continue;
337			}
338			if is_expected_datadir_file(&item.file_name().to_string_lossy()) {
339				continue;
340			}
341
342			if !clean {
343				bail!("Datadir has unexpected contents: {}", item.path().display());
344			}
345
346			// otherwise try wipe
347			let file_type = item.file_type().context("error accessing datadir content")?;
348			if file_type.is_dir() {
349				tokio::fs::remove_dir_all(item.path()).await.context("error deleting datadir content")?;
350			} else if file_type.is_file() || file_type.is_symlink() {
351				tokio::fs::remove_file(item.path()).await.context("error deleting datadir content")?;
352			} else {
353				// can't happen
354				bail!("non-existent file type in ");
355			}
356		}
357	}
358	Ok(has_config)
359}
360
361pub async fn create_wallet(
362	datadir: &Path,
363	user_agent: &str,
364	opts: CreateOpts,
365) -> anyhow::Result<()> {
366	debug!("Creating wallet in {}", datadir.display());
367
368	let net = match (opts.mainnet, opts.signet, opts.regtest, opts.mutinynet) {
369		(true,  false, false, false) => BarkNetwork::Mainnet,
370		(false, true,  false, false) => BarkNetwork::Signet,
371		(false, false, true,  false) => BarkNetwork::Regtest,
372		(false, false, false, true ) => BarkNetwork::Mutinynet,
373		_ => bail!("Specify exactly one of --mainnet, --signet, --regtest or --mutinynet"),
374	};
375
376	// check for non-config file contents in the datadir and wipe if force
377	let config_existed = check_clean_datadir(datadir, opts.force).await?;
378
379	// Everything that errors after this will wipe the datadir again.
380	let result = try_create_wallet(datadir, net, user_agent, opts).await;
381	if let Err(e) = result {
382		if config_existed {
383			if let Err(e) = check_clean_datadir(datadir, true).await {
384				warn!("Error cleaning datadir after failure: {:#}", e);
385			}
386		} else {
387			// A barkd serving this datadir must keep its lock and auth
388			// token; drop the datadir itself only when nothing is left.
389			if let Err(e) = connection::wipe_datadir_except_barkd_files(datadir) {
390				warn!("Error cleaning datadir after failure: {:#}", e);
391			}
392			let _ = fs::remove_dir(datadir);
393		}
394
395		bail!("Error while creating wallet: {:#}", e);
396	}
397	Ok(())
398}
399
400/// In this method we create the wallet and if it fails, the datadir will be wiped again.
401async fn try_create_wallet(
402	datadir: &Path,
403	net: BarkNetwork,
404	user_agent: &str,
405	mut opts: CreateOpts,
406) -> anyhow::Result<()> {
407	info!("Creating new bark Wallet at {}", datadir.display());
408
409	tokio::fs::create_dir_all(datadir).await.context("can't create dir")?;
410
411	fs_perms::harden(datadir, 0o700)?;
412
413	let config_path = datadir.join(CONFIG_FILE);
414	let has_config_args = opts.config != ConfigOpts::default();
415	let mut config = match (config_path.exists(), has_config_args) {
416		(true, false) => {
417			Config::load(net.as_bitcoin(), &config_path).with_context(|| format!(
418				"error loading existing config file at {}", config_path.display(),
419			))?
420		},
421		// Without config args the network defaults alone can suffice;
422		// validate rejects networks that lack a default chain source
423		// (e.g. regtest).
424		(false, _) => {
425			opts.config.fill_network_defaults(net);
426			opts.config.validate().context("invalid config options")?;
427			opts.config.write_to_file(net.as_bitcoin(), config_path)?
428		},
429		(true, true) => bail!("Cannot provide an existing config file and config flags"),
430	};
431
432	// Default the wire-level client identity to the calling binary unless the
433	// operator pinned one in config.toml.
434	if config.user_agent.is_none() {
435		config.user_agent = Some(user_agent.to_owned());
436	}
437
438	// A mnemonic implies that the user wishes to recover an existing wallet.
439	if opts.mnemonic.is_some() {
440		if opts.birthday_height.is_none() {
441			// Only Bitcoin Core requires a birthday height to avoid syncing the entire chain.
442			if config.bitcoind_address.is_some() {
443				bail!("You need to set the --birthday-height field when recovering from mnemonic.");
444			}
445		} else if config.esplora_address.is_some() {
446			warn!("The given --birthday-height will be ignored because you're using Esplora.");
447		}
448	} else {
449		if opts.birthday_height.is_some() {
450			bail!("Can't set --birthday-height if --mnemonic is not set.");
451		}
452	}
453
454	// chain source client
455	let chain_spec = config.chain_source()
456		.context("failed to create a chain source client with the config")?;
457	let chain = ChainSource::new(chain_spec, net.as_bitcoin(), None, None).await
458		.context("failed to create a chain source client with the config")?;
459	chain.require_version().await.context("chain source version check failed")?;
460
461	// generate seed
462	let is_new_wallet = opts.mnemonic.is_none();
463	let mnemonic = opts.mnemonic.unwrap_or_else(|| bip39::Mnemonic::generate(12).expect("12 is valid"));
464	let seed = mnemonic.to_seed("");
465
466	fs_perms::create_new_owner_only(
467		&datadir.join(MNEMONIC_FILE), mnemonic.to_string().as_bytes(),
468	)?;
469
470	// open db
471	let db: Arc<dyn BarkPersister + Send + Sync> = if opts.use_filestore {
472		debug!("Using filestore backend");
473		let adaptor = FileStorageAdaptor::open(datadir.join(FILESTORE_FILE)).await?;
474		Arc::new(StorageAdaptorWrapper::new(adaptor))
475	} else {
476		debug!("Using sqlite backend");
477		let db = SqliteClient::open(datadir.join(DB_FILE))?;
478		fs_perms::harden(&datadir.join(DB_FILE), 0o600)?;
479		Arc::new(db)
480	};
481
482	let mut onchain = OnchainWallet::load_or_create(net.as_bitcoin(), seed, db.clone()).await?;
483	let lock_manager = open_lock_manager(&datadir)?;
484
485	// Skip initial block sync if we generated a new wallet.
486	let birthday_height = if is_new_wallet {
487		Some(chain.tip().await?)
488	} else {
489		opts.birthday_height
490	};
491	onchain.initial_wallet_scan(&chain, birthday_height).await?;
492
493	// Create the wallet by opening with `create_if_not_exists` rather than
494	// calling `Wallet::create` directly: opening is what runs seed recovery, so
495	// a wallet restored from a mnemonic rebuilds its spendable VTXO set from the
496	// recovery mailbox. The on-chain scan above has already run, so recovery can
497	// validate recovered VTXOs against their chain anchors. `run_daemon` stays
498	// off - this only needs to create and recover.
499	BarkWallet::open(
500		net.as_bitcoin(),
501		WalletSeed::new_from_mnemonic(net.as_bitcoin(), &mnemonic),
502		config,
503		OpenWalletArgs {
504			persister: Some(db),
505			lock_manager: Some(lock_manager),
506			create_if_not_exists: true,
507			create_without_server: opts.force,
508			run_daemon: false,
509			..Default::default()
510		},
511	).await.context("error creating wallet")?;
512	Ok(())
513}
514
515/// Read the raw mnemonic phrase from the wallet datadir.
516pub async fn read_mnemonic(datadir: &Path) -> anyhow::Result<String> {
517	let path = datadir.join(MNEMONIC_FILE);
518	let s = tokio::fs::read_to_string(&path).await
519		.with_context(|| format!("failed to read mnemonic file at {}", path.display()))?;
520	Ok(s.trim().to_string())
521}
522
523pub async fn open_wallet(datadir: &Path, user_agent: &str) -> anyhow::Result<Option<BarkWallet>> {
524	debug!("Opening bark wallet in {}", datadir.display());
525
526	// read mnemonic file
527	let mnemonic_path = datadir.join(MNEMONIC_FILE);
528
529	if !tokio::fs::try_exists(datadir).await? {
530		return Ok(None);
531	}
532
533	if !tokio::fs::try_exists(&mnemonic_path).await? {
534		return Ok(None);
535	}
536
537	// The backend db (sqlite or filestore) is checked by its adaptor on open.
538	fs_perms::warn_if_loose(datadir, 0o700);
539	fs_perms::warn_if_loose(&mnemonic_path, 0o600);
540	fs_perms::warn_if_loose(&datadir.join(CONFIG_FILE), 0o600);
541
542	let mnemonic_str = tokio::fs::read_to_string(&mnemonic_path).await
543		.with_context(|| format!("failed to read mnemonic file at {}", mnemonic_path.display()))?;
544	let mnemonic = bip39::Mnemonic::from_str(&mnemonic_str).context("broken mnemonic")?;
545	let seed = mnemonic.to_seed("");
546
547	let use_filestore = datadir.join(FILESTORE_FILE).exists();
548	let db: Arc<dyn BarkPersister + Send + Sync> = if use_filestore {
549		debug!("Using filestore backend");
550		let adaptor = FileStorageAdaptor::open(datadir.join(FILESTORE_FILE)).await?;
551		Arc::new(StorageAdaptorWrapper::new(adaptor))
552	} else {
553		debug!("Using sqlite backend");
554		Arc::new(SqliteClient::open(datadir.join(DB_FILE))?)
555	};
556	let properties = db.read_properties().await?.context("failed to read properties")?;
557
558	// Read the config
559	let config_path = datadir.join("config.toml");
560	let mut config = Config::load(properties.network, config_path)
561		.context("error loading bark config file")?;
562
563	// Default the wire-level client identity to the calling binary unless the
564	// operator pinned one in config.toml.
565	if config.user_agent.is_none() {
566		config.user_agent = Some(user_agent.to_owned());
567	}
568
569	let bdk_wallet = OnchainWallet::load_or_create(properties.network, seed, db.clone()).await?;
570	let onchain = Arc::new(tokio::sync::RwLock::new(bdk_wallet));
571	let lock_manager = open_lock_manager(datadir)?;
572	let bark_wallet = BarkWallet::open(
573		properties.network,
574		WalletSeed::new_from_mnemonic(properties.network, &mnemonic),
575		config,
576		OpenWalletArgs {
577			persister: Some(db),
578			lock_manager: Some(lock_manager),
579			onchain: Some(onchain.clone()),
580			run_daemon: false,
581			..Default::default()
582		},
583	).await?;
584
585	Ok(Some(bark_wallet))
586}
587
588#[cfg(test)]
589mod test {
590	use super::*;
591
592	fn tmp_dir() -> std::path::PathBuf {
593		let dir = std::env::temp_dir()
594			.join(format!("bark-wallet-{}", std::process::id()))
595			.join(format!("{}", std::time::SystemTime::now()
596				.duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
597		fs::create_dir_all(&dir).unwrap();
598		dir
599	}
600
601	/// Options that fail wallet creation with "provide config flags or a
602	/// config file", after the datadir checks.
603	fn failing_create_opts() -> CreateOpts {
604		CreateOpts {
605			force: false,
606			use_filestore: false,
607			mainnet: false,
608			regtest: false,
609			signet: true,
610			mutinynet: false,
611			mnemonic: None,
612			birthday_height: None,
613			config: ConfigOpts::default(),
614		}
615	}
616
617	/// --gap-limit is config, not a one-shot: it must land in config.toml so
618	/// later commands (imports, a re-created wallet) see the same limit.
619	#[test]
620	fn gap_limit_is_written_to_config() {
621		let dir = tmp_dir();
622		let path = dir.join(CONFIG_FILE);
623		let opts = ConfigOpts {
624			ark: Some("http://127.0.0.1:3535".into()),
625			esplora: Some("http://127.0.0.1:3002".into()),
626			gap_limit: Some(10_000),
627			..ConfigOpts::default()
628		};
629
630		let config = opts.write_to_file(Network::Signet, &path)
631			.expect("writing the config should succeed");
632
633		assert_eq!(config.vtxo_key_gap_limit, 10_000, "the written config should carry the limit");
634		let written = fs::read_to_string(&path).expect("config file should exist");
635		assert!(written.contains("vtxo_key_gap_limit = 10000"), "unexpected config: {written}");
636
637		// Omitting the flag leaves the network default in place.
638		let bare_path = dir.join("bare.toml");
639		let bare = ConfigOpts { gap_limit: None, ..opts }
640			.write_to_file(Network::Signet, &bare_path)
641			.expect("writing the config should succeed");
642		assert_eq!(bare.vtxo_key_gap_limit, bark::DEFAULT_VTXO_KEY_GAP_LIMIT,
643			"without the flag the default should stand");
644	}
645
646	#[tokio::test]
647	async fn failed_create_keeps_barkd_files() {
648		let dir = tmp_dir();
649		fs::write(dir.join(AUTH_TOKEN_FILE), "tok").unwrap();
650		fs::write(dir.join(BARKD_LOCK_FILE), "42").unwrap();
651
652		create_wallet(&dir, "test", failing_create_opts()).await.unwrap_err();
653
654		assert!(dir.join(AUTH_TOKEN_FILE).exists());
655		assert!(dir.join(BARKD_LOCK_FILE).exists());
656
657		let _ = fs::remove_dir_all(&dir);
658	}
659
660	#[tokio::test]
661	async fn failed_create_removes_empty_datadir() {
662		let dir = tmp_dir();
663
664		create_wallet(&dir, "test", failing_create_opts()).await.unwrap_err();
665
666		assert!(!dir.exists());
667	}
668
669	#[test]
670	fn expected_datadir_files_and_their_temps() {
671		assert!(is_expected_datadir_file("auth_token"));
672		assert!(is_expected_datadir_file("barkd.lock"));
673		assert!(is_expected_datadir_file("barkd.url"));
674		// Atomic-write temp siblings, mid-write or left by a crash.
675		assert!(is_expected_datadir_file(".auth_token.temp.42.3.tmp"));
676		assert!(is_expected_datadir_file(".config.toml.temp.42.0.tmp"));
677
678		assert!(!is_expected_datadir_file("mnemonic"));
679		assert!(!is_expected_datadir_file("db.sqlite"));
680		assert!(!is_expected_datadir_file(".mnemonic.temp.42.0.tmp"));
681		assert!(!is_expected_datadir_file("barkd.lock.bak"));
682	}
683}
684