bark-cli 0.7.0

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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;

use anyhow::{bail, Context};
use bitcoin::hex::FromHex;
use bitcoin::secp256k1::rand::{self, RngCore};
use clap::{Parser, Subcommand};
use clap::builder::BoolishValueParser;
use log::{info, warn};

use bark_json::web::{BarkNetwork, BitcoindAuth, ChainSourceConfig, CreateWalletRequest};
use bark_rest::{Config, OnGetMnemonic, OnWalletCreate, OnWalletDelete, RestServer, ServerState};
use bark_rest::http::HeaderValue;
use bark_rest::error::ContextExt;
use bark_rest::auth::AuthToken;

use bark::fs_perms;

use bark_cli::VERSION_DEV_MARKER;
use bark_cli::connection;
use bark_cli::log::init_logging;
use bark_cli::wallet::{ConfigOpts, CreateOpts, create_wallet, open_wallet, read_mnemonic, AUTH_TOKEN_FILE};
use tokio_util::sync::CancellationToken;


/// The full version string we show in our binary.
/// (BARK_VERSION and GIT_HASH are set in build.rs)
const FULL_VERSION: &str = concat!(env!("BARK_VERSION"), " (", env!("GIT_HASH"), ")");

/// Wire-level client identity sent in `x-user-agent` on every RPC.
const USER_AGENT: &str = concat!("barkd/", env!("BARK_VERSION"));


fn default_datadir() -> String {
	home::home_dir().or_else(|| {
		std::env::current_dir().ok()
	}).unwrap_or_else(|| {
		"./".into()
	}).join(".bark").display().to_string()
}

#[derive(Parser)]
#[command(name = "barkd", about = "Bark daemon", version = FULL_VERSION)]
struct Cli {
	/// Enable verbose logging
	#[arg(
		long,
		short = 'v',
		env = "BARK_VERBOSE",
		global = true,
		value_parser = BoolishValueParser::new(),
	)]
	verbose: bool,
	/// Disable all terminal logging
	#[arg(
		long,
		short = 'q',
		env = "BARK_QUIET",
		global = true,
		value_parser = BoolishValueParser::new(),
	)]
	quiet: bool,

	/// Write the debug log to this file instead of the default
	/// `<datadir>/debug.log`
	#[arg(long, env = "BARK_LOGFILE", global = true, conflicts_with = "no_logfile")]
	logfile: Option<PathBuf>,
	/// Disable the debug log file entirely
	#[arg(
		long,
		env = "BARK_NO_LOGFILE",
		global = true,
		conflicts_with = "logfile",
		value_parser = BoolishValueParser::new(),
	)]
	no_logfile: bool,

	/// The datadir of the bark wallet
	#[arg(long, env = "BARKD_DATADIR", global = true, default_value_t = default_datadir())]
	datadir: String,

	#[command(subcommand)]
	command: Option<Command>,

	/// The port to listen on
	#[arg(long, env = "BARKD_BIND_PORT")]
	port: Option<u16>,
	/// The host to listen on. Defaults to loopback; any other value may expose
	/// the API to other machines on your network or the public internet.
	#[arg(long, env = "BARKD_BIND_HOST")]
	host: Option<String>,

	/// Comma-separated list of allowed CORS origins (e.g. "http://localhost:3001,https://myapp.example.com").
	/// Defaults to denying all cross-origin requests; any value may expose the
	/// API to browser clients on other origins.
	#[arg(long, env = "BARKD_ALLOWED_ORIGINS", value_delimiter = ',')]
	allowed_origins: Vec<String>,

	/// Expose `GET /api/v1/wallet/mnemonic`, which returns the wallet's BIP-39
	/// mnemonic phrase. Disabled by default; while disabled the endpoint
	/// responds with 404. Pass `--expose-mnemonic` (or set
	/// `BARKD_EXPOSE_MNEMONIC=true`) to enable it.
	#[arg(
		long,
		env = "BARKD_EXPOSE_MNEMONIC",
		default_value_t = false,
		value_parser = BoolishValueParser::new(),
	)]
	expose_mnemonic: bool,

	/// Disables all authentication.
	///
	/// Anyone who can access the HTTP port can create invoices, spend all coins
	/// and might retrieve the mnemonic.
	///
	/// This option is mainly useful for testing and development.
	///
	/// Deliberately has no environment variable. We don't want auth to be
	/// disabled by an inherited environment.
	#[arg(long)]
	no_auth: bool,

	/// Disables all authentication and permits a non-loopback bind.
	///
	/// Implies --no-auth, so it is passed on its own. Anything that can route
	/// to the bind address gets full wallet access, so only use this when
	/// something else restricts who can reach the port.
	#[arg(long)]
	dangerously_allow_remote_no_auth: bool,
}

#[derive(Subcommand)]
enum Command {
	/// Manage auth secrets
	Secret {
		#[command(subcommand)]
		action: SecretCommand,
	},
}

fn parse_hex_secret(s: &str) -> Result<[u8; 32], String> {
	<[u8; 32]>::from_hex(s)
		.map_err(|_| "must be exactly 64 hex characters (32 bytes)".to_string())
}

#[derive(Subcommand)]
enum SecretCommand {
	/// Print the current bearer token.
	Show,
	/// Regenerate the default auth secret and print the bearer token.
	/// If --secret is provided, use that instead of generating a random one.
	Refresh {
		/// Optional 32-byte hex secret to use instead of a random one
		#[arg(long, value_parser = parse_hex_secret)]
		secret: Option<[u8; 32]>,
	},
}

impl Cli {
	fn to_config(&self) -> anyhow::Result<Config> {
		let mut cfg = Config::default();
		if let Some(port) = &self.port {
			if *port == 0 {
				bail!("--port 0 is not supported; barkd listens on a fixed \
					port (default {})", cfg.port);
			}
			cfg.port = *port;
		}
		if let Some(host) = &self.host {
			cfg.host = host.parse()
				.with_context(|| format!("invalid bind host: {host}"))?;
		}
		// Validate that each origin is a well-formed origin (scheme://host[:port]).
		for origin in &self.allowed_origins {
			origin.parse::<HeaderValue>()
				.with_context(|| format!("invalid CORS origin: {origin}"))?;
			let valid = (origin.starts_with("http://") || origin.starts_with("https://"))
				&& !origin.ends_with('/')
				&& origin.matches("://").count() == 1;
			if !valid {
				bail!(
					"invalid CORS origin: {origin} \
					(expected format: http://host[:port] or https://host[:port])"
				);
			}
		}
		cfg.allowed_origins = self.allowed_origins.clone();
		Ok(cfg)
	}

	/// Either flag disables auth; only the dangerous one also permits a
	/// non-loopback bind.
	fn auth_disabled(&self) -> bool {
		self.no_auth || self.dangerously_allow_remote_no_auth
	}
}

/// Refuse to run without auth on a bind address other hosts can reach, unless
/// the operator asked for exactly that with the dangerous flag.
fn check_remote_no_auth(host: IpAddr, allow_remote: bool) -> anyhow::Result<()> {
	if host.is_loopback() || allow_remote {
		return Ok(());
	}

	bail!(
		"refusing to start: --no-auth with bind host {host} would give full wallet access \
		to every client that can reach the port. Bind a loopback address, or use \
		--dangerously-allow-remote-no-auth instead if reachability is restricted by other \
		means (and terminate TLS in front of barkd)",
	);
}

/// Runs a thread that will watch for SIGTERM and ctrl-c signals and
/// returns when a signal is received
async fn run_shutdown_signal_listener(shutdown: CancellationToken) {
	async fn signal_recv() {
		#[cfg(unix)]
		{
			let mut sigterm = tokio::signal::unix::signal(
				tokio::signal::unix::SignalKind::terminate()
			).expect("Failed to listen for SIGTERM");

			sigterm.recv().await;
			info!("SIGTERM received! Sending shutdown signal...");
			return;
		}

		#[cfg(windows)]
		{
			let mut ctrl_break = tokio::signal::windows::ctrl_break()
				.expect("Failed to listen for CTRL+BREAK");

			ctrl_break.recv().await;
			info!("CTRL+BREAK received! Sending shutdown signal...");
			return
		}

		#[cfg(not(any(unix, windows)))]
		{
			log::warn!("Unknown platform, not listening for shutdown signals");
			std::future::pending().await
		}
	}

	tokio::select! {
		_ = signal_recv() => {},
		r = tokio::signal::ctrl_c() => match r {
			Ok(()) => info!("Ctrl+C received! Sending shutdown signal..."),
			Err(e) => panic!("failed to listen to ctrl-c signal: {e}"),
		},
	}

	shutdown.cancel();
}

/// Load the auth token from the datadir. Returns `None` if the file
/// doesn't exist.
fn load_auth_token(datadir: &PathBuf) -> anyhow::Result<Option<AuthToken>> {
	let path = datadir.join(AUTH_TOKEN_FILE);
	if !path.exists() {
		return Ok(None);
	}

	let str = std::fs::read_to_string(&path)
		.with_context(|| format!("failed to read {}", path.display()))?;
	Ok(Some(AuthToken::decode(&str)?))
}

/// Write the auth token to the datadir.
fn store_auth_token(datadir: &PathBuf, token: &AuthToken) -> anyhow::Result<()> {
	let path = datadir.join(AUTH_TOKEN_FILE);
	// This also handles `secret refresh`, which overwrites an existing token.
	fs_perms::write_atomic_owner_only(&path, token.encode().as_bytes())
}

/// Generate a random auth token and persist it to the datadir.
fn generate_store_auth_token(datadir: &PathBuf) -> anyhow::Result<AuthToken> {
	let mut secret = [0u8; 32];
	rand::thread_rng().fill_bytes(&mut secret);
	let token = AuthToken::new(secret);
	store_auth_token(datadir, &token)?;
	Ok(token)
}

fn wallet_create_request_to_create_opts(req: CreateWalletRequest) -> anyhow::Result<CreateOpts> {
	let mnemonic = if let Some(mnemonic) = req.mnemonic {
		Some(bip39::Mnemonic::from_str(&mnemonic).badarg("Invalid mnemonic")?)
	} else {
		None
	};

	#[allow(deprecated)]
	let mut config = ConfigOpts {
		ark: req.ark_server,
		access_token: req.ark_server_access_token,
		esplora: None,
		bitcoind: None,
		bitcoind_cookie: None,
		bitcoind_user: None,
		bitcoind_pass: None,
		socks5_proxy: None,
	};

	if let Some(chain_source) = req.chain_source {
		match chain_source {
			ChainSourceConfig::Esplora { url } => {
				config.esplora = Some(url);
			},
			ChainSourceConfig::Bitcoind { bitcoind, bitcoind_auth } => {
				config.bitcoind = Some(bitcoind);
				match bitcoind_auth {
					BitcoindAuth::Cookie { cookie } => {
						config.bitcoind_cookie = Some(cookie);
					},
					BitcoindAuth::UserPass { user, pass } => {
						config.bitcoind_user = Some(user);
						config.bitcoind_pass = Some(pass);
					},
				}
			},
		}
	}

	Ok(CreateOpts {
		force: req.force,
		use_filestore: false,
		mainnet: req.network == BarkNetwork::Mainnet,
		regtest: req.network == BarkNetwork::Regtest,
		signet: req.network == BarkNetwork::Signet,
		mutinynet: req.network == BarkNetwork::Mutinynet,
		mnemonic: mnemonic,
		birthday_height: req.birthday_height,
		config: config,
	})
}

#[tokio::main]
async fn main() -> anyhow::Result<()>{
	let cli = Cli::parse();

	let datadir = PathBuf::from_str(&cli.datadir).unwrap();

	let datadir_existed = datadir.exists();
	std::fs::create_dir_all(&datadir)
		.with_context(|| format!("failed to create datadir {}", datadir.display()))?;
	if !datadir_existed {
		fs_perms::harden(&datadir, 0o700)?;
	}

	init_logging(cli.verbose, cli.quiet, &datadir, cli.logfile.clone(), cli.no_logfile);

	if datadir_existed {
		fs_perms::warn_if_loose(&datadir, 0o700);
	}

	// Handle subcommands that don't start the daemon.
	if let Some(command) = &cli.command {
		if cli.port.is_some() || cli.host.is_some() {
			warn!("--port and --host are only used when running the daemon, ignoring");
		}

		match command {
			Command::Secret { action: SecretCommand::Show } => {
				let token = load_auth_token(&datadir)?
					.context("no auth token found — run `barkd secret refresh` to generate one")?;
				println!("{}", token.encode());
				return Ok(());
			},
			Command::Secret { action: SecretCommand::Refresh { secret: user_secret } } => {
				let token = if let Some(bytes) = user_secret {
					let token = AuthToken::new(*bytes);
					store_auth_token(&datadir, &token)?;
					token
				} else {
					generate_store_auth_token(&datadir)?
				};
				info!("Restart barkd for the new token to take effect.");
				println!("{}", token.encode());
				return Ok(());
			},
		}
	}

	let config = cli.to_config()?;

	let shutdown = CancellationToken::new();

	info!("Starting barkd version {} with datadir {}", FULL_VERSION, datadir.display());

	if env!("BARK_VERSION").contains(VERSION_DEV_MARKER) {
		warn!("You're running a custom build of barkd, which might cause unexpected issues. \
			Consider building at one of the tagged versions or using the release builds.");
	}

	let _barkd_lock = connection::acquire_barkd_lock(&datadir)?;

	let auth_token = if cli.auth_disabled() {
		check_remote_no_auth(config.host, cli.dangerously_allow_remote_no_auth)?;
		if cli.allowed_origins.is_empty() {
			warn!("Auth is disabled and no CORS origins are configured — \
				any client that can reach this port has full API access.");
		}
		None
	} else {
		let token = match load_auth_token(&datadir)? {
			Some(token) => token,
			None => {
				let token = generate_store_auth_token(&datadir)?;
				info!("No auth token found — generated a new one. Use `barkd secret show` to view it.");
				token
			},
		};
		Some(token)
	};

	let wallet_opt = if let Some(wallet) = open_wallet(&datadir, USER_AGENT).await? {
		wallet.start_daemon()?;
		info!("Wallet loaded and daemon started");
		Some(wallet)
	} else {
		warn!("No wallet found. Starting rest server without daemon");
		None
	};

	let on_wallet_create: Box<OnWalletCreate> = Box::new({
		let datadir = datadir.clone();

		move |req: CreateWalletRequest| {
			let datadir = datadir.clone();

			Box::pin(async move {
				let create_opts = wallet_create_request_to_create_opts(req)?;
				create_wallet(&datadir, USER_AGENT, create_opts).await?;
				let wallet = open_wallet(&datadir, USER_AGENT).await?
					.expect("Wallet should exist");

				// Warm up `wallet.server` before spawning the daemon so
				// that subsequent REST requests don't race with the daemon's
				// first connection check.
				if let Err(e) = wallet.refresh_server().await {
					warn!("Ark server handshake failed on wallet creation: {:#}", e);
				}

				wallet.start_daemon()?;
				Ok::<_, anyhow::Error>(wallet)
			})
		}
	});

	let on_wallet_delete: Box<OnWalletDelete> = Box::new({
		let datadir = datadir.clone();
		move || {
			let datadir = datadir.clone();

			// NB: No need to stop the daemon here, it will be stopped when the wallet is removed from the server state

			Box::pin(async move {
				connection::wipe_datadir_except_barkd_files(&datadir)?;
				Ok(())
			})
		}
	});

	let on_get_mnemonic: Option<Box<OnGetMnemonic>> = if cli.expose_mnemonic {
		let datadir = datadir.clone();
		Some(Box::new(move || {
			let datadir = datadir.clone();
			Box::pin(async move { read_mnemonic(&datadir).await })
		}))
	} else {
		None
	};

	let inner_wallet = wallet_opt.as_ref().map(|w| w.clone());
	let state = ServerState::builder()
		.wallet(wallet_opt)
		.auth_token(auth_token)
		.on_wallet_create(on_wallet_create)
		.on_wallet_delete(on_wallet_delete)
		.on_get_mnemonic(on_get_mnemonic)
		.build(shutdown.clone());
	let server = RestServer::start(&config, Arc::new(state), shutdown.clone()).await?;

	run_shutdown_signal_listener(shutdown.clone()).await;

	if let Some(wallet) = inner_wallet {
		wallet.stop_daemon();
	}

	if let Err(e) = server.stop_wait().await {
		warn!("Error while stopping REST server: {:#}", e);
	}

	Ok(())
}

#[cfg(test)]
mod test {
	use super::*;

	/// `--expose-mnemonic` is a bare presence flag: absent means the mnemonic
	/// endpoint is disabled, present means enabled. This guards both the
	/// disabled-by-default behavior and the flag form; the env-var value form
	/// (`BARKD_EXPOSE_MNEMONIC=true`) is covered by the barkd integration tests.
	#[test]
	fn expose_mnemonic_flag_parsing() {
		let cli = Cli::try_parse_from(["barkd"])
			.expect("bare invocation should parse");
		assert!(!cli.expose_mnemonic, "mnemonic exposure must be off by default");

		let cli = Cli::try_parse_from(["barkd", "--expose-mnemonic"])
			.expect("--expose-mnemonic should parse");
		assert!(cli.expose_mnemonic, "--expose-mnemonic must enable exposure");
	}

	/// Nothing reports the actually bound address, so an OS-assigned port
	/// would leave the daemon unreachable by convention.
	#[test]
	fn to_config_rejects_port_zero() {
		let cli = Cli::try_parse_from(["barkd", "--port", "0"])
			.expect("--port 0 should parse");
		let err = cli.to_config().unwrap_err();
		assert!(
			err.to_string().contains("--port 0 is not supported"),
			"unexpected error: {}", err,
		);

		let cli = Cli::try_parse_from(["barkd", "--port", "3001"])
			.expect("--port 3001 should parse");
		assert_eq!(cli.to_config().unwrap().port, 3001);
	}

	/// Both flags are bare presence flags with no env-var form; that auth can't
	/// be disabled through the environment is covered by the barkd integration
	/// tests.
	#[test]
	fn no_auth_flag_parsing() {
		let cli = Cli::try_parse_from(["barkd"])
			.expect("bare invocation should parse");
		assert!(!cli.auth_disabled(), "auth must be required by default");
		assert!(!cli.dangerously_allow_remote_no_auth, "remote must be off by default");

		let cli = Cli::try_parse_from(["barkd", "--no-auth"])
			.expect("--no-auth should parse");
		assert!(cli.auth_disabled(), "--no-auth must disable auth");
		assert!(!cli.dangerously_allow_remote_no_auth, "--no-auth must not permit remote binds");

		// The dangerous flag stands on its own: it disables auth too.
		let cli = Cli::try_parse_from(["barkd", "--dangerously-allow-remote-no-auth"])
			.expect("--dangerously-allow-remote-no-auth should parse");
		assert!(cli.auth_disabled(), "the dangerous flag must disable auth on its own");
		assert!(cli.dangerously_allow_remote_no_auth, "the dangerous flag must permit remote binds");
	}

	#[test]
	fn remote_no_auth_needs_dangerous_flag() {
		let addr = |s: &str| s.parse::<IpAddr>().unwrap();

		check_remote_no_auth(addr("127.0.0.1"), false).expect("IPv4 loopback");
		check_remote_no_auth(addr("::1"), false).expect("IPv6 loopback");

		for host in ["0.0.0.0", "192.168.1.10", "::"] {
			check_remote_no_auth(addr(host), false)
				.expect_err(&format!("{host} is reachable from other hosts"));
			check_remote_no_auth(addr(host), true)
				.unwrap_or_else(|e| panic!("{host} should be allowed by the flag: {e:#}"));
		}
	}
}