bark-cli 0.1.1

CLI for the bitcoin Ark protocol built by Second
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Wallet utilities
//!
//! Opens a Bark wallet and its on-chain companion from a data directory.
//!
//! ## Behavior
//! - Reads a BIP-39 `mnemonic` file from the provided directory
//! - Parses `config.toml` into a [`bark::Config`]
//! - Opens `db.sqlite` as a [`bark::SqliteClient`] and loads persisted properties
//! - Loads or creates the [`bark::onchain::OnchainWallet`]
//! - Opens the [`bark::Wallet`] bound to the on-chain wallet
//! - Returns `(bark::Wallet, bark::onchain::OnchainWallet)`
//!
//! ## Errors
//! Returns an [`anyhow::Error`] with context describing the failing step (I/O, parsing,
//! database access, or wallet initialization).
//!
//! ## Example
//! Open a wallet from a data directory:
//!
//! ```rust,no_run
//! # use std::path::Path;
//! # use bark_cli::wallet::open_wallet;
//! # async fn example() -> anyhow::Result<()> {
//!     let datadir = Path::new("./bark_data");
//!     let (bark_wallet, onchain_wallet) = open_wallet(datadir).await?.unwrap();
//!     // Use the wallets...
//!     Ok(())
//! # }
//! ```

use std::path::Path;
use std::sync::Arc;
use std::str::FromStr;

use anyhow::{Context, bail};
use bark::persist::adaptor::StorageAdaptorWrapper;
use bitcoin::Network;
use clap::Args;
use log::{debug, info, warn};
use tonic::transport::Uri;

use bark::{BarkNetwork, Config, Wallet as BarkWallet};
use bark::onchain::OnchainWallet;
use bark::persist::BarkPersister;
use bark::pid_lock::LOCK_FILE;
use bark::persist::sqlite::SqliteClient;
use bark::persist::adaptor::filestore::FileStorageAdaptor;

use bitcoin_ext::BlockHeight;

use crate::util;

/// File name of the mnemonic file.
const MNEMONIC_FILE: &str = "mnemonic";

/// File name of the database file.
const DB_FILE: &str = "db.sqlite";
/// File name of the filestore database file.
const FILESTORE_FILE: &str = "wallet.json";

/// File name of the config file.
const CONFIG_FILE: &str = "config.toml";

/// File name of the debug log file.
const DEBUG_LOG_FILE: &str = "debug.log";

/// File name used to persist the auth token in the datadir.
pub const AUTH_TOKEN_FILE: &str = "auth_token";

/// Process log files that may be written into the datadir by the daemon
/// framework during testing; they should be ignored like debug.log.
const STDOUT_LOG_FILE: &str = "stdout.log";
const STDERR_LOG_FILE: &str = "stderr.log";

/// Options to define the initial bark config
#[derive(Clone, PartialEq, Eq, Default, clap::Args)]
pub struct ConfigOpts {
	/// The address of your Ark server.
	#[arg(long)]
	pub ark: Option<String>,

	/// The address of the Esplora HTTP server to use.
	///
	/// Either this or the `bitcoind_address` field has to be provided.
	#[arg(long)]
	pub esplora: Option<String>,

	/// The address of the bitcoind RPC server to use.
	///
	/// Either this or the `esplora_address` field has to be provided.
	#[arg(long)]
	pub bitcoind: Option<String>,

	/// The path to the bitcoind rpc cookie file.
	///
	/// Only used with `bitcoind_address`.
	#[arg(long)]
	pub bitcoind_cookie: Option<String>,

	/// The bitcoind RPC username.
	///
	/// Only used with `bitcoind_address`.
	#[arg(long)]
	pub bitcoind_user: Option<String>,

	/// The bitcoind RPC password.
	///
	/// Only used with `bitcoind_address`.
	#[arg(long)]
	pub bitcoind_pass: Option<String>,

	/// SOCKS5 proxy URL (e.g. socks5h://127.0.0.1:9050 for Tor).
	/// Automatically bypassed for localhost connections.
	#[arg(long)]
	pub socks5_proxy: Option<String>,
}

impl ConfigOpts {
	/// Fill the default required config fields based on network
	fn fill_network_defaults(&mut self, net: BarkNetwork) {
		// Fallback to our default mainnet
		if net == BarkNetwork::Mainnet {
			// Only do it when the user did *not* specify either --esplora or --bitcoind.
			if self.esplora.is_none() && self.bitcoind.is_none() {
				self.esplora = Some("https://mempool.second.tech/api".to_owned());
			}
		}

		// Fallback to our default signet
		if net == BarkNetwork::Signet {
			// Only do it when the user did *not* specify either --esplora or --bitcoind.
			if self.esplora.is_none() && self.bitcoind.is_none() {
				self.esplora = Some("https://esplora.signet.2nd.dev/".to_owned());
			}

			if self.ark.is_none() {
				self.ark = Some("https://ark.signet.2nd.dev/".to_owned());
			}
		}

		// Fallback to Mutinynet community Esplora
		// Only do it when the user did *not* specify either --esplora or --bitcoind.
		if net == BarkNetwork::Mutinynet && self.esplora.is_none() && self.bitcoind.is_none() {
			self.esplora = Some("https://mutinynet.com/api".to_owned());
		}
	}

	/// Validate the config options are sane
	fn validate(&self) -> anyhow::Result<()> {
		if self.esplora.is_none() && self.bitcoind.is_none() {
			bail!("You need to provide a chain source using either --esplora or --bitcoind");
		}

		match (
			self.bitcoind.is_some(),
			self.bitcoind_cookie.is_some(),
			self.bitcoind_user.is_some(),
			self.bitcoind_pass.is_some(),
		) {
			(false, false, false, false) => {},
			(false, _, _, _) => bail!("Provided bitcoind auth args without bitcoind address"),
			(_, true, false, false) => {},
			(_, true, _, _) => bail!("Bitcoind user/pass shouldn't be provided together with cookie file"),
			(_, _, true, true) => {},
			_ => bail!("When providing --bitcoind, you need to provide auth args as well."),
		}

		if let Some(ref proxy) = self.socks5_proxy {
			let uri = proxy.parse::<Uri>().context("invalid socks5 proxy URI")?;
			let scheme = uri.scheme_str().context("invalid socks5 proxy URI scheme")?;
			if scheme != "socks5h" {
				bail!("Only socks5h:// proxies are supported");
			}
		}

		Ok(())
	}

	/// Will write the provided config options to the config
	///
	/// Will also load and return the config when loaded from the written file.
	fn write_to_file(&self, network: Network, path: impl AsRef<Path>) -> anyhow::Result<Config> {
		use std::fmt::Write;

		let mut conf = String::new();
		let ark = util::default_scheme("https", self.ark.as_ref().context("missing --ark arg")?)
			.context("invalid ark server URL")?;
		writeln!(conf, "server_address = \"{}\"", ark).unwrap();

		if let Some(ref v) = self.esplora {
			let url = util::default_scheme("https", v).context("invalid esplora URL")?;
			writeln!(conf, "esplora_address = \"{}\"", url).unwrap();
		}
		if let Some(ref v) = self.bitcoind {
			let url = util::default_scheme("http", v).context("invalid bitcoind URL")?;
			writeln!(conf, "bitcoind_address = \"{}\"", url).unwrap();
		}
		if let Some(ref v) = self.bitcoind_cookie {
			writeln!(conf, "bitcoind_cookiefile = \"{}\"", v).unwrap();
		}
		if let Some(ref v) = self.bitcoind_user {
			writeln!(conf, "bitcoind_user = \"{}\"", v).unwrap();
		}
		if let Some(ref v) = self.bitcoind_pass {
			writeln!(conf, "bitcoind_pass = \"{}\"", v).unwrap();
		}
		if let Some(ref v) = self.socks5_proxy {
			writeln!(conf, "socks5_proxy = \"{}\"", v).unwrap();
		}

		let path = path.as_ref();
		std::fs::write(path, conf).with_context(|| format!(
			"error writing new config file to {}", path.display(),
		))?;

		// new let's try load it to make sure it's sane
		Ok(Config::load(network, path).context("problematic config flags provided")?)
	}
}

#[derive(Args)]
pub struct CreateOpts {
	/// Force re-create the wallet even if it already exists.
	/// Any funds in the old wallet will be lost
	#[arg(long)]
	pub force: bool,

	/// Use filestore (JSON file) persistence instead of SQLite.
	/// This creates a marker file so subsequent commands use the same backend.
	///
	/// Warning: do not use this for a production wallet.
	#[arg(long)]
	pub use_filestore: bool,

	/// Use bitcoin mainnet
	#[arg(long)]
	pub mainnet: bool,
	/// Use regtest network
	#[arg(long)]
	pub regtest: bool,
	/// Use the official signet network
	#[arg(long)]
	pub signet: bool,
	/// Use mutinynet
	#[arg(long)]
	pub mutinynet: bool,

	/// Recover a wallet with an existing mnemonic.
	/// This currently only works for on-chain funds.
	#[arg(long)]
	pub mnemonic: Option<bip39::Mnemonic>,

	/// The wallet/mnemonic's birthday blockheight to start syncing when recovering.
	#[arg(long)]
	pub birthday_height: Option<BlockHeight>,

	#[command(flatten)]
	pub config: ConfigOpts,
}

/// Checks the config file and maybe cleans it
/// - returns whether a config file was present
/// - if clean is false, errors if any file not config or logs is present
/// - if clean is true, removes all files not config or logs
async fn check_clean_datadir(datadir: &Path, clean: bool) -> anyhow::Result<bool> {
	let mut has_config = false;
	if datadir.exists() {
		for item in datadir.read_dir().context("error accessing datadir")? {
			let item = item.context("error reading existing content of datadir")?;

			if item.file_name() == CONFIG_FILE {
				has_config = true;
				continue;
			}
			if item.file_name() == DEBUG_LOG_FILE
				|| item.file_name() == STDOUT_LOG_FILE
				|| item.file_name() == STDERR_LOG_FILE
			{
				continue;
			}
			if item.file_name() == LOCK_FILE {
				continue;
			}
			if item.file_name() == AUTH_TOKEN_FILE {
				continue;
			}

			if !clean {
				bail!("Datadir has unexpected contents: {}", item.path().display());
			}

			// otherwise try wipe
			let file_type = item.file_type().context("error accessing datadir content")?;
			if file_type.is_dir() {
				tokio::fs::remove_dir_all(item.path()).await.context("error deleting datadir content")?;
			} else if file_type.is_file() || file_type.is_symlink() {
				tokio::fs::remove_file(item.path()).await.context("error deleting datadir content")?;
			} else {
				// can't happen
				bail!("non-existent file type in ");
			}
		}
	}
	Ok(has_config)
}

pub async fn create_wallet(datadir: &Path, opts: CreateOpts) -> anyhow::Result<()> {
	debug!("Creating wallet in {}", datadir.display());

	let net = match (opts.mainnet, opts.signet, opts.regtest, opts.mutinynet) {
		(true,  false, false, false) => BarkNetwork::Mainnet,
		(false, true,  false, false) => BarkNetwork::Signet,
		(false, false, true,  false) => BarkNetwork::Regtest,
		(false, false, false, true ) => BarkNetwork::Mutinynet,
		_ => bail!("Specify exactly one of --mainnet, --signet, --regtest or --mutinynet"),
	};

	// check for non-config file contents in the datadir and wipe if force
	let config_existed = check_clean_datadir(datadir, opts.force).await?;

	// Everything that errors after this will wipe the datadir again.
	let result = try_create_wallet(datadir, net, opts).await;
	if let Err(e) = result {
		if config_existed {
			if let Err(e) = check_clean_datadir(datadir, true).await {
				warn!("Error cleaning datadir after failure: {:#}", e);
			}
		} else {
			if let Err(e) = tokio::fs::remove_dir_all(datadir).await {
				warn!("Error removing datadir after failure: {:#}", e);
			}
		}

		bail!("Error while creating wallet: {:#}", e);
	}
	Ok(())
}

/// In this method we create the wallet and if it fails, the datadir will be wiped again.
async fn try_create_wallet(
	datadir: &Path,
	net: BarkNetwork,
	mut opts: CreateOpts,
) -> anyhow::Result<()> {
	info!("Creating new bark Wallet at {}", datadir.display());

	tokio::fs::create_dir_all(datadir).await.context("can't create dir")?;

	let config_path = datadir.join(CONFIG_FILE);
	let has_config_args = opts.config != ConfigOpts::default();
	let config = match (config_path.exists(), has_config_args) {
		(true, false) => {
			Config::load(net.as_bitcoin(), &config_path).with_context(|| format!(
				"error loading existing config file at {}", config_path.display(),
			))?
		},
		(false, true) => {
			opts.config.fill_network_defaults(net);
			opts.config.validate().context("invalid config options")?;
			opts.config.write_to_file(net.as_bitcoin(), config_path)?
		},
		(false, false) => bail!("You need to provide config flags or a config file"),
		(true, true) => bail!("Cannot provide an existing config file and config flags"),
	};

	// A mnemonic implies that the user wishes to recover an existing wallet.
	if opts.mnemonic.is_some() {
		if opts.birthday_height.is_none() {
			// Only Bitcoin Core requires a birthday height to avoid syncing the entire chain.
			if config.bitcoind_address.is_some() {
				bail!("You need to set the --birthday-height field when recovering from mnemonic.");
			}
		} else if config.esplora_address.is_some() {
			warn!("The given --birthday-height will be ignored because you're using Esplora.");
		}
		warn!("Recovering from mnemonic currently only supports recovering on-chain funds!");
	} else {
		if opts.birthday_height.is_some() {
			bail!("Can't set --birthday-height if --mnemonic is not set.");
		}
	}

	// generate seed
	let is_new_wallet = opts.mnemonic.is_none();
	let mnemonic = opts.mnemonic.unwrap_or_else(|| bip39::Mnemonic::generate(12).expect("12 is valid"));
	let seed = mnemonic.to_seed("");
	tokio::fs::write(datadir.join(MNEMONIC_FILE), mnemonic.to_string().as_bytes()).await
		.context("failed to write mnemonic")?;

	// open db
	let db: Arc<dyn BarkPersister + Send + Sync> = if opts.use_filestore {
		debug!("Using filestore backend");
		let adaptor = FileStorageAdaptor::open(datadir.join(FILESTORE_FILE)).await?;
		Arc::new(StorageAdaptorWrapper::new(adaptor))
	} else {
		debug!("Using sqlite backend");
		Arc::new(SqliteClient::open(datadir.join(DB_FILE))?)
	};

	let mut onchain = OnchainWallet::load_or_create(net.as_bitcoin(), seed, db.clone()).await?;
	let wallet = BarkWallet::create_with_onchain(
		&mnemonic, net.as_bitcoin(), config, db, &onchain, opts.force,
	).await.context("error creating wallet")?;

	// Skip initial block sync if we generated a new wallet.
	let birthday_height = if is_new_wallet {
		Some(wallet.chain.tip().await?)
	} else {
		opts.birthday_height
	};
	onchain.initial_wallet_scan(&wallet.chain, birthday_height).await?;
	Ok(())
}

pub async fn open_wallet(datadir: &Path) -> anyhow::Result<Option<(BarkWallet, OnchainWallet)>> {
	debug!("Opening bark wallet in {}", datadir.display());


	// read mnemonic file
	let mnemonic_path = datadir.join(MNEMONIC_FILE);

	if !tokio::fs::try_exists(datadir).await? {
		return Ok(None);
	}

	if !tokio::fs::try_exists(&mnemonic_path).await? {
		return Ok(None);
	}

	let mnemonic_str = tokio::fs::read_to_string(&mnemonic_path).await
		.with_context(|| format!("failed to read mnemonic file at {}", mnemonic_path.display()))?;
	let mnemonic = bip39::Mnemonic::from_str(&mnemonic_str).context("broken mnemonic")?;
	let seed = mnemonic.to_seed("");

	let use_filestore = datadir.join(FILESTORE_FILE).exists();
	let db: Arc<dyn BarkPersister + Send + Sync> = if use_filestore {
		debug!("Using filestore backend");
		let adaptor = FileStorageAdaptor::open(datadir.join(FILESTORE_FILE)).await?;
		Arc::new(StorageAdaptorWrapper::new(adaptor))
	} else {
		debug!("Using sqlite backend");
		Arc::new(SqliteClient::open(datadir.join(DB_FILE))?)
	};
	let properties = db.read_properties().await?.context("failed to read properties")?;

	// Read the config
	let config_path = datadir.join("config.toml");
	let config = Config::load(properties.network, config_path)
		.context("error loading bark config file")?;

	let bdk_wallet = OnchainWallet::load_or_create(properties.network, seed, db.clone()).await?;
	let bark_wallet = BarkWallet::open_with_onchain(&mnemonic, db, &bdk_wallet, config).await?;

	if let Err(e) = bark_wallet.require_chainsource_version() {
		warn!("{}", e);
	}

	Ok(Some((bark_wallet, bdk_wallet)))
}