Skip to main content

bark/
config.rs

1
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use anyhow::Context;
6use bitcoin::{FeeRate, Network};
7
8use bitcoin_ext::{BlockDelta, BlockHeight};
9
10
11/// Networks bark can be used on
12#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub enum BarkNetwork {
14	/// Bitcoin's mainnet
15	Mainnet,
16	/// The official Bitcoin Core signet
17	Signet,
18	/// Mutinynet
19	Mutinynet,
20	/// Any regtest network
21	Regtest,
22}
23
24impl BarkNetwork {
25	/// Map to the [Network] types
26	pub fn as_bitcoin(&self) -> Network {
27		match self {
28			Self::Mainnet => Network::Bitcoin,
29			Self::Signet => Network::Signet,
30			Self::Mutinynet => Network::Signet,
31			Self::Regtest => Network::Regtest,
32		}
33	}
34}
35
36impl fmt::Display for BarkNetwork {
37	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38	    match self {
39			Self::Mainnet => f.write_str("mainnet"),
40			Self::Signet => f.write_str("signet"),
41			Self::Mutinynet => f.write_str("mutinynet"),
42			Self::Regtest => f.write_str("regtest"),
43		}
44	}
45}
46
47impl fmt::Debug for BarkNetwork {
48	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49		fmt::Display::fmt(self, f)
50	}
51}
52
53/// Configuration of the Bark wallet.
54///
55/// - [Config::esplora_address] or [Config::bitcoind_address] must be provided.
56/// - If you use [Config::bitcoind_address], you must also provide:
57///   - [Config::bitcoind_cookiefile] or
58///   - [Config::bitcoind_user] and [Config::bitcoind_pass]
59/// - Other optional fields can be omitted.
60///
61/// # Example
62/// Configure the wallet using defaults, then override endpoints for public signet:
63///
64/// ```rust
65/// use bark::Config;
66///
67/// let cfg = Config {
68///   server_address: "https://ark.signet.2nd.dev".into(),
69///   esplora_address: Some("https://esplora.signet.2nd.dev".into()),
70///   ..Config::network_default(bitcoin::Network::Bitcoin)
71/// };
72/// // cfg now has all other fields from the default configuration
73/// ```
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct Config {
76	/// The address of your ark server.
77	pub server_address: String,
78
79	/// An access token used to access a private server
80	pub server_access_token: Option<String>,
81
82	/// The address of the Esplora HTTP REST server to use.
83	///
84	/// Either this or the `bitcoind_address` field has to be provided.
85	pub esplora_address: Option<String>,
86
87	/// The address of the bitcoind RPC server to use.
88	///
89	/// Either this or the `esplora_address` field has to be provided.
90	/// Either `bitcoind_cookiefile` or `bitcoind_user` and `bitcoind_pass` has to be provided.
91	pub bitcoind_address: Option<String>,
92
93	/// The path to the bitcoind rpc cookie file.
94	///
95	/// Only used with `bitcoind_address`.
96	pub bitcoind_cookiefile: Option<PathBuf>,
97
98	/// The bitcoind RPC username.
99	///
100	/// Only used with `bitcoind_address`.
101	pub bitcoind_user: Option<String>,
102
103	/// The bitcoind RPC password.
104	///
105	/// Only used with `bitcoind_address`.
106	pub bitcoind_pass: Option<String>,
107
108	/// The number of blocks before expiration to refresh vtxos.
109	///
110	/// Default value: 144 (24h) for mainnet, 12 for testnets
111	pub vtxo_refresh_expiry_threshold: BlockHeight,
112
113	/// An upper limit of the number of blocks we expect to need to
114	/// safely exit the vtxos.
115	///
116	/// Default value: 12
117	pub vtxo_exit_margin: BlockDelta,
118
119	/// The number of blocks to claim a HTLC-recv VTXO.
120	///
121	/// Default value: 18
122	pub htlc_recv_claim_delta: BlockDelta,
123
124	/// Optional SOCKS5 proxy URL for network traffic.
125	///
126	/// The proxy is automatically bypassed for localhost addresses
127	/// (127.0.0.1, localhost, ::1), so a local bitcoind works without
128	/// extra configuration.
129	///
130	/// Use `socks5h://` to resolve DNS through the proxy which is required for .onion addresses
131	/// and to prevent DNS leaks. We don't allow `socks5://` to be used to preserve privacy.
132	///
133	/// Example: `socks5h://127.0.0.1:9050` for a local Tor daemon.
134	#[cfg(feature = "socks5-proxy")]
135	pub socks5_proxy: Option<String>,
136
137	/// A fallback fee rate to use in sat/kWu when we fail to retrieve a fee rate from the
138	/// configured bitcoind/esplora connection.
139	///
140	/// Example for 1 sat/vB: --fallback-fee-rate 250
141	pub fallback_fee_rate: Option<FeeRate>,
142
143	/// The number of confirmations required before considering a round tx
144	/// fully confirmed
145	///
146	/// Default value: 6 for mainnet, 2 for testnets
147	pub round_tx_required_confirmations: BlockHeight,
148
149	/// The number of confirmations required before considering an offboard tx
150	/// confirmed. If set to 0, offboard movements are marked as successful
151	/// immediately without waiting for confirmation.
152	///
153	/// Default value: 2 for mainnet
154	pub offboard_required_confirmations: BlockHeight,
155
156	/// Daemon sync interval in seconds for fast tasks (lightning sync).
157	///
158	/// This should be significantly smaller than the server's
159	/// `receive_htlc_forward_timeout` (default 30s). If the sync interval is
160	/// too close to the timeout, lightning receives are more likely to fail
161	/// because the client may not claim the HTLC in time.
162	///
163	/// Default value: 1
164	pub daemon_fast_sync_interval_secs: u64,
165
166	/// Daemon sync interval in seconds for slow tasks (onchain, exits, boards, offboards, maintenance, rounds, mailbox).
167	///
168	/// Default value: 60
169	pub daemon_slow_sync_interval_secs: u64,
170
171	/// When set, the daemon skips all automatic wallet syncing — startup
172	/// sync, the fast/slow sync intervals, round event subscription, and
173	/// the mailbox subscription. Only the server connection heartbeat
174	/// keeps running. The operator is responsible for triggering syncs
175	/// via the REST API (e.g. `POST /sync`).
176	///
177	/// Default value: false
178	pub daemon_manual_sync: bool,
179}
180
181impl Config {
182	/// A network-dependent default config that sets some useful defaults
183	///
184	/// The [Default::default] provides a sane default for mainnet
185	pub fn network_default(network: Network) -> Self {
186		let mut ret = Self {
187			server_address: "http://127.0.0.1:3535".to_owned(),
188			server_access_token: None,
189			esplora_address: None,
190			bitcoind_address: None,
191			bitcoind_cookiefile: None,
192			bitcoind_user: None,
193			bitcoind_pass: None,
194			#[cfg(feature = "socks5-proxy")]
195			socks5_proxy: None,
196			vtxo_refresh_expiry_threshold: 144,
197			vtxo_exit_margin: 12,
198			htlc_recv_claim_delta: 18,
199			fallback_fee_rate: Some(FeeRate::from_sat_per_vb_unchecked(2)),
200			round_tx_required_confirmations: 1,
201			offboard_required_confirmations: 2,
202			daemon_fast_sync_interval_secs: 1,
203			daemon_slow_sync_interval_secs: 60,
204			daemon_manual_sync: false,
205		};
206
207		if network != Network::Bitcoin {
208			ret.vtxo_refresh_expiry_threshold = 12;
209			ret.fallback_fee_rate = Some(FeeRate::from_sat_per_vb_unchecked(1));
210			ret.round_tx_required_confirmations = 1;
211			ret.offboard_required_confirmations = 0;
212		}
213
214		ret
215	}
216
217	/// Load config from the config file path, filling missing fields
218	/// from the network default.
219	///
220	/// Config values are loaded in the following priority order (highest to lowest):
221	/// 1. Environment variables with `BARK_` prefix (e.g., `BARK_ESPLORA_ADDRESS`)
222	/// 2. Config file values
223	/// 3. Network defaults
224	pub fn load(network: Network, path: impl AsRef<Path>) -> anyhow::Result<Config> {
225		let default = config::Config::try_from(&Self::network_default(network))
226			.expect("default config failed to deconstruct");
227
228		Ok(config::Config::builder()
229			.add_source(default)
230			.add_source(config::File::from(path.as_ref()).required(false))
231			.add_source(config::Environment::with_prefix("BARK"))
232			.build().context("error building config")?
233			.try_deserialize::<Config>().context("error parsing config")?)
234	}
235}
236