main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. //! CDK Mint Server
  2. #![warn(missing_docs)]
  3. #![warn(rustdoc::bare_urls)]
  4. use std::collections::HashMap;
  5. use std::env;
  6. use std::path::PathBuf;
  7. use std::str::FromStr;
  8. use std::sync::Arc;
  9. use anyhow::{anyhow, bail, Result};
  10. use axum::http::Request;
  11. use axum::middleware::Next;
  12. use axum::response::Response;
  13. use axum::{middleware, Router};
  14. use bip39::Mnemonic;
  15. use cdk::cdk_database::{self, MintDatabase};
  16. use cdk::cdk_lightning;
  17. use cdk::cdk_lightning::MintLightning;
  18. use cdk::mint::{MintBuilder, MintMeltLimits};
  19. use cdk::nuts::nut17::SupportedMethods;
  20. use cdk::nuts::nut19::{CachedEndpoint, Method as NUT19Method, Path as NUT19Path};
  21. use cdk::nuts::{ContactInfo, CurrencyUnit, MintVersion, PaymentMethod};
  22. use cdk::types::LnKey;
  23. use cdk_axum::cache::HttpCache;
  24. use cdk_mintd::cli::CLIArgs;
  25. use cdk_mintd::config::{self, DatabaseEngine, LnBackend};
  26. use cdk_mintd::env_vars::ENV_WORK_DIR;
  27. use cdk_mintd::setup::LnBackendSetup;
  28. use cdk_redb::MintRedbDatabase;
  29. use cdk_sqlite::MintSqliteDatabase;
  30. use clap::Parser;
  31. use tokio::sync::Notify;
  32. use tower_http::compression::CompressionLayer;
  33. use tower_http::cors::CorsLayer;
  34. use tracing_subscriber::EnvFilter;
  35. #[cfg(feature = "swagger")]
  36. use utoipa::OpenApi;
  37. const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
  38. #[tokio::main]
  39. async fn main() -> anyhow::Result<()> {
  40. let default_filter = "debug";
  41. let sqlx_filter = "sqlx=warn";
  42. let hyper_filter = "hyper=warn";
  43. let env_filter = EnvFilter::new(format!(
  44. "{},{},{}",
  45. default_filter, sqlx_filter, hyper_filter
  46. ));
  47. tracing_subscriber::fmt().with_env_filter(env_filter).init();
  48. let args = CLIArgs::parse();
  49. let work_dir = if let Some(work_dir) = args.work_dir {
  50. tracing::info!("Using work dir from cmd arg");
  51. work_dir
  52. } else if let Ok(env_work_dir) = env::var(ENV_WORK_DIR) {
  53. tracing::info!("Using work dir from env var");
  54. env_work_dir.into()
  55. } else {
  56. work_dir()?
  57. };
  58. tracing::info!("Using work dir: {}", work_dir.display());
  59. // get config file name from args
  60. let config_file_arg = match args.config {
  61. Some(c) => c,
  62. None => work_dir.join("config.toml"),
  63. };
  64. let mut mint_builder = MintBuilder::new();
  65. let mut settings = if config_file_arg.exists() {
  66. config::Settings::new(Some(config_file_arg))
  67. } else {
  68. tracing::info!("Config file does not exist. Attempting to read env vars");
  69. config::Settings::default()
  70. };
  71. // This check for any settings defined in ENV VARs
  72. // ENV VARS will take **priority** over those in the config
  73. let settings = settings.from_env()?;
  74. let localstore: Arc<dyn MintDatabase<Err = cdk_database::Error> + Send + Sync> =
  75. match settings.database.engine {
  76. DatabaseEngine::Sqlite => {
  77. let sql_db_path = work_dir.join("cdk-mintd.sqlite");
  78. let sqlite_db = MintSqliteDatabase::new(&sql_db_path).await?;
  79. sqlite_db.migrate().await;
  80. Arc::new(sqlite_db)
  81. }
  82. DatabaseEngine::Redb => {
  83. let redb_path = work_dir.join("cdk-mintd.redb");
  84. Arc::new(MintRedbDatabase::new(&redb_path)?)
  85. }
  86. };
  87. mint_builder = mint_builder.with_localstore(localstore);
  88. let mut contact_info: Option<Vec<ContactInfo>> = None;
  89. if let Some(nostr_contact) = &settings.mint_info.contact_nostr_public_key {
  90. let nostr_contact = ContactInfo::new("nostr".to_string(), nostr_contact.to_string());
  91. contact_info = match contact_info {
  92. Some(mut vec) => {
  93. vec.push(nostr_contact);
  94. Some(vec)
  95. }
  96. None => Some(vec![nostr_contact]),
  97. };
  98. }
  99. if let Some(email_contact) = &settings.mint_info.contact_email {
  100. let email_contact = ContactInfo::new("email".to_string(), email_contact.to_string());
  101. contact_info = match contact_info {
  102. Some(mut vec) => {
  103. vec.push(email_contact);
  104. Some(vec)
  105. }
  106. None => Some(vec![email_contact]),
  107. };
  108. }
  109. let mint_version = MintVersion::new(
  110. "cdk-mintd".to_string(),
  111. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  112. );
  113. let mut ln_backends: HashMap<
  114. LnKey,
  115. Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>,
  116. > = HashMap::new();
  117. let mut ln_routers = vec![];
  118. let mint_melt_limits = MintMeltLimits {
  119. mint_min: settings.ln.min_mint,
  120. mint_max: settings.ln.max_mint,
  121. melt_min: settings.ln.min_melt,
  122. melt_max: settings.ln.max_melt,
  123. };
  124. match settings.ln.ln_backend {
  125. LnBackend::Cln => {
  126. let cln_settings = settings
  127. .cln
  128. .clone()
  129. .expect("Config checked at load that cln is some");
  130. let cln = cln_settings
  131. .setup(&mut ln_routers, &settings, CurrencyUnit::Msat)
  132. .await?;
  133. let cln = Arc::new(cln);
  134. let ln_key = LnKey {
  135. unit: CurrencyUnit::Sat,
  136. method: PaymentMethod::Bolt11,
  137. };
  138. ln_backends.insert(ln_key, cln.clone());
  139. mint_builder = mint_builder.add_ln_backend(
  140. CurrencyUnit::Sat,
  141. PaymentMethod::Bolt11,
  142. mint_melt_limits,
  143. cln.clone(),
  144. );
  145. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, CurrencyUnit::Sat);
  146. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  147. }
  148. LnBackend::Strike => {
  149. let strike_settings = settings.clone().strike.expect("Checked on config load");
  150. for unit in strike_settings
  151. .clone()
  152. .supported_units
  153. .unwrap_or(vec![CurrencyUnit::Sat])
  154. {
  155. let strike = strike_settings
  156. .setup(&mut ln_routers, &settings, unit.clone())
  157. .await?;
  158. mint_builder = mint_builder.add_ln_backend(
  159. unit.clone(),
  160. PaymentMethod::Bolt11,
  161. mint_melt_limits,
  162. Arc::new(strike),
  163. );
  164. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, unit);
  165. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  166. }
  167. }
  168. LnBackend::LNbits => {
  169. let lnbits_settings = settings.clone().lnbits.expect("Checked on config load");
  170. let lnbits = lnbits_settings
  171. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  172. .await?;
  173. mint_builder = mint_builder.add_ln_backend(
  174. CurrencyUnit::Sat,
  175. PaymentMethod::Bolt11,
  176. mint_melt_limits,
  177. Arc::new(lnbits),
  178. );
  179. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, CurrencyUnit::Sat);
  180. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  181. }
  182. LnBackend::Phoenixd => {
  183. let phd_settings = settings.clone().phoenixd.expect("Checked at config load");
  184. let phd = phd_settings
  185. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  186. .await?;
  187. mint_builder = mint_builder.add_ln_backend(
  188. CurrencyUnit::Sat,
  189. PaymentMethod::Bolt11,
  190. mint_melt_limits,
  191. Arc::new(phd),
  192. );
  193. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, CurrencyUnit::Sat);
  194. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  195. }
  196. LnBackend::Lnd => {
  197. let lnd_settings = settings.clone().lnd.expect("Checked at config load");
  198. let lnd = lnd_settings
  199. .setup(&mut ln_routers, &settings, CurrencyUnit::Msat)
  200. .await?;
  201. mint_builder = mint_builder.add_ln_backend(
  202. CurrencyUnit::Sat,
  203. PaymentMethod::Bolt11,
  204. mint_melt_limits,
  205. Arc::new(lnd),
  206. );
  207. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, CurrencyUnit::Sat);
  208. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  209. }
  210. LnBackend::FakeWallet => {
  211. let fake_wallet = settings.clone().fake_wallet.expect("Fake wallet defined");
  212. for unit in fake_wallet.clone().supported_units {
  213. let fake = fake_wallet
  214. .setup(&mut ln_routers, &settings, CurrencyUnit::Sat)
  215. .await?;
  216. let fake = Arc::new(fake);
  217. mint_builder = mint_builder.add_ln_backend(
  218. unit.clone(),
  219. PaymentMethod::Bolt11,
  220. mint_melt_limits,
  221. fake.clone(),
  222. );
  223. let nut17_supported = SupportedMethods::new(PaymentMethod::Bolt11, unit);
  224. mint_builder = mint_builder.add_supported_websockets(nut17_supported);
  225. }
  226. }
  227. LnBackend::None => bail!("Ln backend must be set"),
  228. };
  229. if let Some(long_description) = &settings.mint_info.description_long {
  230. mint_builder = mint_builder.with_long_description(long_description.to_string());
  231. }
  232. if let Some(contact_info) = contact_info {
  233. for info in contact_info {
  234. mint_builder = mint_builder.add_contact_info(info);
  235. }
  236. }
  237. if let Some(pubkey) = settings.mint_info.pubkey {
  238. mint_builder = mint_builder.with_pubkey(pubkey);
  239. }
  240. if let Some(icon_url) = &settings.mint_info.icon_url {
  241. mint_builder = mint_builder.with_icon_url(icon_url.to_string());
  242. }
  243. if let Some(motd) = settings.mint_info.motd {
  244. mint_builder = mint_builder.with_motd(motd);
  245. }
  246. let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;
  247. mint_builder = mint_builder
  248. .with_name(settings.mint_info.name)
  249. .with_version(mint_version)
  250. .with_description(settings.mint_info.description)
  251. .with_quote_ttl(10000, 10000)
  252. .with_seed(mnemonic.to_seed_normalized("").to_vec());
  253. let cached_endpoints = vec![
  254. CachedEndpoint::new(NUT19Method::Post, NUT19Path::MintBolt11),
  255. CachedEndpoint::new(NUT19Method::Post, NUT19Path::MeltBolt11),
  256. CachedEndpoint::new(NUT19Method::Post, NUT19Path::Swap),
  257. ];
  258. let cache: HttpCache = settings.info.http_cache.into();
  259. mint_builder = mint_builder.add_cache(Some(cache.ttl.as_secs()), cached_endpoints);
  260. let mint = mint_builder.build().await?;
  261. let mint = Arc::new(mint);
  262. // Check the status of any mint quotes that are pending
  263. // In the event that the mint server is down but the ln node is not
  264. // it is possible that a mint quote was paid but the mint has not been updated
  265. // this will check and update the mint state of those quotes
  266. mint.check_pending_mint_quotes().await?;
  267. // Checks the status of all pending melt quotes
  268. // Pending melt quotes where the payment has gone through inputs are burnt
  269. // Pending melt quotes where the payment has **failed** inputs are reset to unspent
  270. mint.check_pending_melt_quotes().await?;
  271. let listen_addr = settings.info.listen_host;
  272. let listen_port = settings.info.listen_port;
  273. let v1_service =
  274. cdk_axum::create_mint_router_with_custom_cache(Arc::clone(&mint), cache).await?;
  275. let mut mint_service = Router::new()
  276. .merge(v1_service)
  277. .layer(CompressionLayer::new())
  278. .layer(middleware::from_fn(logging_middleware))
  279. .layer(CorsLayer::permissive());
  280. #[cfg(feature = "swagger")]
  281. {
  282. if settings.info.enable_swagger_ui.unwrap_or(false) {
  283. mint_service = mint_service.merge(
  284. utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
  285. .url("/api-docs/openapi.json", cdk_axum::ApiDocV1::openapi()),
  286. );
  287. }
  288. }
  289. for router in ln_routers {
  290. mint_service = mint_service.merge(router);
  291. }
  292. let shutdown = Arc::new(Notify::new());
  293. tokio::spawn({
  294. let shutdown = Arc::clone(&shutdown);
  295. async move { mint.wait_for_paid_invoices(shutdown).await }
  296. });
  297. let axum_result = axum::Server::bind(
  298. &format!("{}:{}", listen_addr, listen_port)
  299. .as_str()
  300. .parse()?,
  301. )
  302. .serve(mint_service.into_make_service())
  303. .await;
  304. shutdown.notify_waiters();
  305. match axum_result {
  306. Ok(_) => {
  307. tracing::info!("Axum server stopped with okay status");
  308. }
  309. Err(err) => {
  310. tracing::warn!("Axum server stopped with error");
  311. tracing::error!("{}", err);
  312. bail!("Axum exited with error")
  313. }
  314. }
  315. Ok(())
  316. }
  317. /// Logs infos about the request and the response
  318. async fn logging_middleware<B>(req: Request<B>, next: Next<B>) -> Response {
  319. let start = std::time::Instant::now();
  320. let path = req.uri().path().to_owned();
  321. let method = req.method().clone();
  322. let response = next.run(req).await;
  323. let duration = start.elapsed();
  324. let status = response.status();
  325. let compression = response
  326. .headers()
  327. .get("content-encoding")
  328. .map(|h| h.to_str().unwrap_or("none"))
  329. .unwrap_or("none");
  330. tracing::trace!(
  331. "Request: {method} {path} | Status: {status} | Compression: {compression} | Duration: {duration:?}",
  332. );
  333. response
  334. }
  335. fn work_dir() -> Result<PathBuf> {
  336. let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
  337. let dir = home_dir.join(".cdk-mintd");
  338. std::fs::create_dir_all(&dir)?;
  339. Ok(dir)
  340. }