bark-cli 0.2.2

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
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 tokio::sync::RwLock;

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

use bark_cli::VERSION_DIRTY;
use bark_cli::log::init_logging;
use bark_cli::wallet::{ConfigOpts, CreateOpts, create_wallet, open_wallet, read_mnemonic, AUTH_TOKEN_FILE};


/// 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"), ")");


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,

	/// 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.
	/// Consider `--expose-mnemonic=false` for hardening.
	#[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. Consider
	/// `--expose-mnemonic=false` for hardening.
	#[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. Disabling responds with 404.
	#[arg(
		long,
		env = "BARKD_EXPOSE_MNEMONIC",
		default_value_t = true,
		value_parser = BoolishValueParser::new(),
	)]
	expose_mnemonic: 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 {
			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)
	}
}

/// 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() {
	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}"),
		},
	}
}

/// 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);
	std::fs::write(&path, token.encode())
		.with_context(|| format!("failed to write {}", path.display()))?;

	#[cfg(unix)]
	{
		use std::os::unix::fs::PermissionsExt;
		let perms = std::fs::Permissions::from_mode(0o600);
		std::fs::set_permissions(&path, perms)
			.with_context(|| format!("failed to set permissions on {}", path.display()))?;
	}

	Ok(())
}

/// 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
	};

	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: false,
		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();

	init_logging(cli.verbose, cli.quiet, &datadir);

	// 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)?
				};
				eprintln!("Restart barkd for the new token to take effect.");
				println!("{}", token.encode());
				return Ok(());
			},
		}
	}

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

	if env!("BARK_VERSION") == VERSION_DIRTY {
		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 auth_token = match load_auth_token(&datadir)? {
		Some(token) => token,
		None => {
			let token = generate_store_auth_token(&datadir)?;
			eprintln!("No auth token found — generated a new one. Use `barkd secret show` to view it.");
			token
		},
	};

	let wallet_opt = if let Some((wallet, onchain)) = open_wallet(&datadir).await? {
		let onchain = Arc::new(RwLock::new(onchain));

		wallet.start_daemon(Some(onchain.clone()))?;
		info!("Wallet loaded and daemon started");
		let server_wallet = bark_rest::ServerWallet::new(wallet, onchain);

		Some(server_wallet)
	} else {
		warn!("No wallet found. Starting rest server without daemon");
		None
	};

	let on_wallet_create: Arc<OnWalletCreate> = Arc::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, create_opts).await?;
				let (wallet, onchain) = open_wallet(&datadir).await?
					.expect("Wallet should exist");

				let onchain = Arc::new(RwLock::new(onchain));

				// 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(Some(onchain.clone()))?;

				let handle = ServerWallet::new(wallet, onchain);
				Ok::<_, anyhow::Error>(handle)
			})
		}
	});

	let on_wallet_delete: Arc<OnWalletDelete> = Arc::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 {
				// Wipe datadir
				let _ = tokio::fs::remove_dir_all(&datadir).await.ok();
				tokio::fs::create_dir_all(&datadir).await?;
				Ok(())
			})
		}
	});

	let on_get_mnemonic: Option<Arc<OnGetMnemonic>> = if cli.expose_mnemonic {
		let datadir = datadir.clone();
		Some(Arc::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.wallet.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();
	let server = RestServer::start(&cli.to_config()?, state).await?;

	run_shutdown_signal_listener().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(())
}