main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //! CDK Mint Server
  2. #![warn(missing_docs)]
  3. #![warn(rustdoc::bare_urls)]
  4. use std::collections::HashMap;
  5. use std::path::PathBuf;
  6. use std::str::FromStr;
  7. use std::sync::Arc;
  8. use anyhow::{anyhow, bail, Result};
  9. use axum::Router;
  10. use bip39::Mnemonic;
  11. use cdk::cdk_database::{self, MintDatabase};
  12. use cdk::cdk_lightning;
  13. use cdk::cdk_lightning::MintLightning;
  14. use cdk::mint::{MeltQuote, Mint, MintBuilder, MintMeltLimits};
  15. use cdk::nuts::{ContactInfo, CurrencyUnit, MeltQuoteState, MintVersion, PaymentMethod};
  16. use cdk::types::LnKey;
  17. use cdk_mintd::cli::CLIArgs;
  18. use cdk_mintd::config::{self, DatabaseEngine, LnBackend};
  19. use cdk_mintd::setup::LnBackendSetup;
  20. use cdk_redb::MintRedbDatabase;
  21. use cdk_sqlite::MintSqliteDatabase;
  22. use clap::Parser;
  23. use tokio::sync::Notify;
  24. use tower_http::cors::CorsLayer;
  25. use tracing_subscriber::EnvFilter;
  26. #[cfg(feature = "swagger")]
  27. use utoipa::OpenApi;
  28. const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
  29. const DEFAULT_QUOTE_TTL_SECS: u64 = 1800;
  30. const DEFAULT_CACHE_TTL_SECS: u64 = 1800;
  31. const DEFAULT_CACHE_TTI_SECS: u64 = 1800;
  32. #[tokio::main]
  33. async fn main() -> anyhow::Result<()> {
  34. let default_filter = "debug";
  35. let sqlx_filter = "sqlx=warn";
  36. let hyper_filter = "hyper=warn";
  37. let env_filter = EnvFilter::new(format!(
  38. "{},{},{}",
  39. default_filter, sqlx_filter, hyper_filter
  40. ));
  41. tracing_subscriber::fmt().with_env_filter(env_filter).init();
  42. let args = CLIArgs::parse();
  43. let work_dir = match args.work_dir {
  44. Some(w) => w,
  45. None => work_dir()?,
  46. };
  47. // get config file name from args
  48. let config_file_arg = match args.config {
  49. Some(c) => c,
  50. None => work_dir.join("config.toml"),
  51. };
  52. let mut mint_builder = MintBuilder::new();
  53. let settings = config::Settings::new(&Some(config_file_arg));
  54. let localstore: Arc<dyn MintDatabase<Err = cdk_database::Error> + Send + Sync> =
  55. match settings.database.engine {
  56. DatabaseEngine::Sqlite => {
  57. let sql_db_path = work_dir.join("cdk-mintd.sqlite");
  58. let sqlite_db = MintSqliteDatabase::new(&sql_db_path).await?;
  59. sqlite_db.migrate().await;
  60. Arc::new(sqlite_db)
  61. }
  62. DatabaseEngine::Redb => {
  63. let redb_path = work_dir.join("cdk-mintd.redb");
  64. Arc::new(MintRedbDatabase::new(&redb_path)?)
  65. }
  66. };
  67. mint_builder = mint_builder.with_localstore(localstore);
  68. let mut contact_info: Option<Vec<ContactInfo>> = None;
  69. if let Some(nostr_contact) = &settings.mint_info.contact_nostr_public_key {
  70. let nostr_contact = ContactInfo::new("nostr".to_string(), nostr_contact.to_string());
  71. contact_info = match contact_info {
  72. Some(mut vec) => {
  73. vec.push(nostr_contact);
  74. Some(vec)
  75. }
  76. None => Some(vec![nostr_contact]),
  77. };
  78. }
  79. if let Some(email_contact) = &settings.mint_info.contact_email {
  80. let email_contact = ContactInfo::new("email".to_string(), email_contact.to_string());
  81. contact_info = match contact_info {
  82. Some(mut vec) => {
  83. vec.push(email_contact);
  84. Some(vec)
  85. }
  86. None => Some(vec![email_contact]),
  87. };
  88. }
  89. let mint_version = MintVersion::new(
  90. "cdk-mintd".to_string(),
  91. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  92. );
  93. let mut ln_backends: HashMap<
  94. LnKey,
  95. Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>,
  96. > = HashMap::new();
  97. let mut ln_routers = vec![];
  98. let mint_melt_limits = MintMeltLimits {
  99. mint_min: settings.ln.min_mint,
  100. mint_max: settings.ln.max_mint,
  101. melt_min: settings.ln.min_melt,
  102. melt_max: settings.ln.max_melt,
  103. };
  104. match settings.ln.ln_backend {
  105. LnBackend::Cln => {
  106. let cln_settings = settings
  107. .cln
  108. .clone()
  109. .expect("Config checked at load that cln is some");
  110. let cln = cln_settings
  111. .setup(&mut ln_routers, &settings, CurrencyUnit::Msat)
  112. .await?;
  113. let cln = Arc::new(cln);
  114. let ln_key = LnKey {
  115. unit: CurrencyUnit::Sat,
  116. method: PaymentMethod::Bolt11,
  117. };
  118. ln_backends.insert(ln_key, cln.clone());
  119. mint_builder = mint_builder.add_ln_backend(
  120. CurrencyUnit::Sat,
  121. PaymentMethod::Bolt11,
  122. mint_melt_limits,
  123. cln.clone(),
  124. );
  125. }
  126. LnBackend::Strike => {
  127. let strike_settings = settings.clone().strike.expect("Checked on config load");
  128. for unit in strike_settings
  129. .clone()
  130. .supported_units
  131. .unwrap_or(vec![CurrencyUnit::Sat])
  132. {
  133. let strike = strike_settings
  134. .setup(&mut ln_routers, &settings, unit.clone())
  135. .await?;
  136. mint_builder = mint_builder.add_ln_backend(
  137. unit,
  138. PaymentMethod::Bolt11,
  139. mint_melt_limits,
  140. Arc::new(strike),
  141. );
  142. }
  143. }
  144. LnBackend::LNbits => {
  145. let lnbits_settings = settings.clone().lnbits.expect("Checked on config load");
  146. let lnbits = lnbits_settings
  147. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  148. .await?;
  149. mint_builder = mint_builder.add_ln_backend(
  150. CurrencyUnit::Sat,
  151. PaymentMethod::Bolt11,
  152. mint_melt_limits,
  153. Arc::new(lnbits),
  154. );
  155. }
  156. LnBackend::Phoenixd => {
  157. let phd_settings = settings.clone().phoenixd.expect("Checked at config load");
  158. let phd = phd_settings
  159. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  160. .await?;
  161. mint_builder = mint_builder.add_ln_backend(
  162. CurrencyUnit::Sat,
  163. PaymentMethod::Bolt11,
  164. mint_melt_limits,
  165. Arc::new(phd),
  166. );
  167. }
  168. LnBackend::Lnd => {
  169. let lnd_settings = settings.clone().lnd.expect("Checked at config load");
  170. let lnd = lnd_settings
  171. .setup(&mut ln_routers, &settings, CurrencyUnit::Msat)
  172. .await?;
  173. mint_builder = mint_builder.add_ln_backend(
  174. CurrencyUnit::Sat,
  175. PaymentMethod::Bolt11,
  176. mint_melt_limits,
  177. Arc::new(lnd),
  178. );
  179. }
  180. LnBackend::FakeWallet => {
  181. let fake_wallet = settings.clone().fake_wallet.expect("Fake wallet defined");
  182. for unit in fake_wallet.clone().supported_units {
  183. let fake = fake_wallet
  184. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  185. .await?;
  186. let fake = Arc::new(fake);
  187. mint_builder = mint_builder.add_ln_backend(
  188. unit.clone(),
  189. PaymentMethod::Bolt11,
  190. mint_melt_limits,
  191. fake.clone(),
  192. );
  193. }
  194. }
  195. };
  196. if let Some(long_description) = &settings.mint_info.description_long {
  197. mint_builder = mint_builder.with_long_description(long_description.to_string());
  198. }
  199. if let Some(contact_info) = contact_info {
  200. for info in contact_info {
  201. mint_builder = mint_builder.add_contact_info(info);
  202. }
  203. }
  204. if let Some(pubkey) = settings.mint_info.pubkey {
  205. mint_builder = mint_builder.with_pubkey(pubkey);
  206. }
  207. if let Some(icon_url) = &settings.mint_info.icon_url {
  208. mint_builder = mint_builder.with_icon_url(icon_url.to_string());
  209. }
  210. if let Some(motd) = settings.mint_info.motd {
  211. mint_builder = mint_builder.with_motd(motd);
  212. }
  213. let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;
  214. mint_builder = mint_builder
  215. .with_name(settings.mint_info.name)
  216. .with_mint_url(settings.info.url)
  217. .with_version(mint_version)
  218. .with_description(settings.mint_info.description)
  219. .with_quote_ttl(10000, 10000)
  220. .with_seed(mnemonic.to_seed_normalized("").to_vec());
  221. let mint = mint_builder.build().await?;
  222. let mint = Arc::new(mint);
  223. // Check the status of any mint quotes that are pending
  224. // In the event that the mint server is down but the ln node is not
  225. // it is possible that a mint quote was paid but the mint has not been updated
  226. // this will check and update the mint state of those quotes
  227. mint.check_pending_mint_quotes().await?;
  228. // Checks the status of all pending melt quotes
  229. // Pending melt quotes where the payment has gone through inputs are burnt
  230. // Pending melt quotes where the payment has **failed** inputs are reset to unspent
  231. check_pending_melt_quotes(Arc::clone(&mint), &ln_backends).await?;
  232. let listen_addr = settings.info.listen_host;
  233. let listen_port = settings.info.listen_port;
  234. let _quote_ttl = settings
  235. .info
  236. .seconds_quote_is_valid_for
  237. .unwrap_or(DEFAULT_QUOTE_TTL_SECS);
  238. let cache_ttl = settings
  239. .info
  240. .seconds_to_cache_requests_for
  241. .unwrap_or(DEFAULT_CACHE_TTL_SECS);
  242. let cache_tti = settings
  243. .info
  244. .seconds_to_extend_cache_by
  245. .unwrap_or(DEFAULT_CACHE_TTI_SECS);
  246. let v1_service = cdk_axum::create_mint_router(Arc::clone(&mint), cache_ttl, cache_tti).await?;
  247. let mut mint_service = Router::new()
  248. .merge(v1_service)
  249. .layer(CorsLayer::permissive());
  250. #[cfg(feature = "swagger")]
  251. {
  252. if settings.info.enable_swagger_ui.unwrap_or(false) {
  253. mint_service = mint_service.merge(
  254. utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
  255. .url("/api-docs/openapi.json", cdk_axum::ApiDocV1::openapi()),
  256. );
  257. }
  258. }
  259. for router in ln_routers {
  260. mint_service = mint_service.merge(router);
  261. }
  262. let shutdown = Arc::new(Notify::new());
  263. tokio::spawn({
  264. let shutdown = Arc::clone(&shutdown);
  265. async move { mint.wait_for_paid_invoices(shutdown).await }
  266. });
  267. let axum_result = axum::Server::bind(
  268. &format!("{}:{}", listen_addr, listen_port)
  269. .as_str()
  270. .parse()?,
  271. )
  272. .serve(mint_service.into_make_service())
  273. .await;
  274. shutdown.notify_waiters();
  275. match axum_result {
  276. Ok(_) => {
  277. tracing::info!("Axum server stopped with okay status");
  278. }
  279. Err(err) => {
  280. tracing::warn!("Axum server stopped with error");
  281. tracing::error!("{}", err);
  282. bail!("Axum exited with error")
  283. }
  284. }
  285. Ok(())
  286. }
  287. async fn check_pending_melt_quotes(
  288. mint: Arc<Mint>,
  289. ln_backends: &HashMap<LnKey, Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>>,
  290. ) -> Result<()> {
  291. let melt_quotes = mint.localstore.get_melt_quotes().await?;
  292. let pending_quotes: Vec<MeltQuote> = melt_quotes
  293. .into_iter()
  294. .filter(|q| q.state == MeltQuoteState::Pending || q.state == MeltQuoteState::Unknown)
  295. .collect();
  296. tracing::info!("There are {} pending melt quotes.", pending_quotes.len());
  297. for pending_quote in pending_quotes {
  298. tracing::debug!("Checking status for melt quote {}.", pending_quote.id);
  299. let melt_request_ln_key = mint.localstore.get_melt_request(&pending_quote.id).await?;
  300. let (melt_request, ln_key) = match melt_request_ln_key {
  301. None => (
  302. None,
  303. LnKey {
  304. unit: pending_quote.unit,
  305. method: PaymentMethod::Bolt11,
  306. },
  307. ),
  308. Some((melt_request, ln_key)) => (Some(melt_request), ln_key),
  309. };
  310. let ln_backend = match ln_backends.get(&ln_key) {
  311. Some(ln_backend) => ln_backend,
  312. None => {
  313. tracing::warn!("No backend for ln key: {:?}", ln_key);
  314. continue;
  315. }
  316. };
  317. let pay_invoice_response = ln_backend
  318. .check_outgoing_payment(&pending_quote.request_lookup_id)
  319. .await?;
  320. match melt_request {
  321. Some(melt_request) => {
  322. match pay_invoice_response.status {
  323. MeltQuoteState::Paid => {
  324. if let Err(err) = mint
  325. .process_melt_request(
  326. &melt_request,
  327. pay_invoice_response.payment_preimage,
  328. pay_invoice_response.total_spent,
  329. )
  330. .await
  331. {
  332. tracing::error!(
  333. "Could not process melt request for pending quote: {}",
  334. melt_request.quote
  335. );
  336. tracing::error!("{}", err);
  337. }
  338. }
  339. MeltQuoteState::Unpaid | MeltQuoteState::Unknown | MeltQuoteState::Failed => {
  340. // Payment has not been made we want to unset
  341. tracing::info!("Lightning payment for quote {} failed.", pending_quote.id);
  342. if let Err(err) = mint.process_unpaid_melt(&melt_request).await {
  343. tracing::error!("Could not reset melt quote state: {}", err);
  344. }
  345. }
  346. MeltQuoteState::Pending => {
  347. tracing::warn!(
  348. "LN payment pending, proofs are stuck as pending for quote: {}",
  349. melt_request.quote
  350. );
  351. // Quote is still pending we do not want to do anything
  352. // continue to check next quote
  353. }
  354. }
  355. }
  356. None => {
  357. tracing::warn!(
  358. "There is no stored melt request for pending melt quote: {}",
  359. pending_quote.id
  360. );
  361. mint.localstore
  362. .update_melt_quote_state(&pending_quote.id, pay_invoice_response.status)
  363. .await?;
  364. }
  365. };
  366. }
  367. Ok(())
  368. }
  369. fn work_dir() -> Result<PathBuf> {
  370. let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
  371. Ok(home_dir.join(".cdk-mintd"))
  372. }