main.rs 15 KB

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