lexe/config.rs
1use std::{
2 borrow::Cow,
3 fmt,
4 path::{Path, PathBuf},
5};
6
7use anyhow::Context;
8pub use lexe_common::{env::DeployEnv, ln::network::Network};
9
10use crate::{
11 types::auth::{CredentialsRef, UserPk},
12 unstable::SDK_USER_AGENT,
13};
14
15// --- Structs --- //
16//
17// - WalletEnv (`wallet_env`)
18// - WalletEnvConfig (`env_config`)
19// - WalletUserConfig (`user_config`)
20// - WalletEnvDbConfig (`env_db_config`)
21// - WalletUserDbConfig (`user_db_config`)
22
23/// A wallet environment, e.g. "prod-mainnet-sgx".
24///
25/// Disambiguates persisted state and secrets across environments.
26#[derive(Copy, Clone, Debug, Eq, PartialEq)]
27pub struct WalletEnv {
28 /// Prod, staging, or dev.
29 pub deploy_env: DeployEnv,
30 /// The Bitcoin network: mainnet, testnet, or regtest.
31 pub network: Network,
32 /// Whether our node should be running in a real SGX enclave.
33 /// Set to [`true`] for prod and staging.
34 pub use_sgx: bool,
35}
36
37/// A configuration for a wallet environment.
38#[derive(Clone, Debug, Eq, PartialEq)]
39pub struct WalletEnvConfig {
40 /// The wallet environment.
41 pub wallet_env: WalletEnv,
42 // NOTE(unstable): Fields should stay pub(crate) until API is more mature
43 pub(crate) gateway_url: Cow<'static, str>,
44 pub(crate) user_agent: Cow<'static, str>,
45}
46
47/// A wallet configuration for a specific user and wallet environment.
48#[derive(Clone)]
49pub struct WalletUserConfig {
50 /// The user public key.
51 pub user_pk: UserPk,
52 /// The configuration for the wallet environment.
53 pub env_config: WalletEnvConfig,
54}
55
56/// Database directory configuration for a specific wallet environment.
57#[derive(Clone)]
58pub struct WalletEnvDbConfig {
59 // NOTE(unstable): Fields should stay pub(crate) until API is more mature.
60 /// The base data directory for all Lexe-related data.
61 /// Holds data for different app environments and users.
62 ///
63 /// `<lexe_data_dir>`
64 pub(crate) lexe_data_dir: PathBuf,
65 /// Database directory for a specific wallet environment.
66 /// Holds data for all users within that environment.
67 ///
68 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>`
69 pub(crate) env_db_dir: PathBuf,
70}
71
72/// Database directory configuration for a specific user and wallet environment.
73#[derive(Clone)]
74pub struct WalletUserDbConfig {
75 // NOTE(unstable): Fields should stay pub(crate) until API is more mature.
76 /// Environment-level database configuration.
77 pub(crate) env_db_config: WalletEnvDbConfig,
78 /// The user public key.
79 pub(crate) user_pk: UserPk,
80 /// Database directory for a specific user.
81 /// Contains user-specific data like payments, settings, etc.
82 ///
83 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>/<user_pk>`
84 pub(crate) user_db_dir: PathBuf,
85}
86
87// --- impl WalletEnv --- //
88
89impl WalletEnv {
90 /// Bitcoin mainnet environment (prod, SGX).
91 pub fn mainnet() -> Self {
92 Self {
93 deploy_env: DeployEnv::Prod,
94 network: Network::Mainnet,
95 use_sgx: true,
96 }
97 }
98
99 /// Bitcoin testnet3 environment (staging, SGX).
100 pub fn testnet3() -> Self {
101 Self {
102 deploy_env: DeployEnv::Staging,
103 network: Network::Testnet3,
104 use_sgx: true,
105 }
106 }
107
108 /// Regtest environment (dev, configurable SGX).
109 pub fn regtest(use_sgx: bool) -> Self {
110 Self {
111 deploy_env: DeployEnv::Dev,
112 network: Network::Regtest,
113 use_sgx,
114 }
115 }
116
117 /// Returns the default path to the seedphrase file for this environment.
118 ///
119 /// - Mainnet (prod): `<data_dir>/seedphrase.txt`
120 /// - Other environments: `<data_dir>/seedphrase.<wallet_env>.txt`
121 pub fn seedphrase_path(&self, data_dir: &Path) -> PathBuf {
122 let filename = if self.deploy_env == DeployEnv::Prod {
123 Cow::Borrowed("seedphrase.txt")
124 } else {
125 Cow::Owned(format!("seedphrase.{self}.txt"))
126 };
127 data_dir.join(filename.as_ref())
128 }
129}
130
131impl fmt::Display for WalletEnv {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 let deploy_env = self.deploy_env.as_str();
134 let network = self.network.as_str();
135 let sgx = if self.use_sgx { "sgx" } else { "dbg" };
136 write!(f, "{deploy_env}-{network}-{sgx}")
137 }
138}
139
140// --- impl WalletEnvConfig --- //
141
142impl WalletEnvConfig {
143 /// Standard wallet environment configuration for Bitcoin mainnet.
144 pub fn mainnet() -> Self {
145 let wallet_env = WalletEnv::mainnet();
146 Self {
147 gateway_url: wallet_env.deploy_env.gateway_url(None),
148 user_agent: Cow::Borrowed(*SDK_USER_AGENT),
149 wallet_env,
150 }
151 }
152
153 /// Standard wallet environment configuration for Bitcoin testnet3.
154 pub fn testnet3() -> Self {
155 let wallet_env = WalletEnv::testnet3();
156 Self {
157 gateway_url: wallet_env.deploy_env.gateway_url(None),
158 user_agent: Cow::Borrowed(*SDK_USER_AGENT),
159 wallet_env,
160 }
161 }
162
163 /// Regtest configuration for local development and testing.
164 ///
165 /// - `use_sgx`: Whether to use SGX enclaves.
166 /// - `gateway_url`: Custom gateway URL. If `None`, uses the default dev
167 /// URL.
168 pub fn regtest(
169 use_sgx: bool,
170 gateway_url: Option<impl Into<Cow<'static, str>>>,
171 ) -> Self {
172 let wallet_env = WalletEnv::regtest(use_sgx);
173 let gateway_url = gateway_url.map(Into::into);
174 Self {
175 gateway_url: wallet_env.deploy_env.gateway_url(gateway_url),
176 user_agent: Cow::Borrowed(*SDK_USER_AGENT),
177 wallet_env,
178 }
179 }
180
181 /// Construct a [`WalletEnvConfig`] with a custom gateway URL.
182 #[cfg(feature = "unstable")]
183 pub fn new(wallet_env: WalletEnv, gateway_url: Cow<'static, str>) -> Self {
184 Self {
185 wallet_env,
186 gateway_url,
187 user_agent: Cow::Borrowed(*SDK_USER_AGENT),
188 }
189 }
190
191 /// Get a [`WalletEnvConfig`] for production.
192 //
193 // This is unstable because "Deploy environment" is an internal concept and
194 // should not be exposed to SDK users.
195 #[cfg(feature = "unstable")]
196 pub fn prod() -> Self {
197 Self::mainnet()
198 }
199
200 /// Get a [`WalletEnvConfig`] for staging.
201 //
202 // This is unstable because "Deploy environment" is an internal concept and
203 // should not be exposed to SDK users.
204 #[cfg(feature = "unstable")]
205 pub fn staging() -> Self {
206 Self::testnet3()
207 }
208
209 /// Get a [`WalletEnvConfig`] for dev/testing.
210 //
211 // This is unstable because "Deploy environment" is an internal concept and
212 // should not be exposed to SDK users.
213 #[cfg(feature = "unstable")]
214 pub fn dev(
215 use_sgx: bool,
216 gateway_url: Option<impl Into<Cow<'static, str>>>,
217 ) -> Self {
218 Self::regtest(use_sgx, gateway_url)
219 }
220
221 /// The gateway URL.
222 #[cfg(feature = "unstable")]
223 pub fn gateway_url(&self) -> &str {
224 &self.gateway_url
225 }
226
227 /// The user agent string.
228 #[cfg(feature = "unstable")]
229 pub fn user_agent(&self) -> &str {
230 &self.user_agent
231 }
232
233 /// Prepend a token identifying the first-party surface embedding the SDK,
234 /// e.g. `sdk-sidecar/0.4.18`.
235 ///
236 /// The resulting user agent looks like:
237 /// `sdk-sidecar/0.4.18 lexe/0.1.21 node/0.10.3`.
238 #[cfg(feature = "unstable")]
239 pub fn with_user_agent_prefix(mut self, prefix: &str) -> Self {
240 self.user_agent = Cow::Owned(format!("{prefix} {}", self.user_agent));
241 self
242 }
243
244 /// Returns the default path to the seedphrase file for this environment.
245 pub fn seedphrase_path(&self, data_dir: &Path) -> PathBuf {
246 self.wallet_env.seedphrase_path(data_dir)
247 }
248}
249
250// --- impl WalletEnvDbConfig --- //
251
252impl WalletEnvDbConfig {
253 /// Construct a new [`WalletEnvDbConfig`] from the wallet environment and
254 /// base data directory.
255 pub fn new(wallet_env: WalletEnv, lexe_data_dir: PathBuf) -> Self {
256 let env_db_dir = lexe_data_dir.join(wallet_env.to_string());
257 Self {
258 lexe_data_dir,
259 env_db_dir,
260 }
261 }
262
263 /// The top-level, root, base data directory for Lexe-related data.
264 pub fn lexe_data_dir(&self) -> &PathBuf {
265 &self.lexe_data_dir
266 }
267
268 /// The database directory for this wallet environment.
269 pub fn env_db_dir(&self) -> &PathBuf {
270 &self.env_db_dir
271 }
272}
273
274// --- impl WalletUserDbConfig --- //
275
276impl WalletUserDbConfig {
277 /// Construct a new [`WalletUserDbConfig`] from the environment database
278 /// config and user public key.
279 pub fn new(env_db_config: WalletEnvDbConfig, user_pk: UserPk) -> Self {
280 let user_db_dir = env_db_config.env_db_dir.join(user_pk.to_string());
281 Self {
282 env_db_config,
283 user_pk,
284 user_db_dir,
285 }
286 }
287
288 /// Construct a new [`WalletUserDbConfig`] from credentials and the
289 /// environment database config.
290 pub fn from_credentials(
291 credentials: CredentialsRef<'_>,
292 env_db_config: WalletEnvDbConfig,
293 ) -> anyhow::Result<Self> {
294 // Is `Some(_)` if the credentials were created by `node-v0.8.11+`.
295 let user_pk = credentials.user_pk().context(
296 "Client credentials are out of date. \
297 Please create a new one from within the Lexe wallet app.",
298 )?;
299 Ok(Self::new(env_db_config, user_pk))
300 }
301
302 /// The environment-level database configuration.
303 pub fn env_db_config(&self) -> &WalletEnvDbConfig {
304 &self.env_db_config
305 }
306
307 /// The user public key.
308 pub fn user_pk(&self) -> UserPk {
309 self.user_pk
310 }
311
312 /// The top-level, root, base data directory for Lexe-related data.
313 ///
314 /// `<lexe_data_dir>`
315 pub fn lexe_data_dir(&self) -> &PathBuf {
316 self.env_db_config.lexe_data_dir()
317 }
318
319 /// The database directory for this wallet environment.
320 ///
321 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>`
322 pub fn env_db_dir(&self) -> &PathBuf {
323 self.env_db_config.env_db_dir()
324 }
325
326 /// The user-specific database directory.
327 ///
328 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>/<user_pk>`
329 pub fn user_db_dir(&self) -> &PathBuf {
330 &self.user_db_dir
331 }
332
333 /// Payment records and history.
334 ///
335 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>/<user_pk>/payments_db`
336 // Unstable
337 pub(crate) fn payments_db_dir(&self) -> PathBuf {
338 self.user_db_dir.join("payments_db")
339 }
340
341 /// `check_address` address cursors.
342 ///
343 /// `<lexe_data_dir>/<deploy_env>-<network>-<use_sgx>/<user_pk>/
344 /// check_address_db`
345 // Unstable
346 pub(crate) fn check_address_db_dir(&self) -> PathBuf {
347 self.user_db_dir.join("check_address_db")
348 }
349
350 // --- Old dirs --- //
351
352 /// Old payment database directories that may need cleanup after migration.
353 pub(crate) fn old_payment_db_dirs(&self) -> [PathBuf; 1] {
354 [
355 // BasicPaymentV1
356 self.user_db_dir.join("payment_db"),
357 // Add more here as needed
358 ]
359 }
360
361 /// Old provision database directory that may need cleanup.
362 pub(crate) fn old_provision_db_dir(&self) -> PathBuf {
363 self.user_db_dir.join("provision_db")
364 }
365}
366
367#[cfg(test)]
368mod test {
369 use std::str::FromStr;
370
371 use super::*;
372
373 /// Ensure SDK_USER_AGENT parses correctly and has the expected format.
374 #[test]
375 fn test_sdk_user_agent() {
376 let user_agent: &str = &SDK_USER_AGENT;
377
378 // Should match: "lexe/<semver> node/<semver>"
379 let (sdk_part, node_part) = user_agent
380 .split_once(" node/")
381 .expect("Missing ' node/' separator");
382
383 // Validate sdk part: "lexe/<version>"
384 let sdk_version_str = sdk_part
385 .strip_prefix("lexe/")
386 .expect("Missing 'lexe/' prefix");
387 let _sdk_version = semver::Version::from_str(sdk_version_str)
388 .expect("Invalid SDK semver version");
389
390 // Validate node version
391 let _node_version = semver::Version::from_str(node_part)
392 .expect("Invalid node semver version");
393 }
394
395 /// Ensure the prefix is prepended to the user agent.
396 #[cfg(feature = "unstable")]
397 #[test]
398 fn test_with_user_agent_prefix() {
399 let env_config = WalletEnvConfig::mainnet()
400 .with_user_agent_prefix("sdk-sidecar/0.4.2");
401 let expected = format!("sdk-sidecar/0.4.2 {}", *SDK_USER_AGENT);
402 assert_eq!(env_config.user_agent(), expected);
403 }
404}