main.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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, Result};
  9. use axum::Router;
  10. use bip39::Mnemonic;
  11. use cdk::cdk_database::{self, MintDatabase};
  12. use cdk::cdk_lightning::MintLightning;
  13. use cdk::mint::{FeeReserve, Mint};
  14. use cdk::nuts::{
  15. nut04, nut05, ContactInfo, CurrencyUnit, MeltMethodSettings, MintInfo, MintMethodSettings,
  16. MintVersion, MppMethodSettings, Nuts, PaymentMethod,
  17. };
  18. use cdk::{cdk_lightning, Amount};
  19. use cdk_axum::LnKey;
  20. use cdk_cln::Cln;
  21. use cdk_redb::MintRedbDatabase;
  22. use cdk_sqlite::MintSqliteDatabase;
  23. use clap::Parser;
  24. use cli::CLIArgs;
  25. use config::{DatabaseEngine, LnBackend};
  26. use futures::StreamExt;
  27. use tower_http::cors::CorsLayer;
  28. use tracing_subscriber::EnvFilter;
  29. mod cli;
  30. mod config;
  31. const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
  32. const DEFAULT_QUOTE_TTL_SECS: u64 = 1800;
  33. #[tokio::main]
  34. async fn main() -> anyhow::Result<()> {
  35. let default_filter = "debug";
  36. let sqlx_filter = "sqlx=warn";
  37. let env_filter = EnvFilter::new(format!("{},{}", default_filter, sqlx_filter));
  38. tracing_subscriber::fmt().with_env_filter(env_filter).init();
  39. let args = CLIArgs::parse();
  40. let work_dir = match args.work_dir {
  41. Some(w) => w,
  42. None => work_dir()?,
  43. };
  44. // get config file name from args
  45. let config_file_arg = match args.config {
  46. Some(c) => c,
  47. None => work_dir.join("config.toml"),
  48. };
  49. let settings = config::Settings::new(&Some(config_file_arg));
  50. let localstore: Arc<dyn MintDatabase<Err = cdk_database::Error> + Send + Sync> =
  51. match settings.database.engine {
  52. DatabaseEngine::Sqlite => {
  53. let sql_db_path = work_dir.join("cdk-mintd.sqlite");
  54. let sqlite_db = MintSqliteDatabase::new(&sql_db_path).await?;
  55. sqlite_db.migrate().await;
  56. Arc::new(sqlite_db)
  57. }
  58. DatabaseEngine::Redb => {
  59. let redb_path = work_dir.join("cdk-mintd.redb");
  60. Arc::new(MintRedbDatabase::new(&redb_path)?)
  61. }
  62. };
  63. let mut contact_info: Option<Vec<ContactInfo>> = None;
  64. if let Some(nostr_contact) = settings.mint_info.contact_nostr_public_key {
  65. let nostr_contact = ContactInfo::new("nostr".to_string(), nostr_contact);
  66. contact_info = match contact_info {
  67. Some(mut vec) => {
  68. vec.push(nostr_contact);
  69. Some(vec)
  70. }
  71. None => Some(vec![nostr_contact]),
  72. };
  73. }
  74. if let Some(email_contact) = settings.mint_info.contact_email {
  75. let email_contact = ContactInfo::new("email".to_string(), email_contact);
  76. contact_info = match contact_info {
  77. Some(mut vec) => {
  78. vec.push(email_contact);
  79. Some(vec)
  80. }
  81. None => Some(vec![email_contact]),
  82. };
  83. }
  84. let mint_version = MintVersion::new(
  85. "cdk-mintd".to_string(),
  86. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  87. );
  88. let relative_ln_fee = settings.ln.fee_percent;
  89. let absolute_ln_fee_reserve = settings.ln.reserve_fee_min;
  90. let fee_reserve = FeeReserve {
  91. min_fee_reserve: absolute_ln_fee_reserve,
  92. percent_fee_reserve: relative_ln_fee,
  93. };
  94. let ln: Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync> =
  95. match settings.ln.ln_backend {
  96. LnBackend::Cln => {
  97. let cln_socket = expand_path(
  98. settings
  99. .ln
  100. .cln_path
  101. .clone()
  102. .ok_or(anyhow!("cln socket not defined"))?
  103. .to_str()
  104. .ok_or(anyhow!("cln socket not defined"))?,
  105. )
  106. .ok_or(anyhow!("cln socket not defined"))?;
  107. Arc::new(Cln::new(cln_socket, fee_reserve, 1000, 1000000, 1000, 100000).await?)
  108. }
  109. };
  110. let mut ln_backends = HashMap::new();
  111. ln_backends.insert(
  112. LnKey::new(CurrencyUnit::Sat, PaymentMethod::Bolt11),
  113. Arc::clone(&ln),
  114. );
  115. let (nut04_settings, nut05_settings, mpp_settings): (
  116. nut04::Settings,
  117. nut05::Settings,
  118. Vec<MppMethodSettings>,
  119. ) = ln_backends.iter().fold(
  120. (
  121. nut04::Settings::new(vec![], false),
  122. nut05::Settings::new(vec![], false),
  123. Vec::new(),
  124. ),
  125. |(mut nut_04, mut nut_05, mut mpp), (key, ln)| {
  126. let settings = ln.get_settings();
  127. let m = MppMethodSettings {
  128. method: key.method.clone(),
  129. unit: key.unit,
  130. mpp: settings.mpp,
  131. };
  132. let n4 = MintMethodSettings {
  133. method: key.method.clone(),
  134. unit: key.unit,
  135. min_amount: Some(Amount::from(settings.min_mint_amount)),
  136. max_amount: Some(Amount::from(settings.max_mint_amount)),
  137. };
  138. let n5 = MeltMethodSettings {
  139. method: key.method.clone(),
  140. unit: key.unit,
  141. min_amount: Some(Amount::from(settings.min_melt_amount)),
  142. max_amount: Some(Amount::from(settings.max_melt_amount)),
  143. };
  144. nut_04.methods.push(n4);
  145. nut_05.methods.push(n5);
  146. mpp.push(m);
  147. (nut_04, nut_05, mpp)
  148. },
  149. );
  150. let nuts = Nuts::new()
  151. .nut04(nut04_settings)
  152. .nut05(nut05_settings)
  153. .nut15(mpp_settings);
  154. let mut mint_info = MintInfo::new()
  155. .name(settings.mint_info.name)
  156. .version(mint_version)
  157. .description(settings.mint_info.description)
  158. .nuts(nuts);
  159. if let Some(long_description) = &settings.mint_info.description_long {
  160. mint_info = mint_info.long_description(long_description);
  161. }
  162. if let Some(contact_info) = contact_info {
  163. mint_info = mint_info.contact_info(contact_info);
  164. }
  165. if let Some(pubkey) = settings.mint_info.pubkey {
  166. mint_info = mint_info.pubkey(pubkey);
  167. }
  168. if let Some(motd) = settings.mint_info.motd {
  169. mint_info = mint_info.motd(motd);
  170. }
  171. let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;
  172. let input_fee_ppk = settings.info.input_fee_ppk.unwrap_or(0);
  173. let mut supported_units = HashMap::new();
  174. supported_units.insert(CurrencyUnit::Sat, (input_fee_ppk, 64));
  175. let mint = Mint::new(
  176. &settings.info.url,
  177. &mnemonic.to_seed_normalized(""),
  178. mint_info,
  179. localstore,
  180. supported_units,
  181. )
  182. .await?;
  183. let mint = Arc::new(mint);
  184. // Check the status of any mint quotes that are pending
  185. // In the event that the mint server is down but the ln node is not
  186. // it is possible that a mint quote was paid but the mint has not been updated
  187. // this will check and update the mint state of those quotes
  188. check_pending_quotes(Arc::clone(&mint), Arc::clone(&ln)).await?;
  189. let mint_url = settings.info.url;
  190. let listen_addr = settings.info.listen_host;
  191. let listen_port = settings.info.listen_port;
  192. let quote_ttl = settings
  193. .info
  194. .seconds_quote_is_valid_for
  195. .unwrap_or(DEFAULT_QUOTE_TTL_SECS);
  196. let v1_service =
  197. cdk_axum::create_mint_router(&mint_url, Arc::clone(&mint), ln_backends, quote_ttl).await?;
  198. let mint_service = Router::new()
  199. .nest("/", v1_service)
  200. .layer(CorsLayer::permissive());
  201. // Spawn task to wait for invoces to be paid and update mint quotes
  202. tokio::spawn(async move {
  203. loop {
  204. match ln.wait_any_invoice().await {
  205. Ok(mut stream) => {
  206. while let Some(request_lookup_id) = stream.next().await {
  207. if let Err(err) =
  208. handle_paid_invoice(Arc::clone(&mint), &request_lookup_id).await
  209. {
  210. tracing::warn!("{:?}", err);
  211. }
  212. }
  213. }
  214. Err(err) => {
  215. tracing::warn!("Could not get invoice stream: {}", err);
  216. }
  217. }
  218. }
  219. });
  220. let listener =
  221. tokio::net::TcpListener::bind(format!("{}:{}", listen_addr, listen_port)).await?;
  222. axum::serve(listener, mint_service).await?;
  223. Ok(())
  224. }
  225. /// Update mint quote when called for a paid invoice
  226. async fn handle_paid_invoice(mint: Arc<Mint>, request_lookup_id: &str) -> Result<()> {
  227. tracing::debug!("Invoice with lookup id paid: {}", request_lookup_id);
  228. if let Ok(Some(mint_quote)) = mint
  229. .localstore
  230. .get_mint_quote_by_request_lookup_id(request_lookup_id)
  231. .await
  232. {
  233. tracing::debug!(
  234. "Quote {} paid by lookup id {}",
  235. mint_quote.id,
  236. request_lookup_id
  237. );
  238. mint.localstore
  239. .update_mint_quote_state(&mint_quote.id, cdk::nuts::MintQuoteState::Paid)
  240. .await?;
  241. }
  242. Ok(())
  243. }
  244. /// Used on mint start up to check status of all pending mint quotes
  245. async fn check_pending_quotes(
  246. mint: Arc<Mint>,
  247. ln: Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>,
  248. ) -> Result<()> {
  249. let pending_quotes = mint.get_pending_mint_quotes().await?;
  250. for quote in pending_quotes {
  251. let lookup_id = quote.request_lookup_id;
  252. let state = ln.check_invoice_status(&lookup_id).await?;
  253. if state != quote.state {
  254. mint.localstore
  255. .update_mint_quote_state(&quote.id, state)
  256. .await?;
  257. }
  258. }
  259. Ok(())
  260. }
  261. fn expand_path(path: &str) -> Option<PathBuf> {
  262. if path.starts_with('~') {
  263. if let Some(home_dir) = home::home_dir().as_mut() {
  264. let remainder = &path[2..];
  265. home_dir.push(remainder);
  266. let expanded_path = home_dir;
  267. Some(expanded_path.clone())
  268. } else {
  269. None
  270. }
  271. } else {
  272. Some(PathBuf::from(path))
  273. }
  274. }
  275. fn work_dir() -> Result<PathBuf> {
  276. let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
  277. Ok(home_dir.join(".cdk-mintd"))
  278. }