config.rs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. use std::path::PathBuf;
  2. use bitcoin::hashes::{sha256, Hash};
  3. use cdk::nuts::{CurrencyUnit, PublicKey};
  4. use cdk::Amount;
  5. use cdk_axum::cache;
  6. use cdk_common::common::QuoteTTL;
  7. use config::{Config, ConfigError, File};
  8. use serde::{Deserialize, Serialize};
  9. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
  10. #[serde(rename_all = "lowercase")]
  11. pub enum LoggingOutput {
  12. /// Log to stderr only
  13. Stderr,
  14. /// Log to file only
  15. File,
  16. /// Log to both stderr and file (default)
  17. #[default]
  18. Both,
  19. }
  20. impl std::str::FromStr for LoggingOutput {
  21. type Err = String;
  22. fn from_str(s: &str) -> Result<Self, Self::Err> {
  23. match s.to_lowercase().as_str() {
  24. "stderr" => Ok(LoggingOutput::Stderr),
  25. "file" => Ok(LoggingOutput::File),
  26. "both" => Ok(LoggingOutput::Both),
  27. _ => Err(format!(
  28. "Unknown logging output: {s}. Valid options: stdout, file, both"
  29. )),
  30. }
  31. }
  32. }
  33. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  34. pub struct LoggingConfig {
  35. /// Where to output logs: stdout, file, or both
  36. #[serde(default)]
  37. pub output: LoggingOutput,
  38. /// Log level for console output (when stdout or both)
  39. pub console_level: Option<String>,
  40. /// Log level for file output (when file or both)
  41. pub file_level: Option<String>,
  42. }
  43. #[derive(Clone, Serialize, Deserialize)]
  44. pub struct Info {
  45. pub url: String,
  46. pub listen_host: String,
  47. pub listen_port: u16,
  48. /// Overrides mnemonic
  49. pub seed: Option<String>,
  50. pub mnemonic: Option<String>,
  51. pub signatory_url: Option<String>,
  52. pub signatory_certs: Option<String>,
  53. pub input_fee_ppk: Option<u64>,
  54. pub http_cache: cache::Config,
  55. /// Logging configuration
  56. #[serde(default)]
  57. pub logging: LoggingConfig,
  58. /// When this is set to true, the mint exposes a Swagger UI for it's API at
  59. /// `[listen_host]:[listen_port]/swagger-ui`
  60. ///
  61. /// This requires `mintd` was built with the `swagger` feature flag.
  62. pub enable_swagger_ui: Option<bool>,
  63. /// Optional persisted quote TTL values (seconds) to initialize the database with
  64. /// when RPC is disabled or on first-run when RPC is enabled.
  65. /// If not provided, defaults are used.
  66. #[serde(skip_serializing_if = "Option::is_none")]
  67. pub quote_ttl: Option<QuoteTTL>,
  68. }
  69. impl Default for Info {
  70. fn default() -> Self {
  71. Info {
  72. url: String::new(),
  73. listen_host: "127.0.0.1".to_string(),
  74. listen_port: 8091, // Default to port 8091 instead of 0
  75. seed: None,
  76. mnemonic: None,
  77. signatory_url: None,
  78. signatory_certs: None,
  79. input_fee_ppk: None,
  80. http_cache: cache::Config::default(),
  81. enable_swagger_ui: None,
  82. logging: LoggingConfig::default(),
  83. quote_ttl: None,
  84. }
  85. }
  86. }
  87. impl std::fmt::Debug for Info {
  88. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  89. // Use a fallback approach that won't panic
  90. let mnemonic_display: String = {
  91. if let Some(mnemonic) = self.mnemonic.as_ref() {
  92. let hash = sha256::Hash::hash(mnemonic.as_bytes());
  93. format!("<hashed: {hash}>")
  94. } else {
  95. format!("<url: {}>", self.signatory_url.clone().unwrap_or_default())
  96. }
  97. };
  98. f.debug_struct("Info")
  99. .field("url", &self.url)
  100. .field("listen_host", &self.listen_host)
  101. .field("listen_port", &self.listen_port)
  102. .field("mnemonic", &mnemonic_display)
  103. .field("input_fee_ppk", &self.input_fee_ppk)
  104. .field("http_cache", &self.http_cache)
  105. .field("logging", &self.logging)
  106. .field("enable_swagger_ui", &self.enable_swagger_ui)
  107. .finish()
  108. }
  109. }
  110. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
  111. #[serde(rename_all = "lowercase")]
  112. pub enum LnBackend {
  113. #[default]
  114. None,
  115. #[cfg(feature = "cln")]
  116. Cln,
  117. #[cfg(feature = "lnbits")]
  118. LNbits,
  119. #[cfg(feature = "fakewallet")]
  120. FakeWallet,
  121. #[cfg(feature = "lnd")]
  122. Lnd,
  123. #[cfg(feature = "ldk-node")]
  124. LdkNode,
  125. #[cfg(feature = "grpc-processor")]
  126. GrpcProcessor,
  127. }
  128. impl std::str::FromStr for LnBackend {
  129. type Err = String;
  130. fn from_str(s: &str) -> Result<Self, Self::Err> {
  131. match s.to_lowercase().as_str() {
  132. #[cfg(feature = "cln")]
  133. "cln" => Ok(LnBackend::Cln),
  134. #[cfg(feature = "lnbits")]
  135. "lnbits" => Ok(LnBackend::LNbits),
  136. #[cfg(feature = "fakewallet")]
  137. "fakewallet" => Ok(LnBackend::FakeWallet),
  138. #[cfg(feature = "lnd")]
  139. "lnd" => Ok(LnBackend::Lnd),
  140. #[cfg(feature = "ldk-node")]
  141. "ldk-node" | "ldknode" => Ok(LnBackend::LdkNode),
  142. #[cfg(feature = "grpc-processor")]
  143. "grpcprocessor" => Ok(LnBackend::GrpcProcessor),
  144. _ => Err(format!("Unknown Lightning backend: {s}")),
  145. }
  146. }
  147. }
  148. #[derive(Debug, Clone, Serialize, Deserialize)]
  149. pub struct Ln {
  150. pub ln_backend: LnBackend,
  151. pub invoice_description: Option<String>,
  152. pub min_mint: Amount,
  153. pub max_mint: Amount,
  154. pub min_melt: Amount,
  155. pub max_melt: Amount,
  156. }
  157. impl Default for Ln {
  158. fn default() -> Self {
  159. Ln {
  160. ln_backend: LnBackend::default(),
  161. invoice_description: None,
  162. min_mint: 1.into(),
  163. max_mint: 500_000.into(),
  164. min_melt: 1.into(),
  165. max_melt: 500_000.into(),
  166. }
  167. }
  168. }
  169. #[cfg(feature = "lnbits")]
  170. #[derive(Debug, Clone, Serialize, Deserialize)]
  171. pub struct LNbits {
  172. pub admin_api_key: String,
  173. pub invoice_api_key: String,
  174. pub lnbits_api: String,
  175. #[serde(default = "default_fee_percent")]
  176. pub fee_percent: f32,
  177. #[serde(default = "default_reserve_fee_min")]
  178. pub reserve_fee_min: Amount,
  179. }
  180. #[cfg(feature = "lnbits")]
  181. impl Default for LNbits {
  182. fn default() -> Self {
  183. Self {
  184. admin_api_key: String::new(),
  185. invoice_api_key: String::new(),
  186. lnbits_api: String::new(),
  187. fee_percent: 0.02,
  188. reserve_fee_min: 2.into(),
  189. }
  190. }
  191. }
  192. #[cfg(feature = "cln")]
  193. #[derive(Debug, Clone, Serialize, Deserialize)]
  194. pub struct Cln {
  195. pub rpc_path: PathBuf,
  196. #[serde(default = "default_cln_bolt12")]
  197. pub bolt12: bool,
  198. #[serde(default = "default_fee_percent")]
  199. pub fee_percent: f32,
  200. #[serde(default = "default_reserve_fee_min")]
  201. pub reserve_fee_min: Amount,
  202. }
  203. #[cfg(feature = "cln")]
  204. impl Default for Cln {
  205. fn default() -> Self {
  206. Self {
  207. rpc_path: PathBuf::new(),
  208. bolt12: true,
  209. fee_percent: 0.02,
  210. reserve_fee_min: 2.into(),
  211. }
  212. }
  213. }
  214. #[cfg(feature = "cln")]
  215. fn default_cln_bolt12() -> bool {
  216. true
  217. }
  218. #[cfg(feature = "lnd")]
  219. #[derive(Debug, Clone, Serialize, Deserialize)]
  220. pub struct Lnd {
  221. pub address: String,
  222. pub cert_file: PathBuf,
  223. pub macaroon_file: PathBuf,
  224. #[serde(default = "default_fee_percent")]
  225. pub fee_percent: f32,
  226. #[serde(default = "default_reserve_fee_min")]
  227. pub reserve_fee_min: Amount,
  228. }
  229. #[cfg(feature = "lnd")]
  230. impl Default for Lnd {
  231. fn default() -> Self {
  232. Self {
  233. address: String::new(),
  234. cert_file: PathBuf::new(),
  235. macaroon_file: PathBuf::new(),
  236. fee_percent: 0.02,
  237. reserve_fee_min: 2.into(),
  238. }
  239. }
  240. }
  241. #[cfg(feature = "ldk-node")]
  242. #[derive(Debug, Clone, Serialize, Deserialize)]
  243. pub struct LdkNode {
  244. /// Fee percentage (e.g., 0.02 for 2%)
  245. #[serde(default = "default_ldk_fee_percent")]
  246. pub fee_percent: f32,
  247. /// Minimum reserve fee
  248. #[serde(default = "default_ldk_reserve_fee_min")]
  249. pub reserve_fee_min: Amount,
  250. /// Bitcoin network (mainnet, testnet, signet, regtest)
  251. pub bitcoin_network: Option<String>,
  252. /// Chain source type (esplora or bitcoinrpc)
  253. pub chain_source_type: Option<String>,
  254. /// Esplora URL (when chain_source_type = "esplora")
  255. pub esplora_url: Option<String>,
  256. /// Bitcoin RPC configuration (when chain_source_type = "bitcoinrpc")
  257. pub bitcoind_rpc_host: Option<String>,
  258. pub bitcoind_rpc_port: Option<u16>,
  259. pub bitcoind_rpc_user: Option<String>,
  260. pub bitcoind_rpc_password: Option<String>,
  261. /// Storage directory path
  262. pub storage_dir_path: Option<String>,
  263. /// LDK node listening host
  264. pub ldk_node_host: Option<String>,
  265. /// LDK node listening port
  266. pub ldk_node_port: Option<u16>,
  267. /// Gossip source type (p2p or rgs)
  268. pub gossip_source_type: Option<String>,
  269. /// Rapid Gossip Sync URL (when gossip_source_type = "rgs")
  270. pub rgs_url: Option<String>,
  271. /// Webserver host (defaults to 127.0.0.1)
  272. #[serde(default = "default_webserver_host")]
  273. pub webserver_host: Option<String>,
  274. /// Webserver port
  275. #[serde(default = "default_webserver_port")]
  276. pub webserver_port: Option<u16>,
  277. }
  278. #[cfg(feature = "ldk-node")]
  279. impl Default for LdkNode {
  280. fn default() -> Self {
  281. Self {
  282. fee_percent: default_ldk_fee_percent(),
  283. reserve_fee_min: default_ldk_reserve_fee_min(),
  284. bitcoin_network: None,
  285. chain_source_type: None,
  286. esplora_url: None,
  287. bitcoind_rpc_host: None,
  288. bitcoind_rpc_port: None,
  289. bitcoind_rpc_user: None,
  290. bitcoind_rpc_password: None,
  291. storage_dir_path: None,
  292. ldk_node_host: None,
  293. ldk_node_port: None,
  294. gossip_source_type: None,
  295. rgs_url: None,
  296. webserver_host: default_webserver_host(),
  297. webserver_port: default_webserver_port(),
  298. }
  299. }
  300. }
  301. #[cfg(feature = "ldk-node")]
  302. fn default_ldk_fee_percent() -> f32 {
  303. 0.04
  304. }
  305. #[cfg(feature = "ldk-node")]
  306. fn default_ldk_reserve_fee_min() -> Amount {
  307. 4.into()
  308. }
  309. #[cfg(feature = "ldk-node")]
  310. fn default_webserver_host() -> Option<String> {
  311. Some("127.0.0.1".to_string())
  312. }
  313. #[cfg(feature = "ldk-node")]
  314. fn default_webserver_port() -> Option<u16> {
  315. Some(8091)
  316. }
  317. #[cfg(feature = "fakewallet")]
  318. #[derive(Debug, Clone, Serialize, Deserialize)]
  319. pub struct FakeWallet {
  320. pub supported_units: Vec<CurrencyUnit>,
  321. pub fee_percent: f32,
  322. pub reserve_fee_min: Amount,
  323. #[serde(default = "default_min_delay_time")]
  324. pub min_delay_time: u64,
  325. #[serde(default = "default_max_delay_time")]
  326. pub max_delay_time: u64,
  327. }
  328. #[cfg(feature = "fakewallet")]
  329. impl Default for FakeWallet {
  330. fn default() -> Self {
  331. Self {
  332. supported_units: vec![CurrencyUnit::Sat],
  333. fee_percent: 0.02,
  334. reserve_fee_min: 2.into(),
  335. min_delay_time: 1,
  336. max_delay_time: 3,
  337. }
  338. }
  339. }
  340. // Helper functions to provide default values
  341. // Common fee defaults for all backends
  342. #[cfg(any(feature = "cln", feature = "lnbits", feature = "lnd"))]
  343. fn default_fee_percent() -> f32 {
  344. 0.02
  345. }
  346. #[cfg(any(feature = "cln", feature = "lnbits", feature = "lnd"))]
  347. fn default_reserve_fee_min() -> Amount {
  348. 2.into()
  349. }
  350. #[cfg(feature = "fakewallet")]
  351. fn default_min_delay_time() -> u64 {
  352. 1
  353. }
  354. #[cfg(feature = "fakewallet")]
  355. fn default_max_delay_time() -> u64 {
  356. 3
  357. }
  358. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
  359. pub struct GrpcProcessor {
  360. #[serde(default)]
  361. pub supported_units: Vec<CurrencyUnit>,
  362. #[serde(default = "default_grpc_addr")]
  363. pub addr: String,
  364. #[serde(default = "default_grpc_port")]
  365. pub port: u16,
  366. #[serde(default)]
  367. pub tls_dir: Option<PathBuf>,
  368. }
  369. impl Default for GrpcProcessor {
  370. fn default() -> Self {
  371. Self {
  372. supported_units: Vec::new(),
  373. addr: default_grpc_addr(),
  374. port: default_grpc_port(),
  375. tls_dir: None,
  376. }
  377. }
  378. }
  379. fn default_grpc_addr() -> String {
  380. "127.0.0.1".to_string()
  381. }
  382. fn default_grpc_port() -> u16 {
  383. 50051
  384. }
  385. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
  386. #[serde(rename_all = "lowercase")]
  387. pub enum DatabaseEngine {
  388. #[default]
  389. Sqlite,
  390. Postgres,
  391. }
  392. impl std::str::FromStr for DatabaseEngine {
  393. type Err = String;
  394. fn from_str(s: &str) -> Result<Self, Self::Err> {
  395. match s.to_lowercase().as_str() {
  396. "sqlite" => Ok(DatabaseEngine::Sqlite),
  397. "postgres" => Ok(DatabaseEngine::Postgres),
  398. _ => Err(format!("Unknown database engine: {s}")),
  399. }
  400. }
  401. }
  402. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  403. pub struct Database {
  404. pub engine: DatabaseEngine,
  405. pub postgres: Option<PostgresConfig>,
  406. }
  407. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  408. pub struct AuthDatabase {
  409. pub postgres: Option<PostgresAuthConfig>,
  410. }
  411. #[derive(Debug, Clone, Serialize, Deserialize)]
  412. pub struct PostgresAuthConfig {
  413. pub url: String,
  414. pub tls_mode: Option<String>,
  415. pub max_connections: Option<usize>,
  416. pub connection_timeout_seconds: Option<u64>,
  417. }
  418. impl Default for PostgresAuthConfig {
  419. fn default() -> Self {
  420. Self {
  421. url: String::new(),
  422. tls_mode: Some("disable".to_string()),
  423. max_connections: Some(20),
  424. connection_timeout_seconds: Some(10),
  425. }
  426. }
  427. }
  428. #[derive(Debug, Clone, Serialize, Deserialize)]
  429. pub struct PostgresConfig {
  430. pub url: String,
  431. pub tls_mode: Option<String>,
  432. pub max_connections: Option<usize>,
  433. pub connection_timeout_seconds: Option<u64>,
  434. }
  435. impl Default for PostgresConfig {
  436. fn default() -> Self {
  437. Self {
  438. url: String::new(),
  439. tls_mode: Some("disable".to_string()),
  440. max_connections: Some(20),
  441. connection_timeout_seconds: Some(10),
  442. }
  443. }
  444. }
  445. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
  446. #[serde(rename_all = "lowercase")]
  447. pub enum AuthType {
  448. Clear,
  449. Blind,
  450. #[default]
  451. None,
  452. }
  453. impl std::str::FromStr for AuthType {
  454. type Err = String;
  455. fn from_str(s: &str) -> Result<Self, Self::Err> {
  456. match s.to_lowercase().as_str() {
  457. "clear" => Ok(AuthType::Clear),
  458. "blind" => Ok(AuthType::Blind),
  459. "none" => Ok(AuthType::None),
  460. _ => Err(format!("Unknown auth type: {s}")),
  461. }
  462. }
  463. }
  464. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  465. pub struct Auth {
  466. #[serde(default)]
  467. pub auth_enabled: bool,
  468. pub openid_discovery: String,
  469. pub openid_client_id: String,
  470. pub mint_max_bat: u64,
  471. #[serde(default = "default_blind")]
  472. pub mint: AuthType,
  473. #[serde(default)]
  474. pub get_mint_quote: AuthType,
  475. #[serde(default)]
  476. pub check_mint_quote: AuthType,
  477. #[serde(default)]
  478. pub melt: AuthType,
  479. #[serde(default)]
  480. pub get_melt_quote: AuthType,
  481. #[serde(default)]
  482. pub check_melt_quote: AuthType,
  483. #[serde(default = "default_blind")]
  484. pub swap: AuthType,
  485. #[serde(default = "default_blind")]
  486. pub restore: AuthType,
  487. #[serde(default)]
  488. pub check_proof_state: AuthType,
  489. /// Enable WebSocket authentication support
  490. #[serde(default = "default_blind")]
  491. pub websocket_auth: AuthType,
  492. }
  493. fn default_blind() -> AuthType {
  494. AuthType::Blind
  495. }
  496. /// CDK settings, derived from `config.toml`
  497. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  498. pub struct Settings {
  499. pub info: Info,
  500. pub mint_info: MintInfo,
  501. pub ln: Ln,
  502. #[cfg(feature = "cln")]
  503. pub cln: Option<Cln>,
  504. #[cfg(feature = "lnbits")]
  505. pub lnbits: Option<LNbits>,
  506. #[cfg(feature = "lnd")]
  507. pub lnd: Option<Lnd>,
  508. #[cfg(feature = "ldk-node")]
  509. pub ldk_node: Option<LdkNode>,
  510. #[cfg(feature = "fakewallet")]
  511. pub fake_wallet: Option<FakeWallet>,
  512. pub grpc_processor: Option<GrpcProcessor>,
  513. pub database: Database,
  514. #[cfg(feature = "auth")]
  515. pub auth_database: Option<AuthDatabase>,
  516. #[cfg(feature = "management-rpc")]
  517. pub mint_management_rpc: Option<MintManagementRpc>,
  518. pub auth: Option<Auth>,
  519. #[cfg(feature = "prometheus")]
  520. pub prometheus: Option<Prometheus>,
  521. }
  522. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  523. #[cfg(feature = "prometheus")]
  524. pub struct Prometheus {
  525. pub enabled: bool,
  526. pub address: Option<String>,
  527. pub port: Option<u16>,
  528. }
  529. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  530. pub struct MintInfo {
  531. /// name of the mint and should be recognizable
  532. pub name: String,
  533. /// hex pubkey of the mint
  534. pub pubkey: Option<PublicKey>,
  535. /// short description of the mint
  536. pub description: String,
  537. /// long description
  538. pub description_long: Option<String>,
  539. /// url to the mint icon
  540. pub icon_url: Option<String>,
  541. /// message of the day that the wallet must display to the user
  542. pub motd: Option<String>,
  543. /// Nostr publickey
  544. pub contact_nostr_public_key: Option<String>,
  545. /// Contact email
  546. pub contact_email: Option<String>,
  547. /// URL to the terms of service
  548. pub tos_url: Option<String>,
  549. }
  550. #[cfg(feature = "management-rpc")]
  551. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  552. pub struct MintManagementRpc {
  553. /// When this is set to `true` the mint use the config file for the initial set up on first start.
  554. /// Changes to the `[mint_info]` after this **MUST** be made via the RPC changes to the config file or env vars will be ignored.
  555. pub enabled: bool,
  556. pub address: Option<String>,
  557. pub port: Option<u16>,
  558. pub tls_dir_path: Option<PathBuf>,
  559. }
  560. impl Settings {
  561. #[must_use]
  562. pub fn new<P>(config_file_name: Option<P>) -> Self
  563. where
  564. P: Into<PathBuf>,
  565. {
  566. let default_settings = Self::default();
  567. // attempt to construct settings with file
  568. let from_file = Self::new_from_default(&default_settings, config_file_name);
  569. match from_file {
  570. Ok(f) => f,
  571. Err(e) => {
  572. tracing::error!(
  573. "Error reading config file, falling back to defaults. Error: {e:?}"
  574. );
  575. default_settings
  576. }
  577. }
  578. }
  579. fn new_from_default<P>(
  580. default: &Settings,
  581. config_file_name: Option<P>,
  582. ) -> Result<Self, ConfigError>
  583. where
  584. P: Into<PathBuf>,
  585. {
  586. let mut default_config_file_name = home::home_dir()
  587. .ok_or(ConfigError::NotFound("Config Path".to_string()))?
  588. .join("cashu-rs-mint");
  589. default_config_file_name.push("config.toml");
  590. let config: String = match config_file_name {
  591. Some(value) => value.into().to_string_lossy().to_string(),
  592. None => default_config_file_name.to_string_lossy().to_string(),
  593. };
  594. let builder = Config::builder();
  595. let config: Config = builder
  596. // use defaults
  597. .add_source(Config::try_from(default)?)
  598. // override with file contents
  599. .add_source(File::with_name(&config))
  600. .build()?;
  601. let settings: Settings = config.try_deserialize()?;
  602. Ok(settings)
  603. }
  604. }
  605. #[cfg(test)]
  606. mod tests {
  607. use super::*;
  608. #[test]
  609. fn test_info_debug_impl() {
  610. // Create a sample Info struct with test data
  611. let info = Info {
  612. url: "http://example.com".to_string(),
  613. listen_host: "127.0.0.1".to_string(),
  614. listen_port: 8080,
  615. mnemonic: Some("test secret mnemonic phrase".to_string()),
  616. input_fee_ppk: Some(100),
  617. ..Default::default()
  618. };
  619. // Convert the Info struct to a debug string
  620. let debug_output = format!("{info:?}");
  621. // Verify the debug output contains expected fields
  622. assert!(debug_output.contains("url: \"http://example.com\""));
  623. assert!(debug_output.contains("listen_host: \"127.0.0.1\""));
  624. assert!(debug_output.contains("listen_port: 8080"));
  625. // The mnemonic should be hashed, not displayed in plaintext
  626. assert!(!debug_output.contains("test secret mnemonic phrase"));
  627. assert!(debug_output.contains("<hashed: "));
  628. assert!(debug_output.contains("input_fee_ppk: Some(100)"));
  629. }
  630. #[test]
  631. fn test_info_debug_with_empty_mnemonic() {
  632. // Test with an empty mnemonic to ensure it doesn't panic
  633. let info = Info {
  634. url: "http://example.com".to_string(),
  635. listen_host: "127.0.0.1".to_string(),
  636. listen_port: 8080,
  637. mnemonic: Some("".to_string()), // Empty mnemonic
  638. enable_swagger_ui: Some(false),
  639. ..Default::default()
  640. };
  641. // This should not panic
  642. let debug_output = format!("{:?}", info);
  643. // The empty mnemonic should still be hashed
  644. assert!(debug_output.contains("<hashed: "));
  645. }
  646. #[test]
  647. fn test_info_debug_with_special_chars() {
  648. // Test with a mnemonic containing special characters
  649. let info = Info {
  650. url: "http://example.com".to_string(),
  651. listen_host: "127.0.0.1".to_string(),
  652. listen_port: 8080,
  653. mnemonic: Some("特殊字符 !@#$%^&*()".to_string()), // Special characters
  654. ..Default::default()
  655. };
  656. // This should not panic
  657. let debug_output = format!("{:?}", info);
  658. // The mnemonic with special chars should be hashed
  659. assert!(!debug_output.contains("特殊字符 !@#$%^&*()"));
  660. assert!(debug_output.contains("<hashed: "));
  661. }
  662. /// Test that configuration can be loaded purely from environment variables
  663. /// without requiring a config.toml file with backend sections.
  664. ///
  665. /// This test runs sequentially for all enabled backends to avoid env var interference.
  666. #[test]
  667. fn test_env_var_only_config_all_backends() {
  668. // Run each backend test sequentially
  669. #[cfg(feature = "lnd")]
  670. test_lnd_env_config();
  671. #[cfg(feature = "cln")]
  672. test_cln_env_config();
  673. #[cfg(feature = "lnbits")]
  674. test_lnbits_env_config();
  675. #[cfg(feature = "fakewallet")]
  676. test_fakewallet_env_config();
  677. #[cfg(feature = "grpc-processor")]
  678. test_grpc_processor_env_config();
  679. #[cfg(feature = "ldk-node")]
  680. test_ldk_node_env_config();
  681. }
  682. #[cfg(feature = "lnd")]
  683. fn test_lnd_env_config() {
  684. use std::path::PathBuf;
  685. use std::{env, fs};
  686. // Create a temporary directory for config file
  687. let temp_dir = env::temp_dir().join("cdk_test_env_vars");
  688. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  689. let config_path = temp_dir.join("config.toml");
  690. // Create a minimal config.toml with backend set but NO [lnd] section
  691. let config_content = r#"
  692. [ln]
  693. backend = "lnd"
  694. min_mint = 1
  695. max_mint = 500000
  696. min_melt = 1
  697. max_melt = 500000
  698. "#;
  699. fs::write(&config_path, config_content).expect("Failed to write config file");
  700. // Set environment variables for LND configuration
  701. env::set_var(crate::env_vars::ENV_LN_BACKEND, "lnd");
  702. env::set_var(crate::env_vars::ENV_LND_ADDRESS, "https://localhost:10009");
  703. env::set_var(crate::env_vars::ENV_LND_CERT_FILE, "/tmp/test_tls.cert");
  704. env::set_var(
  705. crate::env_vars::ENV_LND_MACAROON_FILE,
  706. "/tmp/test_admin.macaroon",
  707. );
  708. env::set_var(crate::env_vars::ENV_LND_FEE_PERCENT, "0.01");
  709. env::set_var(crate::env_vars::ENV_LND_RESERVE_FEE_MIN, "4");
  710. // Load settings and apply environment variables (same as production code)
  711. let mut settings = Settings::new(Some(&config_path));
  712. settings.from_env().expect("Failed to apply env vars");
  713. // Verify that settings were populated from env vars
  714. assert!(settings.lnd.is_some());
  715. let lnd_config = settings.lnd.as_ref().unwrap();
  716. assert_eq!(lnd_config.address, "https://localhost:10009");
  717. assert_eq!(lnd_config.cert_file, PathBuf::from("/tmp/test_tls.cert"));
  718. assert_eq!(
  719. lnd_config.macaroon_file,
  720. PathBuf::from("/tmp/test_admin.macaroon")
  721. );
  722. assert_eq!(lnd_config.fee_percent, 0.01);
  723. let reserve_fee_u64: u64 = lnd_config.reserve_fee_min.into();
  724. assert_eq!(reserve_fee_u64, 4);
  725. // Cleanup env vars
  726. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  727. env::remove_var(crate::env_vars::ENV_LND_ADDRESS);
  728. env::remove_var(crate::env_vars::ENV_LND_CERT_FILE);
  729. env::remove_var(crate::env_vars::ENV_LND_MACAROON_FILE);
  730. env::remove_var(crate::env_vars::ENV_LND_FEE_PERCENT);
  731. env::remove_var(crate::env_vars::ENV_LND_RESERVE_FEE_MIN);
  732. // Cleanup test file
  733. let _ = fs::remove_dir_all(&temp_dir);
  734. }
  735. #[cfg(feature = "cln")]
  736. fn test_cln_env_config() {
  737. use std::path::PathBuf;
  738. use std::{env, fs};
  739. // Create a temporary directory for config file
  740. let temp_dir = env::temp_dir().join("cdk_test_env_vars_cln");
  741. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  742. let config_path = temp_dir.join("config.toml");
  743. // Create a minimal config.toml with backend set but NO [cln] section
  744. let config_content = r#"
  745. [ln]
  746. backend = "cln"
  747. min_mint = 1
  748. max_mint = 500000
  749. min_melt = 1
  750. max_melt = 500000
  751. "#;
  752. fs::write(&config_path, config_content).expect("Failed to write config file");
  753. // Set environment variables for CLN configuration
  754. env::set_var(crate::env_vars::ENV_LN_BACKEND, "cln");
  755. env::set_var(crate::env_vars::ENV_CLN_RPC_PATH, "/tmp/lightning-rpc");
  756. env::set_var(crate::env_vars::ENV_CLN_BOLT12, "false");
  757. env::set_var(crate::env_vars::ENV_CLN_FEE_PERCENT, "0.01");
  758. env::set_var(crate::env_vars::ENV_CLN_RESERVE_FEE_MIN, "4");
  759. // Load settings and apply environment variables (same as production code)
  760. let mut settings = Settings::new(Some(&config_path));
  761. settings.from_env().expect("Failed to apply env vars");
  762. // Verify that settings were populated from env vars
  763. assert!(settings.cln.is_some());
  764. let cln_config = settings.cln.as_ref().unwrap();
  765. assert_eq!(cln_config.rpc_path, PathBuf::from("/tmp/lightning-rpc"));
  766. assert_eq!(cln_config.bolt12, false);
  767. assert_eq!(cln_config.fee_percent, 0.01);
  768. let reserve_fee_u64: u64 = cln_config.reserve_fee_min.into();
  769. assert_eq!(reserve_fee_u64, 4);
  770. // Cleanup env vars
  771. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  772. env::remove_var(crate::env_vars::ENV_CLN_RPC_PATH);
  773. env::remove_var(crate::env_vars::ENV_CLN_BOLT12);
  774. env::remove_var(crate::env_vars::ENV_CLN_FEE_PERCENT);
  775. env::remove_var(crate::env_vars::ENV_CLN_RESERVE_FEE_MIN);
  776. // Cleanup test file
  777. let _ = fs::remove_dir_all(&temp_dir);
  778. }
  779. #[cfg(feature = "lnbits")]
  780. fn test_lnbits_env_config() {
  781. use std::{env, fs};
  782. // Create a temporary directory for config file
  783. let temp_dir = env::temp_dir().join("cdk_test_env_vars_lnbits");
  784. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  785. let config_path = temp_dir.join("config.toml");
  786. // Create a minimal config.toml with backend set but NO [lnbits] section
  787. let config_content = r#"
  788. [ln]
  789. backend = "lnbits"
  790. min_mint = 1
  791. max_mint = 500000
  792. min_melt = 1
  793. max_melt = 500000
  794. "#;
  795. fs::write(&config_path, config_content).expect("Failed to write config file");
  796. // Set environment variables for LNbits configuration
  797. env::set_var(crate::env_vars::ENV_LN_BACKEND, "lnbits");
  798. env::set_var(crate::env_vars::ENV_LNBITS_ADMIN_API_KEY, "test_admin_key");
  799. env::set_var(
  800. crate::env_vars::ENV_LNBITS_INVOICE_API_KEY,
  801. "test_invoice_key",
  802. );
  803. env::set_var(
  804. crate::env_vars::ENV_LNBITS_API,
  805. "https://lnbits.example.com",
  806. );
  807. env::set_var(crate::env_vars::ENV_LNBITS_FEE_PERCENT, "0.02");
  808. env::set_var(crate::env_vars::ENV_LNBITS_RESERVE_FEE_MIN, "5");
  809. // Load settings and apply environment variables (same as production code)
  810. let mut settings = Settings::new(Some(&config_path));
  811. settings.from_env().expect("Failed to apply env vars");
  812. // Verify that settings were populated from env vars
  813. assert!(settings.lnbits.is_some());
  814. let lnbits_config = settings.lnbits.as_ref().unwrap();
  815. assert_eq!(lnbits_config.admin_api_key, "test_admin_key");
  816. assert_eq!(lnbits_config.invoice_api_key, "test_invoice_key");
  817. assert_eq!(lnbits_config.lnbits_api, "https://lnbits.example.com");
  818. assert_eq!(lnbits_config.fee_percent, 0.02);
  819. let reserve_fee_u64: u64 = lnbits_config.reserve_fee_min.into();
  820. assert_eq!(reserve_fee_u64, 5);
  821. // Cleanup env vars
  822. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  823. env::remove_var(crate::env_vars::ENV_LNBITS_ADMIN_API_KEY);
  824. env::remove_var(crate::env_vars::ENV_LNBITS_INVOICE_API_KEY);
  825. env::remove_var(crate::env_vars::ENV_LNBITS_API);
  826. env::remove_var(crate::env_vars::ENV_LNBITS_FEE_PERCENT);
  827. env::remove_var(crate::env_vars::ENV_LNBITS_RESERVE_FEE_MIN);
  828. // Cleanup test file
  829. let _ = fs::remove_dir_all(&temp_dir);
  830. }
  831. #[cfg(feature = "fakewallet")]
  832. fn test_fakewallet_env_config() {
  833. use std::{env, fs};
  834. // Create a temporary directory for config file
  835. let temp_dir = env::temp_dir().join("cdk_test_env_vars_fakewallet");
  836. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  837. let config_path = temp_dir.join("config.toml");
  838. // Create a minimal config.toml with backend set but NO [fake_wallet] section
  839. let config_content = r#"
  840. [ln]
  841. backend = "fakewallet"
  842. min_mint = 1
  843. max_mint = 500000
  844. min_melt = 1
  845. max_melt = 500000
  846. "#;
  847. fs::write(&config_path, config_content).expect("Failed to write config file");
  848. // Set environment variables for FakeWallet configuration
  849. env::set_var(crate::env_vars::ENV_LN_BACKEND, "fakewallet");
  850. env::set_var(crate::env_vars::ENV_FAKE_WALLET_SUPPORTED_UNITS, "sat,msat");
  851. env::set_var(crate::env_vars::ENV_FAKE_WALLET_FEE_PERCENT, "0.0");
  852. env::set_var(crate::env_vars::ENV_FAKE_WALLET_RESERVE_FEE_MIN, "0");
  853. env::set_var(crate::env_vars::ENV_FAKE_WALLET_MIN_DELAY, "0");
  854. env::set_var(crate::env_vars::ENV_FAKE_WALLET_MAX_DELAY, "5");
  855. // Load settings and apply environment variables (same as production code)
  856. let mut settings = Settings::new(Some(&config_path));
  857. settings.from_env().expect("Failed to apply env vars");
  858. // Verify that settings were populated from env vars
  859. assert!(settings.fake_wallet.is_some());
  860. let fakewallet_config = settings.fake_wallet.as_ref().unwrap();
  861. assert_eq!(fakewallet_config.fee_percent, 0.0);
  862. let reserve_fee_u64: u64 = fakewallet_config.reserve_fee_min.into();
  863. assert_eq!(reserve_fee_u64, 0);
  864. assert_eq!(fakewallet_config.min_delay_time, 0);
  865. assert_eq!(fakewallet_config.max_delay_time, 5);
  866. // Cleanup env vars
  867. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  868. env::remove_var(crate::env_vars::ENV_FAKE_WALLET_SUPPORTED_UNITS);
  869. env::remove_var(crate::env_vars::ENV_FAKE_WALLET_FEE_PERCENT);
  870. env::remove_var(crate::env_vars::ENV_FAKE_WALLET_RESERVE_FEE_MIN);
  871. env::remove_var(crate::env_vars::ENV_FAKE_WALLET_MIN_DELAY);
  872. env::remove_var(crate::env_vars::ENV_FAKE_WALLET_MAX_DELAY);
  873. // Cleanup test file
  874. let _ = fs::remove_dir_all(&temp_dir);
  875. }
  876. #[cfg(feature = "grpc-processor")]
  877. fn test_grpc_processor_env_config() {
  878. use std::{env, fs};
  879. // Create a temporary directory for config file
  880. let temp_dir = env::temp_dir().join("cdk_test_env_vars_grpc");
  881. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  882. let config_path = temp_dir.join("config.toml");
  883. // Create a minimal config.toml with backend set but NO [grpc_processor] section
  884. let config_content = r#"
  885. [ln]
  886. backend = "grpcprocessor"
  887. min_mint = 1
  888. max_mint = 500000
  889. min_melt = 1
  890. max_melt = 500000
  891. "#;
  892. fs::write(&config_path, config_content).expect("Failed to write config file");
  893. // Set environment variables for GRPC Processor configuration
  894. env::set_var(crate::env_vars::ENV_LN_BACKEND, "grpcprocessor");
  895. env::set_var(
  896. crate::env_vars::ENV_GRPC_PROCESSOR_SUPPORTED_UNITS,
  897. "sat,msat",
  898. );
  899. env::set_var(crate::env_vars::ENV_GRPC_PROCESSOR_ADDRESS, "localhost");
  900. env::set_var(crate::env_vars::ENV_GRPC_PROCESSOR_PORT, "50051");
  901. // Load settings and apply environment variables (same as production code)
  902. let mut settings = Settings::new(Some(&config_path));
  903. settings.from_env().expect("Failed to apply env vars");
  904. // Verify that settings were populated from env vars
  905. assert!(settings.grpc_processor.is_some());
  906. let grpc_config = settings.grpc_processor.as_ref().unwrap();
  907. assert_eq!(grpc_config.addr, "localhost");
  908. assert_eq!(grpc_config.port, 50051);
  909. // Cleanup env vars
  910. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  911. env::remove_var(crate::env_vars::ENV_GRPC_PROCESSOR_SUPPORTED_UNITS);
  912. env::remove_var(crate::env_vars::ENV_GRPC_PROCESSOR_ADDRESS);
  913. env::remove_var(crate::env_vars::ENV_GRPC_PROCESSOR_PORT);
  914. // Cleanup test file
  915. let _ = fs::remove_dir_all(&temp_dir);
  916. }
  917. #[cfg(feature = "ldk-node")]
  918. fn test_ldk_node_env_config() {
  919. use std::{env, fs};
  920. // Create a temporary directory for config file
  921. let temp_dir = env::temp_dir().join("cdk_test_env_vars_ldk");
  922. fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
  923. let config_path = temp_dir.join("config.toml");
  924. // Create a minimal config.toml with backend set but NO [ldk_node] section
  925. let config_content = r#"
  926. [ln]
  927. backend = "ldknode"
  928. min_mint = 1
  929. max_mint = 500000
  930. min_melt = 1
  931. max_melt = 500000
  932. "#;
  933. fs::write(&config_path, config_content).expect("Failed to write config file");
  934. // Set environment variables for LDK Node configuration
  935. env::set_var(crate::env_vars::ENV_LN_BACKEND, "ldknode");
  936. env::set_var(crate::env_vars::LDK_NODE_FEE_PERCENT_ENV_VAR, "0.01");
  937. env::set_var(crate::env_vars::LDK_NODE_RESERVE_FEE_MIN_ENV_VAR, "4");
  938. env::set_var(crate::env_vars::LDK_NODE_BITCOIN_NETWORK_ENV_VAR, "regtest");
  939. env::set_var(
  940. crate::env_vars::LDK_NODE_CHAIN_SOURCE_TYPE_ENV_VAR,
  941. "esplora",
  942. );
  943. env::set_var(
  944. crate::env_vars::LDK_NODE_ESPLORA_URL_ENV_VAR,
  945. "http://localhost:3000",
  946. );
  947. env::set_var(
  948. crate::env_vars::LDK_NODE_STORAGE_DIR_PATH_ENV_VAR,
  949. "/tmp/ldk",
  950. );
  951. // Load settings and apply environment variables (same as production code)
  952. let mut settings = Settings::new(Some(&config_path));
  953. settings.from_env().expect("Failed to apply env vars");
  954. // Verify that settings were populated from env vars
  955. assert!(settings.ldk_node.is_some());
  956. let ldk_config = settings.ldk_node.as_ref().unwrap();
  957. assert_eq!(ldk_config.fee_percent, 0.01);
  958. let reserve_fee_u64: u64 = ldk_config.reserve_fee_min.into();
  959. assert_eq!(reserve_fee_u64, 4);
  960. assert_eq!(ldk_config.bitcoin_network, Some("regtest".to_string()));
  961. assert_eq!(ldk_config.chain_source_type, Some("esplora".to_string()));
  962. assert_eq!(
  963. ldk_config.esplora_url,
  964. Some("http://localhost:3000".to_string())
  965. );
  966. assert_eq!(ldk_config.storage_dir_path, Some("/tmp/ldk".to_string()));
  967. // Cleanup env vars
  968. env::remove_var(crate::env_vars::ENV_LN_BACKEND);
  969. env::remove_var(crate::env_vars::LDK_NODE_FEE_PERCENT_ENV_VAR);
  970. env::remove_var(crate::env_vars::LDK_NODE_RESERVE_FEE_MIN_ENV_VAR);
  971. env::remove_var(crate::env_vars::LDK_NODE_BITCOIN_NETWORK_ENV_VAR);
  972. env::remove_var(crate::env_vars::LDK_NODE_CHAIN_SOURCE_TYPE_ENV_VAR);
  973. env::remove_var(crate::env_vars::LDK_NODE_ESPLORA_URL_ENV_VAR);
  974. env::remove_var(crate::env_vars::LDK_NODE_STORAGE_DIR_PATH_ENV_VAR);
  975. // Cleanup test file
  976. let _ = fs::remove_dir_all(&temp_dir);
  977. }
  978. }