lib.rs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. //! Cdk mintd lib
  2. // std
  3. #[cfg(feature = "auth")]
  4. use std::collections::HashMap;
  5. use std::env::{self};
  6. use std::net::SocketAddr;
  7. use std::path::{Path, PathBuf};
  8. use std::str::FromStr;
  9. use std::sync::Arc;
  10. // external crates
  11. use anyhow::{anyhow, bail, Result};
  12. use axum::Router;
  13. use bip39::Mnemonic;
  14. use cdk::cdk_database::{self, KVStore, MintDatabase, MintKeysDatabase};
  15. use cdk::mint::{Mint, MintBuilder, MintMeltLimits};
  16. use cdk::nuts::nut00::KnownMethod;
  17. #[cfg(any(
  18. feature = "cln",
  19. feature = "lnbits",
  20. feature = "lnd",
  21. feature = "ldk-node",
  22. feature = "fakewallet",
  23. feature = "grpc-processor"
  24. ))]
  25. use cdk::nuts::nut17::SupportedMethods;
  26. use cdk::nuts::nut19::{CachedEndpoint, Method as NUT19Method, Path as NUT19Path};
  27. #[cfg(any(
  28. feature = "cln",
  29. feature = "lnbits",
  30. feature = "lnd",
  31. feature = "ldk-node"
  32. ))]
  33. use cdk::nuts::CurrencyUnit;
  34. #[cfg(feature = "auth")]
  35. use cdk::nuts::{AuthRequired, Method, ProtectedEndpoint, RoutePath};
  36. use cdk::nuts::{ContactInfo, MintVersion, PaymentMethod};
  37. use cdk_axum::cache::HttpCache;
  38. use cdk_common::common::QuoteTTL;
  39. use cdk_common::database::DynMintDatabase;
  40. // internal crate modules
  41. #[cfg(feature = "prometheus")]
  42. use cdk_common::payment::MetricsMintPayment;
  43. use cdk_common::payment::MintPayment;
  44. #[cfg(all(feature = "auth", feature = "postgres"))]
  45. use cdk_postgres::MintPgAuthDatabase;
  46. #[cfg(feature = "postgres")]
  47. use cdk_postgres::MintPgDatabase;
  48. #[cfg(all(feature = "auth", feature = "sqlite"))]
  49. use cdk_sqlite::mint::MintSqliteAuthDatabase;
  50. #[cfg(feature = "sqlite")]
  51. use cdk_sqlite::MintSqliteDatabase;
  52. use cli::CLIArgs;
  53. #[cfg(feature = "auth")]
  54. use config::AuthType;
  55. use config::{DatabaseEngine, LnBackend};
  56. use env_vars::ENV_WORK_DIR;
  57. use setup::LnBackendSetup;
  58. use tower::ServiceBuilder;
  59. use tower_http::compression::CompressionLayer;
  60. use tower_http::decompression::RequestDecompressionLayer;
  61. use tower_http::trace::TraceLayer;
  62. use tracing_appender::{non_blocking, rolling};
  63. use tracing_subscriber::fmt::writer::MakeWriterExt;
  64. use tracing_subscriber::EnvFilter;
  65. #[cfg(feature = "swagger")]
  66. use utoipa::OpenApi;
  67. pub mod cli;
  68. pub mod config;
  69. pub mod env_vars;
  70. pub mod setup;
  71. const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
  72. #[cfg(feature = "cln")]
  73. fn expand_path(path: &str) -> Option<PathBuf> {
  74. if path.starts_with('~') {
  75. if let Some(home_dir) = home::home_dir().as_mut() {
  76. let remainder = &path[2..];
  77. home_dir.push(remainder);
  78. let expanded_path = home_dir;
  79. Some(expanded_path.clone())
  80. } else {
  81. None
  82. }
  83. } else {
  84. Some(PathBuf::from(path))
  85. }
  86. }
  87. /// Performs the initial setup for the application, including configuring tracing,
  88. /// parsing CLI arguments, setting up the working directory, loading settings,
  89. /// and initializing the database connection.
  90. async fn initial_setup(
  91. work_dir: &Path,
  92. settings: &config::Settings,
  93. db_password: Option<String>,
  94. ) -> Result<(
  95. DynMintDatabase,
  96. Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
  97. Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync>,
  98. )> {
  99. let (localstore, keystore, kv) = setup_database(settings, work_dir, db_password).await?;
  100. Ok((localstore, keystore, kv))
  101. }
  102. /// Sets up and initializes a tracing subscriber with custom log filtering.
  103. /// Logs can be configured to output to stdout only, file only, or both.
  104. /// Returns a guard that must be kept alive and properly dropped on shutdown.
  105. pub fn setup_tracing(
  106. work_dir: &Path,
  107. logging_config: &config::LoggingConfig,
  108. ) -> Result<Option<tracing_appender::non_blocking::WorkerGuard>> {
  109. let default_filter = "debug";
  110. let hyper_filter = "hyper=warn,rustls=warn,reqwest=warn";
  111. let h2_filter = "h2=warn";
  112. let tower_filter = "tower=warn";
  113. let tower_http = "tower_http=warn";
  114. let rustls = "rustls=warn";
  115. let tungstenite = "tungstenite=warn";
  116. let tokio_postgres = "tokio_postgres=warn";
  117. let env_filter = EnvFilter::new(format!(
  118. "{default_filter},{hyper_filter},{h2_filter},{tower_filter},{tower_http},{rustls},{tungstenite},{tokio_postgres}"
  119. ));
  120. use config::LoggingOutput;
  121. match logging_config.output {
  122. LoggingOutput::Stderr => {
  123. // Console output only (stderr)
  124. let console_level = logging_config
  125. .console_level
  126. .as_deref()
  127. .unwrap_or("info")
  128. .parse::<tracing::Level>()
  129. .unwrap_or(tracing::Level::INFO);
  130. let stderr = std::io::stderr.with_max_level(console_level);
  131. tracing_subscriber::fmt()
  132. .with_env_filter(env_filter)
  133. .with_writer(stderr)
  134. .init();
  135. tracing::info!("Logging initialized: console only ({}+)", console_level);
  136. Ok(None)
  137. }
  138. LoggingOutput::File => {
  139. // File output only
  140. let file_level = logging_config
  141. .file_level
  142. .as_deref()
  143. .unwrap_or("debug")
  144. .parse::<tracing::Level>()
  145. .unwrap_or(tracing::Level::DEBUG);
  146. // Create logs directory in work_dir if it doesn't exist
  147. let logs_dir = work_dir.join("logs");
  148. std::fs::create_dir_all(&logs_dir)?;
  149. // Set up file appender with daily rotation
  150. let file_appender = rolling::daily(&logs_dir, "cdk-mintd.log");
  151. let (non_blocking_appender, guard) = non_blocking(file_appender);
  152. let file_writer = non_blocking_appender.with_max_level(file_level);
  153. tracing_subscriber::fmt()
  154. .with_env_filter(env_filter)
  155. .with_writer(file_writer)
  156. .init();
  157. tracing::info!(
  158. "Logging initialized: file only at {}/cdk-mintd.log ({}+)",
  159. logs_dir.display(),
  160. file_level
  161. );
  162. Ok(Some(guard))
  163. }
  164. LoggingOutput::Both => {
  165. // Both console and file output (stderr + file)
  166. let console_level = logging_config
  167. .console_level
  168. .as_deref()
  169. .unwrap_or("info")
  170. .parse::<tracing::Level>()
  171. .unwrap_or(tracing::Level::INFO);
  172. let file_level = logging_config
  173. .file_level
  174. .as_deref()
  175. .unwrap_or("debug")
  176. .parse::<tracing::Level>()
  177. .unwrap_or(tracing::Level::DEBUG);
  178. // Create logs directory in work_dir if it doesn't exist
  179. let logs_dir = work_dir.join("logs");
  180. std::fs::create_dir_all(&logs_dir)?;
  181. // Set up file appender with daily rotation
  182. let file_appender = rolling::daily(&logs_dir, "cdk-mintd.log");
  183. let (non_blocking_appender, guard) = non_blocking(file_appender);
  184. // Combine console output (stderr) and file output
  185. let stderr = std::io::stderr.with_max_level(console_level);
  186. let file_writer = non_blocking_appender.with_max_level(file_level);
  187. tracing_subscriber::fmt()
  188. .with_env_filter(env_filter)
  189. .with_writer(stderr.and(file_writer))
  190. .init();
  191. tracing::info!(
  192. "Logging initialized: console ({}+) and file at {}/cdk-mintd.log ({}+)",
  193. console_level,
  194. logs_dir.display(),
  195. file_level
  196. );
  197. Ok(Some(guard))
  198. }
  199. }
  200. }
  201. /// Retrieves the work directory based on command-line arguments, environment variables, or system defaults.
  202. pub async fn get_work_directory(args: &CLIArgs) -> Result<PathBuf> {
  203. let work_dir = if let Some(work_dir) = &args.work_dir {
  204. tracing::info!("Using work dir from cmd arg");
  205. work_dir.clone()
  206. } else if let Ok(env_work_dir) = env::var(ENV_WORK_DIR) {
  207. tracing::info!("Using work dir from env var");
  208. env_work_dir.into()
  209. } else {
  210. work_dir()?
  211. };
  212. tracing::info!("Using work dir: {}", work_dir.display());
  213. Ok(work_dir)
  214. }
  215. /// Loads the application settings based on a configuration file and environment variables.
  216. pub fn load_settings(work_dir: &Path, config_path: Option<PathBuf>) -> Result<config::Settings> {
  217. // get config file name from args
  218. let config_file_arg = match config_path {
  219. Some(c) => c,
  220. None => work_dir.join("config.toml"),
  221. };
  222. let mut settings = if config_file_arg.exists() {
  223. config::Settings::new(Some(config_file_arg))
  224. } else {
  225. tracing::info!("Config file does not exist. Attempting to read env vars");
  226. config::Settings::default()
  227. };
  228. // This check for any settings defined in ENV VARs
  229. // ENV VARS will take **priority** over those in the config
  230. settings.from_env()
  231. }
  232. async fn setup_database(
  233. settings: &config::Settings,
  234. _work_dir: &Path,
  235. _db_password: Option<String>,
  236. ) -> Result<(
  237. DynMintDatabase,
  238. Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
  239. Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync>,
  240. )> {
  241. match settings.database.engine {
  242. #[cfg(feature = "sqlite")]
  243. DatabaseEngine::Sqlite => {
  244. let db = setup_sqlite_database(_work_dir, _db_password).await?;
  245. let localstore: Arc<dyn MintDatabase<cdk_database::Error> + Send + Sync> = db.clone();
  246. let kv: Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync> = db.clone();
  247. let keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync> = db;
  248. Ok((localstore, keystore, kv))
  249. }
  250. #[cfg(feature = "postgres")]
  251. DatabaseEngine::Postgres => {
  252. // Get the PostgreSQL configuration, ensuring it exists
  253. let pg_config = settings.database.postgres.as_ref().ok_or_else(|| {
  254. anyhow!("PostgreSQL configuration is required when using PostgreSQL engine")
  255. })?;
  256. if pg_config.url.is_empty() {
  257. bail!("PostgreSQL URL is required. Set it in config file [database.postgres] section or via CDK_MINTD_POSTGRES_URL/CDK_MINTD_DATABASE_URL environment variable");
  258. }
  259. #[cfg(feature = "postgres")]
  260. let pg_db = Arc::new(MintPgDatabase::new(pg_config.url.as_str()).await?);
  261. #[cfg(feature = "postgres")]
  262. let localstore: Arc<dyn MintDatabase<cdk_database::Error> + Send + Sync> =
  263. pg_db.clone();
  264. #[cfg(feature = "postgres")]
  265. let kv: Arc<dyn KVStore<Err = cdk_database::Error> + Send + Sync> = pg_db.clone();
  266. #[cfg(feature = "postgres")]
  267. let keystore: Arc<
  268. dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync,
  269. > = pg_db;
  270. #[cfg(feature = "postgres")]
  271. return Ok((localstore, keystore, kv));
  272. #[cfg(not(feature = "postgres"))]
  273. bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
  274. }
  275. #[cfg(not(feature = "sqlite"))]
  276. DatabaseEngine::Sqlite => {
  277. bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
  278. }
  279. #[cfg(not(feature = "postgres"))]
  280. DatabaseEngine::Postgres => {
  281. bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
  282. }
  283. }
  284. }
  285. #[cfg(feature = "sqlite")]
  286. async fn setup_sqlite_database(
  287. work_dir: &Path,
  288. _password: Option<String>,
  289. ) -> Result<Arc<MintSqliteDatabase>> {
  290. let sql_db_path = work_dir.join("cdk-mintd.sqlite");
  291. #[cfg(not(feature = "sqlcipher"))]
  292. let db = MintSqliteDatabase::new(&sql_db_path).await?;
  293. #[cfg(feature = "sqlcipher")]
  294. let db = {
  295. // Get password from command line arguments for sqlcipher
  296. let password = _password
  297. .ok_or_else(|| anyhow!("Password required when sqlcipher feature is enabled"))?;
  298. MintSqliteDatabase::new((sql_db_path, password)).await?
  299. };
  300. Ok(Arc::new(db))
  301. }
  302. /**
  303. * Configures a `MintBuilder` instance with provided settings and initializes
  304. * routers for Lightning Network backends.
  305. */
  306. async fn configure_mint_builder(
  307. settings: &config::Settings,
  308. mint_builder: MintBuilder,
  309. runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
  310. work_dir: &Path,
  311. kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
  312. ) -> Result<MintBuilder> {
  313. // Configure basic mint information
  314. let mint_builder = configure_basic_info(settings, mint_builder);
  315. // Configure lightning backend
  316. let mint_builder =
  317. configure_lightning_backend(settings, mint_builder, runtime, work_dir, kv_store).await?;
  318. // Extract configured payment methods from mint_builder
  319. let mint_info = mint_builder.current_mint_info();
  320. let payment_methods: Vec<String> = mint_info
  321. .nuts
  322. .nut04
  323. .methods
  324. .iter()
  325. .map(|m| m.method.to_string())
  326. .collect();
  327. // Configure caching with payment methods
  328. let mint_builder = configure_cache(settings, mint_builder, &payment_methods);
  329. Ok(mint_builder)
  330. }
  331. /// Configures basic mint information (name, contact info, descriptions, etc.)
  332. fn configure_basic_info(settings: &config::Settings, mint_builder: MintBuilder) -> MintBuilder {
  333. // Add contact information
  334. let mut contacts = Vec::new();
  335. if let Some(nostr_key) = &settings.mint_info.contact_nostr_public_key {
  336. if !nostr_key.is_empty() {
  337. contacts.push(ContactInfo::new("nostr".to_string(), nostr_key.to_string()));
  338. }
  339. }
  340. if let Some(email) = &settings.mint_info.contact_email {
  341. if !email.is_empty() {
  342. contacts.push(ContactInfo::new("email".to_string(), email.to_string()));
  343. }
  344. }
  345. // Add version information
  346. let mint_version = MintVersion::new(
  347. "cdk-mintd".to_string(),
  348. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  349. );
  350. // Configure mint builder with basic info
  351. let mut builder = mint_builder.with_version(mint_version);
  352. // Only set name if it's not empty
  353. if !settings.mint_info.name.is_empty() {
  354. builder = builder.with_name(settings.mint_info.name.clone());
  355. }
  356. // Only set description if it's not empty
  357. if !settings.mint_info.description.is_empty() {
  358. builder = builder.with_description(settings.mint_info.description.clone());
  359. }
  360. // Add optional information
  361. if let Some(long_description) = &settings.mint_info.description_long {
  362. if !long_description.is_empty() {
  363. builder = builder.with_long_description(long_description.to_string());
  364. }
  365. }
  366. for contact in contacts {
  367. builder = builder.with_contact_info(contact);
  368. }
  369. if let Some(pubkey) = settings.mint_info.pubkey {
  370. builder = builder.with_pubkey(pubkey);
  371. }
  372. if let Some(icon_url) = &settings.mint_info.icon_url {
  373. if !icon_url.is_empty() {
  374. builder = builder.with_icon_url(icon_url.to_string());
  375. }
  376. }
  377. if let Some(motd) = &settings.mint_info.motd {
  378. if !motd.is_empty() {
  379. builder = builder.with_motd(motd.to_string());
  380. }
  381. }
  382. if let Some(tos_url) = &settings.mint_info.tos_url {
  383. if !tos_url.is_empty() {
  384. builder = builder.with_tos_url(tos_url.to_string());
  385. }
  386. }
  387. builder
  388. }
  389. /// Configures Lightning Network backend based on the specified backend type
  390. async fn configure_lightning_backend(
  391. settings: &config::Settings,
  392. mut mint_builder: MintBuilder,
  393. _runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
  394. work_dir: &Path,
  395. _kv_store: Option<Arc<dyn KVStore<Err = cdk::cdk_database::Error> + Send + Sync>>,
  396. ) -> Result<MintBuilder> {
  397. let mint_melt_limits = MintMeltLimits {
  398. mint_min: settings.ln.min_mint,
  399. mint_max: settings.ln.max_mint,
  400. melt_min: settings.ln.min_melt,
  401. melt_max: settings.ln.max_melt,
  402. };
  403. tracing::debug!("Ln backend: {:?}", settings.ln.ln_backend);
  404. match settings.ln.ln_backend {
  405. #[cfg(feature = "cln")]
  406. LnBackend::Cln => {
  407. let cln_settings = settings
  408. .cln
  409. .clone()
  410. .expect("Config checked at load that cln is some");
  411. let cln = cln_settings
  412. .setup(settings, CurrencyUnit::Msat, None, work_dir, _kv_store)
  413. .await?;
  414. #[cfg(feature = "prometheus")]
  415. let cln = MetricsMintPayment::new(cln);
  416. mint_builder = configure_backend_for_unit(
  417. settings,
  418. mint_builder,
  419. CurrencyUnit::Sat,
  420. mint_melt_limits,
  421. Arc::new(cln),
  422. )
  423. .await?;
  424. }
  425. #[cfg(feature = "lnbits")]
  426. LnBackend::LNbits => {
  427. let lnbits_settings = settings.clone().lnbits.expect("Checked on config load");
  428. let lnbits = lnbits_settings
  429. .setup(settings, CurrencyUnit::Sat, None, work_dir, None)
  430. .await?;
  431. #[cfg(feature = "prometheus")]
  432. let lnbits = MetricsMintPayment::new(lnbits);
  433. mint_builder = configure_backend_for_unit(
  434. settings,
  435. mint_builder,
  436. CurrencyUnit::Sat,
  437. mint_melt_limits,
  438. Arc::new(lnbits),
  439. )
  440. .await?;
  441. }
  442. #[cfg(feature = "lnd")]
  443. LnBackend::Lnd => {
  444. let lnd_settings = settings.clone().lnd.expect("Checked at config load");
  445. let lnd = lnd_settings
  446. .setup(settings, CurrencyUnit::Msat, None, work_dir, _kv_store)
  447. .await?;
  448. #[cfg(feature = "prometheus")]
  449. let lnd = MetricsMintPayment::new(lnd);
  450. mint_builder = configure_backend_for_unit(
  451. settings,
  452. mint_builder,
  453. CurrencyUnit::Sat,
  454. mint_melt_limits,
  455. Arc::new(lnd),
  456. )
  457. .await?;
  458. }
  459. #[cfg(feature = "fakewallet")]
  460. LnBackend::FakeWallet => {
  461. let fake_wallet = settings.clone().fake_wallet.expect("Fake wallet defined");
  462. tracing::info!("Using fake wallet: {:?}", fake_wallet);
  463. for unit in fake_wallet.clone().supported_units {
  464. let fake = fake_wallet
  465. .setup(settings, unit.clone(), None, work_dir, _kv_store.clone())
  466. .await?;
  467. #[cfg(feature = "prometheus")]
  468. let fake = MetricsMintPayment::new(fake);
  469. mint_builder = configure_backend_for_unit(
  470. settings,
  471. mint_builder,
  472. unit.clone(),
  473. mint_melt_limits,
  474. Arc::new(fake),
  475. )
  476. .await?;
  477. }
  478. }
  479. #[cfg(feature = "grpc-processor")]
  480. LnBackend::GrpcProcessor => {
  481. let grpc_processor = settings
  482. .clone()
  483. .grpc_processor
  484. .expect("grpc processor config defined");
  485. tracing::info!(
  486. "Attempting to start with gRPC payment processor at {}:{}.",
  487. grpc_processor.addr,
  488. grpc_processor.port
  489. );
  490. for unit in grpc_processor.clone().supported_units {
  491. tracing::debug!("Adding unit: {:?}", unit);
  492. let processor = grpc_processor
  493. .setup(settings, unit.clone(), None, work_dir, None)
  494. .await?;
  495. #[cfg(feature = "prometheus")]
  496. let processor = MetricsMintPayment::new(processor);
  497. mint_builder = configure_backend_for_unit(
  498. settings,
  499. mint_builder,
  500. unit.clone(),
  501. mint_melt_limits,
  502. Arc::new(processor),
  503. )
  504. .await?;
  505. }
  506. }
  507. #[cfg(feature = "ldk-node")]
  508. LnBackend::LdkNode => {
  509. let ldk_node_settings = settings.clone().ldk_node.expect("Checked at config load");
  510. tracing::info!("Using LDK Node backend: {:?}", ldk_node_settings);
  511. let ldk_node = ldk_node_settings
  512. .setup(settings, CurrencyUnit::Sat, _runtime, work_dir, None)
  513. .await?;
  514. mint_builder = configure_backend_for_unit(
  515. settings,
  516. mint_builder,
  517. CurrencyUnit::Sat,
  518. mint_melt_limits,
  519. Arc::new(ldk_node),
  520. )
  521. .await?;
  522. }
  523. LnBackend::None => {
  524. tracing::error!(
  525. "Payment backend was not set or feature disabled. {:?}",
  526. settings.ln.ln_backend
  527. );
  528. bail!("Lightning backend must be configured");
  529. }
  530. };
  531. Ok(mint_builder)
  532. }
  533. /// Helper function to configure a mint builder with a lightning backend for a specific currency unit
  534. async fn configure_backend_for_unit(
  535. settings: &config::Settings,
  536. mut mint_builder: MintBuilder,
  537. unit: cdk::nuts::CurrencyUnit,
  538. mint_melt_limits: MintMeltLimits,
  539. backend: Arc<dyn MintPayment<Err = cdk_common::payment::Error> + Send + Sync>,
  540. ) -> Result<MintBuilder> {
  541. let payment_settings = backend.get_settings().await?;
  542. let mut methods = Vec::new();
  543. // Add bolt11 if supported by payment processor
  544. if payment_settings.bolt11.is_some() {
  545. methods.push(PaymentMethod::Known(KnownMethod::Bolt11));
  546. }
  547. // Add bolt12 if supported by payment processor
  548. if payment_settings.bolt12.is_some() {
  549. methods.push(PaymentMethod::Known(KnownMethod::Bolt12));
  550. }
  551. // Add custom methods from payment settings
  552. for method_name in payment_settings.custom.keys() {
  553. methods.push(PaymentMethod::from(method_name.as_str()));
  554. }
  555. // Add all supported payment methods to the mint builder
  556. for method in &methods {
  557. mint_builder
  558. .add_payment_processor(
  559. unit.clone(),
  560. method.clone(),
  561. mint_melt_limits,
  562. backend.clone(),
  563. )
  564. .await?;
  565. }
  566. // Configure NUT17 (WebSocket support) for all payment methods
  567. for method in &methods {
  568. let method_str = method.to_string();
  569. let nut17_supported = match method_str.as_str() {
  570. "bolt11" => SupportedMethods::default_bolt11(unit.clone()),
  571. "bolt12" => SupportedMethods::default_bolt12(unit.clone()),
  572. _ => SupportedMethods::default_custom(method.clone(), unit.clone()),
  573. };
  574. mint_builder = mint_builder.with_supported_websockets(nut17_supported);
  575. }
  576. if let Some(input_fee) = settings.info.input_fee_ppk {
  577. mint_builder.set_unit_fee(&unit, input_fee)?;
  578. }
  579. Ok(mint_builder)
  580. }
  581. /// Configures cache settings with support for custom payment methods
  582. fn configure_cache(
  583. settings: &config::Settings,
  584. mint_builder: MintBuilder,
  585. payment_methods: &[String],
  586. ) -> MintBuilder {
  587. let mut cached_endpoints = vec![
  588. // Always include swap endpoint
  589. CachedEndpoint::new(NUT19Method::Post, NUT19Path::Swap),
  590. ];
  591. // Add cache endpoints for each configured payment method
  592. for method in payment_methods {
  593. // All payment methods (including bolt11, bolt12) use custom paths now
  594. cached_endpoints.push(CachedEndpoint::new(
  595. NUT19Method::Post,
  596. NUT19Path::custom_mint(method),
  597. ));
  598. cached_endpoints.push(CachedEndpoint::new(
  599. NUT19Method::Post,
  600. NUT19Path::custom_melt(method),
  601. ));
  602. }
  603. let cache: HttpCache = settings.info.http_cache.clone().into();
  604. mint_builder.with_cache(Some(cache.ttl.as_secs()), cached_endpoints)
  605. }
  606. #[cfg(feature = "auth")]
  607. async fn setup_authentication(
  608. settings: &config::Settings,
  609. _work_dir: &Path,
  610. mut mint_builder: MintBuilder,
  611. _password: Option<String>,
  612. ) -> Result<(
  613. MintBuilder,
  614. Option<cdk_common::database::DynMintAuthDatabase>,
  615. )> {
  616. if let Some(auth_settings) = settings.auth.clone() {
  617. use cdk_common::database::DynMintAuthDatabase;
  618. tracing::info!("Auth settings are defined. {:?}", auth_settings);
  619. let auth_localstore: DynMintAuthDatabase = match settings.database.engine {
  620. #[cfg(feature = "sqlite")]
  621. DatabaseEngine::Sqlite => {
  622. #[cfg(feature = "sqlite")]
  623. {
  624. let sql_db_path = _work_dir.join("cdk-mintd-auth.sqlite");
  625. #[cfg(not(feature = "sqlcipher"))]
  626. let sqlite_db = MintSqliteAuthDatabase::new(&sql_db_path).await?;
  627. #[cfg(feature = "sqlcipher")]
  628. let sqlite_db = {
  629. // Get password from command line arguments for sqlcipher
  630. let password = _password.clone().ok_or_else(|| {
  631. anyhow!("Password required when sqlcipher feature is enabled")
  632. })?;
  633. MintSqliteAuthDatabase::new((sql_db_path, password)).await?
  634. };
  635. Arc::new(sqlite_db)
  636. }
  637. #[cfg(not(feature = "sqlite"))]
  638. {
  639. bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
  640. }
  641. }
  642. #[cfg(feature = "postgres")]
  643. DatabaseEngine::Postgres => {
  644. #[cfg(feature = "postgres")]
  645. {
  646. // Require dedicated auth database configuration - no fallback to main database
  647. let auth_db_config = settings.auth_database.as_ref().ok_or_else(|| {
  648. anyhow!("Auth database configuration is required when using PostgreSQL with authentication. Set [auth_database] section in config file or CDK_MINTD_AUTH_POSTGRES_URL environment variable")
  649. })?;
  650. let auth_pg_config = auth_db_config.postgres.as_ref().ok_or_else(|| {
  651. anyhow!("PostgreSQL auth database configuration is required when using PostgreSQL with authentication. Set [auth_database.postgres] section in config file or CDK_MINTD_AUTH_POSTGRES_URL environment variable")
  652. })?;
  653. if auth_pg_config.url.is_empty() {
  654. bail!("Auth database PostgreSQL URL is required and cannot be empty. Set it in config file [auth_database.postgres] section or via CDK_MINTD_AUTH_POSTGRES_URL environment variable");
  655. }
  656. Arc::new(MintPgAuthDatabase::new(auth_pg_config.url.as_str()).await?)
  657. }
  658. #[cfg(not(feature = "postgres"))]
  659. {
  660. bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
  661. }
  662. }
  663. #[cfg(not(feature = "sqlite"))]
  664. DatabaseEngine::Sqlite => {
  665. bail!("SQLite support not compiled in. Enable the 'sqlite' feature to use SQLite database.")
  666. }
  667. #[cfg(not(feature = "postgres"))]
  668. DatabaseEngine::Postgres => {
  669. bail!("PostgreSQL support not compiled in. Enable the 'postgres' feature to use PostgreSQL database.")
  670. }
  671. };
  672. let mut protected_endpoints = HashMap::new();
  673. let mut blind_auth_endpoints = vec![];
  674. let mut clear_auth_endpoints = vec![];
  675. let mut unprotected_endpoints = vec![];
  676. let mint_blind_auth_endpoint =
  677. ProtectedEndpoint::new(Method::Post, RoutePath::MintBlindAuth);
  678. protected_endpoints.insert(mint_blind_auth_endpoint.clone(), AuthRequired::Clear);
  679. clear_auth_endpoints.push(mint_blind_auth_endpoint);
  680. // Helper function to add endpoint based on auth type
  681. let mut add_endpoint = |endpoint: ProtectedEndpoint, auth_type: &AuthType| {
  682. match auth_type {
  683. AuthType::Blind => {
  684. protected_endpoints.insert(endpoint.clone(), AuthRequired::Blind);
  685. blind_auth_endpoints.push(endpoint);
  686. }
  687. AuthType::Clear => {
  688. protected_endpoints.insert(endpoint.clone(), AuthRequired::Clear);
  689. clear_auth_endpoints.push(endpoint);
  690. }
  691. AuthType::None => {
  692. unprotected_endpoints.push(endpoint);
  693. }
  694. };
  695. };
  696. // Payment method endpoints (bolt11, bolt12, custom) will be added dynamically
  697. // after the mint is built and we can query the payment processors for their
  698. // supported methods. See the start_services_with_shutdown function where we
  699. // add auth endpoints for all configured payment methods.
  700. // Swap endpoint
  701. {
  702. let swap_protected_endpoint = ProtectedEndpoint::new(Method::Post, RoutePath::Swap);
  703. add_endpoint(swap_protected_endpoint, &auth_settings.swap);
  704. }
  705. // Restore endpoint
  706. {
  707. let restore_protected_endpoint =
  708. ProtectedEndpoint::new(Method::Post, RoutePath::Restore);
  709. add_endpoint(restore_protected_endpoint, &auth_settings.restore);
  710. }
  711. // Check proof state endpoint
  712. {
  713. let state_protected_endpoint =
  714. ProtectedEndpoint::new(Method::Post, RoutePath::Checkstate);
  715. add_endpoint(state_protected_endpoint, &auth_settings.check_proof_state);
  716. }
  717. // Ws endpoint
  718. {
  719. let ws_protected_endpoint = ProtectedEndpoint::new(Method::Get, RoutePath::Ws);
  720. add_endpoint(ws_protected_endpoint, &auth_settings.websocket_auth);
  721. }
  722. // Custom protected_endpoints will be added dynamically after the mint is built
  723. // and we can query the payment processors for their supported methods.
  724. // For now, we don't add any custom endpoints here - they'll be added in the
  725. // start_services_with_shutdown function after we have access to the mint instance.
  726. mint_builder = mint_builder.with_auth(
  727. auth_localstore.clone(),
  728. auth_settings.openid_discovery,
  729. auth_settings.openid_client_id,
  730. clear_auth_endpoints,
  731. );
  732. mint_builder =
  733. mint_builder.with_blind_auth(auth_settings.mint_max_bat, blind_auth_endpoints);
  734. let mut tx = auth_localstore.begin_transaction().await?;
  735. tx.remove_protected_endpoints(unprotected_endpoints).await?;
  736. tx.add_protected_endpoints(protected_endpoints).await?;
  737. tx.commit().await?;
  738. Ok((mint_builder, Some(auth_localstore)))
  739. } else {
  740. Ok((mint_builder, None))
  741. }
  742. }
  743. /// Build mints with the configured the signing method (remote signatory or local seed)
  744. async fn build_mint(
  745. settings: &config::Settings,
  746. keystore: Arc<dyn MintKeysDatabase<Err = cdk_database::Error> + Send + Sync>,
  747. mint_builder: MintBuilder,
  748. ) -> Result<Mint> {
  749. if let Some(signatory_url) = settings.info.signatory_url.clone() {
  750. tracing::info!(
  751. "Connecting to remote signatory to {} with certs {:?}",
  752. signatory_url,
  753. settings.info.signatory_certs.clone()
  754. );
  755. Ok(mint_builder
  756. .build_with_signatory(Arc::new(
  757. cdk_signatory::SignatoryRpcClient::new(
  758. signatory_url,
  759. settings.info.signatory_certs.clone(),
  760. )
  761. .await?,
  762. ))
  763. .await?)
  764. } else if let Some(seed) = settings.info.seed.clone() {
  765. let seed_bytes: Vec<u8> = seed.into();
  766. Ok(mint_builder.build_with_seed(keystore, &seed_bytes).await?)
  767. } else if let Some(mnemonic) = settings
  768. .info
  769. .mnemonic
  770. .clone()
  771. .map(|s| Mnemonic::from_str(&s))
  772. .transpose()?
  773. {
  774. Ok(mint_builder
  775. .build_with_seed(keystore, &mnemonic.to_seed_normalized(""))
  776. .await?)
  777. } else {
  778. bail!("No seed nor remote signatory set");
  779. }
  780. }
  781. async fn start_services_with_shutdown(
  782. mint: Arc<cdk::mint::Mint>,
  783. settings: &config::Settings,
  784. _work_dir: &Path,
  785. mint_builder_info: cdk::nuts::MintInfo,
  786. shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
  787. routers: Vec<Router>,
  788. #[cfg(feature = "auth")] auth_localstore: Option<cdk_common::database::DynMintAuthDatabase>,
  789. ) -> Result<()> {
  790. let listen_addr = settings.info.listen_host.clone();
  791. let listen_port = settings.info.listen_port;
  792. let cache: HttpCache = settings.info.http_cache.clone().into();
  793. #[cfg(feature = "management-rpc")]
  794. let mut rpc_enabled = false;
  795. #[cfg(not(feature = "management-rpc"))]
  796. let rpc_enabled = false;
  797. #[cfg(feature = "management-rpc")]
  798. let mut rpc_server: Option<cdk_mint_rpc::MintRPCServer> = None;
  799. #[cfg(feature = "management-rpc")]
  800. {
  801. if let Some(rpc_settings) = settings.mint_management_rpc.clone() {
  802. if rpc_settings.enabled {
  803. let addr = rpc_settings.address.unwrap_or("127.0.0.1".to_string());
  804. let port = rpc_settings.port.unwrap_or(8086);
  805. let mut mint_rpc = cdk_mint_rpc::MintRPCServer::new(&addr, port, mint.clone())?;
  806. let tls_dir = rpc_settings.tls_dir_path.unwrap_or(_work_dir.join("tls"));
  807. let tls_dir = if tls_dir.exists() {
  808. Some(tls_dir)
  809. } else {
  810. tracing::warn!(
  811. "TLS directory does not exist: {}. Starting RPC server in INSECURE mode without TLS encryption",
  812. tls_dir.display()
  813. );
  814. None
  815. };
  816. mint_rpc.start(tls_dir).await?;
  817. rpc_server = Some(mint_rpc);
  818. rpc_enabled = true;
  819. }
  820. }
  821. }
  822. // Determine the desired QuoteTTL from config/env or fall back to defaults
  823. let desired_quote_ttl: QuoteTTL = settings.info.quote_ttl.unwrap_or_default();
  824. if rpc_enabled {
  825. if mint.mint_info().await.is_err() {
  826. tracing::info!("Mint info not set on mint, setting.");
  827. // First boot with RPC enabled: seed from config
  828. mint.set_mint_info(mint_builder_info).await?;
  829. mint.set_quote_ttl(desired_quote_ttl).await?;
  830. } else {
  831. // If QuoteTTL has never been persisted, seed it now from config
  832. if !mint.quote_ttl_is_persisted().await? {
  833. mint.set_quote_ttl(desired_quote_ttl).await?;
  834. }
  835. // Add/refresh version information without altering stored mint_info fields
  836. let mint_version = MintVersion::new(
  837. "cdk-mintd".to_string(),
  838. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  839. );
  840. let mut stored_mint_info = mint.mint_info().await?;
  841. stored_mint_info.version = Some(mint_version);
  842. mint.set_mint_info(stored_mint_info).await?;
  843. tracing::info!("Mint info already set, not using config file settings.");
  844. }
  845. } else {
  846. // RPC disabled: config is source of truth on every boot
  847. tracing::info!("RPC not enabled, using mint info and quote TTL from config.");
  848. let mut mint_builder_info = mint_builder_info;
  849. if let Ok(mint_info) = mint.mint_info().await {
  850. if mint_builder_info.pubkey.is_none() {
  851. mint_builder_info.pubkey = mint_info.pubkey;
  852. }
  853. }
  854. mint.set_mint_info(mint_builder_info).await?;
  855. mint.set_quote_ttl(desired_quote_ttl).await?;
  856. }
  857. let mint_info = mint.mint_info().await?;
  858. let nut04_methods = mint_info.nuts.nut04.supported_methods();
  859. let nut05_methods = mint_info.nuts.nut05.supported_methods();
  860. // Get custom payment methods from payment processors
  861. let mut custom_methods = mint.get_custom_payment_methods().await?;
  862. // Add bolt11 if it's supported by any payment processor
  863. let bolt11_method = PaymentMethod::Known(KnownMethod::Bolt11);
  864. let bolt11_supported =
  865. nut04_methods.contains(&&bolt11_method) || nut05_methods.contains(&&bolt11_method);
  866. // Add bolt12 if it's supported by any payment processor
  867. let bolt12_method = PaymentMethod::Known(KnownMethod::Bolt12);
  868. let bolt12_supported =
  869. nut04_methods.contains(&&bolt12_method) || nut05_methods.contains(&&bolt12_method);
  870. if bolt11_supported
  871. && !custom_methods.contains(&PaymentMethod::Known(KnownMethod::Bolt11).to_string())
  872. {
  873. custom_methods.push(PaymentMethod::Known(KnownMethod::Bolt11).to_string());
  874. }
  875. if bolt12_supported
  876. && !custom_methods.contains(&PaymentMethod::Known(KnownMethod::Bolt12).to_string())
  877. {
  878. custom_methods.push(PaymentMethod::Known(KnownMethod::Bolt12).to_string());
  879. }
  880. tracing::info!("Payment methods: {:?}", custom_methods);
  881. // Configure auth for custom payment methods if auth is enabled
  882. #[cfg(feature = "auth")]
  883. if let (Some(ref auth_settings), Some(auth_db)) = (&settings.auth, &auth_localstore) {
  884. if auth_settings.auth_enabled {
  885. use std::collections::HashMap;
  886. use cdk::nuts::nut21::{Method, ProtectedEndpoint, RoutePath};
  887. use cdk::nuts::AuthRequired;
  888. use crate::config::AuthType;
  889. // First, remove all existing payment-method-related endpoints from the database
  890. // to ensure old payment methods don't persist when configuration changes
  891. let existing_endpoints = auth_db.get_auth_for_endpoints().await?;
  892. let payment_method_endpoints_to_remove: Vec<ProtectedEndpoint> = existing_endpoints
  893. .keys()
  894. .filter(|endpoint| {
  895. matches!(
  896. endpoint.path,
  897. RoutePath::MintQuote(_)
  898. | RoutePath::Mint(_)
  899. | RoutePath::MeltQuote(_)
  900. | RoutePath::Melt(_)
  901. )
  902. })
  903. .cloned()
  904. .collect();
  905. if !payment_method_endpoints_to_remove.is_empty() {
  906. tracing::debug!(
  907. "Removing {} old payment method endpoints from database",
  908. payment_method_endpoints_to_remove.len()
  909. );
  910. let mut tx = auth_db.begin_transaction().await?;
  911. tx.remove_protected_endpoints(payment_method_endpoints_to_remove)
  912. .await?;
  913. tx.commit().await?;
  914. }
  915. // Now add endpoints for current payment methods
  916. if !custom_methods.is_empty() {
  917. let mut protected_endpoints = HashMap::new();
  918. for method_name in &custom_methods {
  919. tracing::debug!("Adding auth endpoints for payment method: {}", method_name);
  920. // Determine auth type based on settings
  921. let mint_quote_auth = match auth_settings.get_mint_quote {
  922. AuthType::Clear => Some(AuthRequired::Clear),
  923. AuthType::Blind => Some(AuthRequired::Blind),
  924. AuthType::None => None,
  925. };
  926. let check_mint_quote_auth = match auth_settings.check_mint_quote {
  927. AuthType::Clear => Some(AuthRequired::Clear),
  928. AuthType::Blind => Some(AuthRequired::Blind),
  929. AuthType::None => None,
  930. };
  931. let mint_auth = match auth_settings.mint {
  932. AuthType::Clear => Some(AuthRequired::Clear),
  933. AuthType::Blind => Some(AuthRequired::Blind),
  934. AuthType::None => None,
  935. };
  936. let melt_quote_auth = match auth_settings.get_melt_quote {
  937. AuthType::Clear => Some(AuthRequired::Clear),
  938. AuthType::Blind => Some(AuthRequired::Blind),
  939. AuthType::None => None,
  940. };
  941. let check_melt_quote_auth = match auth_settings.check_melt_quote {
  942. AuthType::Clear => Some(AuthRequired::Clear),
  943. AuthType::Blind => Some(AuthRequired::Blind),
  944. AuthType::None => None,
  945. };
  946. let melt_auth = match auth_settings.melt {
  947. AuthType::Clear => Some(AuthRequired::Clear),
  948. AuthType::Blind => Some(AuthRequired::Blind),
  949. AuthType::None => None,
  950. };
  951. // Create endpoints for each payment method operation
  952. if let Some(auth) = mint_quote_auth {
  953. protected_endpoints.insert(
  954. ProtectedEndpoint::new(
  955. Method::Post,
  956. RoutePath::MintQuote(method_name.clone()),
  957. ),
  958. auth,
  959. );
  960. }
  961. if let Some(auth) = check_mint_quote_auth {
  962. protected_endpoints.insert(
  963. ProtectedEndpoint::new(
  964. Method::Get,
  965. RoutePath::MintQuote(method_name.clone()),
  966. ),
  967. auth,
  968. );
  969. }
  970. if let Some(auth) = mint_auth {
  971. protected_endpoints.insert(
  972. ProtectedEndpoint::new(
  973. Method::Post,
  974. RoutePath::Mint(method_name.clone()),
  975. ),
  976. auth,
  977. );
  978. }
  979. if let Some(auth) = melt_quote_auth {
  980. protected_endpoints.insert(
  981. ProtectedEndpoint::new(
  982. Method::Post,
  983. RoutePath::MeltQuote(method_name.clone()),
  984. ),
  985. auth,
  986. );
  987. }
  988. if let Some(auth) = check_melt_quote_auth {
  989. protected_endpoints.insert(
  990. ProtectedEndpoint::new(
  991. Method::Get,
  992. RoutePath::MeltQuote(method_name.clone()),
  993. ),
  994. auth,
  995. );
  996. }
  997. if let Some(auth) = melt_auth {
  998. protected_endpoints.insert(
  999. ProtectedEndpoint::new(
  1000. Method::Post,
  1001. RoutePath::Melt(method_name.clone()),
  1002. ),
  1003. auth,
  1004. );
  1005. }
  1006. }
  1007. // Add all custom endpoints in one transaction
  1008. if !protected_endpoints.is_empty() {
  1009. let mut tx = auth_db.begin_transaction().await?;
  1010. tx.add_protected_endpoints(protected_endpoints).await?;
  1011. tx.commit().await?;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. let v1_service =
  1017. cdk_axum::create_mint_router_with_custom_cache(Arc::clone(&mint), cache, custom_methods)
  1018. .await?;
  1019. let mut mint_service = Router::new()
  1020. .merge(v1_service)
  1021. .layer(
  1022. ServiceBuilder::new()
  1023. .layer(RequestDecompressionLayer::new())
  1024. .layer(CompressionLayer::new()),
  1025. )
  1026. .layer(TraceLayer::new_for_http());
  1027. for router in routers {
  1028. mint_service = mint_service.merge(router);
  1029. }
  1030. #[cfg(feature = "swagger")]
  1031. {
  1032. if settings.info.enable_swagger_ui.unwrap_or(false) {
  1033. mint_service = mint_service.merge(
  1034. utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
  1035. .url("/api-docs/openapi.json", cdk_axum::ApiDoc::openapi()),
  1036. );
  1037. }
  1038. }
  1039. // Create a broadcast channel to share shutdown signal between services
  1040. let (shutdown_tx, _) = tokio::sync::broadcast::channel::<()>(1);
  1041. // Start Prometheus server if enabled
  1042. #[cfg(feature = "prometheus")]
  1043. let prometheus_handle = {
  1044. if let Some(prometheus_settings) = &settings.prometheus {
  1045. if prometheus_settings.enabled {
  1046. let addr = prometheus_settings
  1047. .address
  1048. .clone()
  1049. .unwrap_or("127.0.0.1".to_string());
  1050. let port = prometheus_settings.port.unwrap_or(9000);
  1051. let address = format!("{}:{}", addr, port)
  1052. .parse()
  1053. .expect("Invalid prometheus address");
  1054. let server = cdk_prometheus::PrometheusBuilder::new()
  1055. .bind_address(address)
  1056. .build_with_cdk_metrics()?;
  1057. let mut shutdown_rx = shutdown_tx.subscribe();
  1058. let prometheus_shutdown = async move {
  1059. let _ = shutdown_rx.recv().await;
  1060. };
  1061. Some(tokio::spawn(async move {
  1062. if let Err(e) = server.start(prometheus_shutdown).await {
  1063. tracing::error!("Failed to start prometheus server: {}", e);
  1064. }
  1065. }))
  1066. } else {
  1067. None
  1068. }
  1069. } else {
  1070. None
  1071. }
  1072. };
  1073. mint.start().await?;
  1074. let socket_addr = SocketAddr::from_str(&format!("{listen_addr}:{listen_port}"))?;
  1075. let listener = tokio::net::TcpListener::bind(socket_addr).await?;
  1076. tracing::info!("listening on {}", listener.local_addr()?);
  1077. // Create a task to wait for the shutdown signal and broadcast it
  1078. let shutdown_broadcast_task = {
  1079. let shutdown_tx = shutdown_tx.clone();
  1080. tokio::spawn(async move {
  1081. shutdown_signal.await;
  1082. tracing::info!("Shutdown signal received, broadcasting to all services");
  1083. let _ = shutdown_tx.send(());
  1084. })
  1085. };
  1086. // Create shutdown future for axum server
  1087. let mut axum_shutdown_rx = shutdown_tx.subscribe();
  1088. let axum_shutdown = async move {
  1089. let _ = axum_shutdown_rx.recv().await;
  1090. };
  1091. // Wait for axum server to complete with custom shutdown signal
  1092. let axum_result = axum::serve(listener, mint_service).with_graceful_shutdown(axum_shutdown);
  1093. match axum_result.await {
  1094. Ok(_) => {
  1095. tracing::info!("Axum server stopped with okay status");
  1096. }
  1097. Err(err) => {
  1098. tracing::warn!("Axum server stopped with error");
  1099. tracing::error!("{}", err);
  1100. bail!("Axum exited with error")
  1101. }
  1102. }
  1103. // Wait for the shutdown broadcast task to complete
  1104. let _ = shutdown_broadcast_task.await;
  1105. // Wait for prometheus server to shutdown if it was started
  1106. #[cfg(feature = "prometheus")]
  1107. if let Some(handle) = prometheus_handle {
  1108. if let Err(e) = handle.await {
  1109. tracing::warn!("Prometheus server task failed: {}", e);
  1110. }
  1111. }
  1112. mint.stop().await?;
  1113. #[cfg(feature = "management-rpc")]
  1114. {
  1115. if let Some(rpc_server) = rpc_server {
  1116. rpc_server.stop().await?;
  1117. }
  1118. }
  1119. Ok(())
  1120. }
  1121. async fn shutdown_signal() {
  1122. tokio::signal::ctrl_c()
  1123. .await
  1124. .expect("failed to install CTRL+C handler");
  1125. tracing::info!("Shutdown signal received");
  1126. }
  1127. fn work_dir() -> Result<PathBuf> {
  1128. let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
  1129. let dir = home_dir.join(".cdk-mintd");
  1130. std::fs::create_dir_all(&dir)?;
  1131. Ok(dir)
  1132. }
  1133. /// The main entry point for the application when used as a library
  1134. pub async fn run_mintd(
  1135. work_dir: &Path,
  1136. settings: &config::Settings,
  1137. db_password: Option<String>,
  1138. enable_logging: bool,
  1139. runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
  1140. routers: Vec<Router>,
  1141. ) -> Result<()> {
  1142. let _guard = if enable_logging {
  1143. setup_tracing(work_dir, &settings.info.logging)?
  1144. } else {
  1145. None
  1146. };
  1147. let result = run_mintd_with_shutdown(
  1148. work_dir,
  1149. settings,
  1150. shutdown_signal(),
  1151. db_password,
  1152. runtime,
  1153. routers,
  1154. )
  1155. .await;
  1156. // Explicitly drop the guard to ensure proper cleanup
  1157. if let Some(guard) = _guard {
  1158. tracing::info!("Shutting down logging worker thread");
  1159. drop(guard);
  1160. // Give the worker thread a moment to flush any remaining logs
  1161. tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
  1162. }
  1163. tracing::info!("Mintd shutdown");
  1164. result
  1165. }
  1166. /// Run mintd with a custom shutdown signal
  1167. pub async fn run_mintd_with_shutdown(
  1168. work_dir: &Path,
  1169. settings: &config::Settings,
  1170. shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
  1171. db_password: Option<String>,
  1172. runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
  1173. routers: Vec<Router>,
  1174. ) -> Result<()> {
  1175. let (localstore, keystore, kv) = initial_setup(work_dir, settings, db_password.clone()).await?;
  1176. let mint_builder = MintBuilder::new(localstore);
  1177. // If RPC is enabled and DB contains mint_info already, initialize the builder from DB.
  1178. // This ensures subsequent builder modifications (like version injection) can respect stored values.
  1179. let maybe_mint_builder = {
  1180. #[cfg(feature = "management-rpc")]
  1181. {
  1182. if let Some(rpc_settings) = settings.mint_management_rpc.clone() {
  1183. if rpc_settings.enabled {
  1184. // Best-effort: pull DB state into builder if present
  1185. let mut tmp = mint_builder;
  1186. if let Err(e) = tmp.init_from_db_if_present().await {
  1187. tracing::warn!("Failed to init builder from DB: {}", e);
  1188. }
  1189. tmp
  1190. } else {
  1191. mint_builder
  1192. }
  1193. } else {
  1194. mint_builder
  1195. }
  1196. }
  1197. #[cfg(not(feature = "management-rpc"))]
  1198. {
  1199. mint_builder
  1200. }
  1201. };
  1202. let mint_builder =
  1203. configure_mint_builder(settings, maybe_mint_builder, runtime, work_dir, Some(kv)).await?;
  1204. #[cfg(feature = "auth")]
  1205. let (mint_builder, auth_localstore) =
  1206. setup_authentication(settings, work_dir, mint_builder, db_password).await?;
  1207. let config_mint_info = mint_builder.current_mint_info();
  1208. let mint = build_mint(settings, keystore, mint_builder).await?;
  1209. tracing::debug!("Mint built from builder.");
  1210. let mint = Arc::new(mint);
  1211. start_services_with_shutdown(
  1212. mint.clone(),
  1213. settings,
  1214. work_dir,
  1215. config_mint_info,
  1216. shutdown_signal,
  1217. routers,
  1218. #[cfg(feature = "auth")]
  1219. auth_localstore,
  1220. )
  1221. .await
  1222. }
  1223. #[cfg(test)]
  1224. mod tests {
  1225. use super::*;
  1226. #[test]
  1227. fn test_postgres_auth_url_validation() {
  1228. // Test that the auth database config requires explicit configuration
  1229. // Test empty URL
  1230. let auth_config = config::PostgresAuthConfig {
  1231. url: "".to_string(),
  1232. ..Default::default()
  1233. };
  1234. assert!(auth_config.url.is_empty());
  1235. // Test non-empty URL
  1236. let auth_config = config::PostgresAuthConfig {
  1237. url: "postgresql://user:password@localhost:5432/auth_db".to_string(),
  1238. ..Default::default()
  1239. };
  1240. assert!(!auth_config.url.is_empty());
  1241. }
  1242. }