main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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;
  13. use cdk::cdk_lightning::{MintLightning, MintMeltSettings};
  14. use cdk::mint::{FeeReserve, Mint};
  15. use cdk::nuts::{
  16. nut04, nut05, ContactInfo, CurrencyUnit, MeltMethodSettings, MintInfo, MintMethodSettings,
  17. MintVersion, MppMethodSettings, Nuts, PaymentMethod,
  18. };
  19. use cdk_axum::LnKey;
  20. use cdk_cln::Cln;
  21. use cdk_fake_wallet::FakeWallet;
  22. use cdk_redb::MintRedbDatabase;
  23. use cdk_sqlite::MintSqliteDatabase;
  24. use cdk_strike::Strike;
  25. use clap::Parser;
  26. use cli::CLIArgs;
  27. use config::{DatabaseEngine, LnBackend};
  28. use futures::StreamExt;
  29. use tokio::sync::Mutex;
  30. use tower_http::cors::CorsLayer;
  31. use tracing_subscriber::EnvFilter;
  32. mod cli;
  33. mod config;
  34. const CARGO_PKG_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
  35. const DEFAULT_QUOTE_TTL_SECS: u64 = 1800;
  36. #[tokio::main]
  37. async fn main() -> anyhow::Result<()> {
  38. let default_filter = "debug";
  39. let sqlx_filter = "sqlx=warn";
  40. let env_filter = EnvFilter::new(format!("{},{}", default_filter, sqlx_filter));
  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 settings = config::Settings::new(&Some(config_file_arg));
  53. let localstore: Arc<dyn MintDatabase<Err = cdk_database::Error> + Send + Sync> =
  54. match settings.database.engine {
  55. DatabaseEngine::Sqlite => {
  56. let sql_db_path = work_dir.join("cdk-mintd.sqlite");
  57. let sqlite_db = MintSqliteDatabase::new(&sql_db_path).await?;
  58. sqlite_db.migrate().await;
  59. Arc::new(sqlite_db)
  60. }
  61. DatabaseEngine::Redb => {
  62. let redb_path = work_dir.join("cdk-mintd.redb");
  63. Arc::new(MintRedbDatabase::new(&redb_path)?)
  64. }
  65. };
  66. let mut contact_info: Option<Vec<ContactInfo>> = None;
  67. if let Some(nostr_contact) = settings.mint_info.contact_nostr_public_key {
  68. let nostr_contact = ContactInfo::new("nostr".to_string(), nostr_contact);
  69. contact_info = match contact_info {
  70. Some(mut vec) => {
  71. vec.push(nostr_contact);
  72. Some(vec)
  73. }
  74. None => Some(vec![nostr_contact]),
  75. };
  76. }
  77. if let Some(email_contact) = settings.mint_info.contact_email {
  78. let email_contact = ContactInfo::new("email".to_string(), email_contact);
  79. contact_info = match contact_info {
  80. Some(mut vec) => {
  81. vec.push(email_contact);
  82. Some(vec)
  83. }
  84. None => Some(vec![email_contact]),
  85. };
  86. }
  87. let mint_version = MintVersion::new(
  88. "cdk-mintd".to_string(),
  89. CARGO_PKG_VERSION.unwrap_or("Unknown").to_string(),
  90. );
  91. let relative_ln_fee = settings.ln.fee_percent;
  92. let absolute_ln_fee_reserve = settings.ln.reserve_fee_min;
  93. let fee_reserve = FeeReserve {
  94. min_fee_reserve: absolute_ln_fee_reserve,
  95. percent_fee_reserve: relative_ln_fee,
  96. };
  97. let (ln, ln_router): (
  98. Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>,
  99. Option<Router>,
  100. ) = match settings.ln.ln_backend {
  101. LnBackend::Cln => {
  102. let cln_socket = expand_path(
  103. settings
  104. .ln
  105. .cln_path
  106. .clone()
  107. .ok_or(anyhow!("cln socket not defined"))?
  108. .to_str()
  109. .ok_or(anyhow!("cln socket not defined"))?,
  110. )
  111. .ok_or(anyhow!("cln socket not defined"))?;
  112. (
  113. Arc::new(
  114. Cln::new(
  115. cln_socket,
  116. fee_reserve,
  117. MintMeltSettings::default(),
  118. MintMeltSettings::default(),
  119. )
  120. .await?,
  121. ),
  122. None,
  123. )
  124. }
  125. LnBackend::Strike => {
  126. let api_key = settings
  127. .ln
  128. .strike_api_key
  129. .expect("Checked when validaing config");
  130. // Channel used for strike web hook
  131. let (sender, receiver) = tokio::sync::mpsc::channel(8);
  132. let webhook_endpoint = "/webhook/invoice";
  133. let webhook_url = format!("{}{}", settings.info.url, webhook_endpoint);
  134. let strike = Strike::new(
  135. api_key,
  136. MintMeltSettings::default(),
  137. MintMeltSettings::default(),
  138. CurrencyUnit::Sat,
  139. Arc::new(Mutex::new(Some(receiver))),
  140. webhook_url,
  141. )
  142. .await?;
  143. let router = strike
  144. .create_invoice_webhook(webhook_endpoint, sender)
  145. .await?;
  146. (Arc::new(strike), Some(router))
  147. }
  148. LnBackend::FakeWallet => (
  149. Arc::new(FakeWallet::new(
  150. fee_reserve,
  151. MintMeltSettings::default(),
  152. MintMeltSettings::default(),
  153. )),
  154. None,
  155. ),
  156. };
  157. let mut ln_backends = HashMap::new();
  158. ln_backends.insert(
  159. LnKey::new(CurrencyUnit::Sat, PaymentMethod::Bolt11),
  160. Arc::clone(&ln),
  161. );
  162. let (nut04_settings, nut05_settings, mpp_settings): (
  163. nut04::Settings,
  164. nut05::Settings,
  165. Vec<MppMethodSettings>,
  166. ) = ln_backends.iter().fold(
  167. (
  168. nut04::Settings::new(vec![], false),
  169. nut05::Settings::new(vec![], false),
  170. Vec::new(),
  171. ),
  172. |(mut nut_04, mut nut_05, mut mpp), (key, ln)| {
  173. let settings = ln.get_settings();
  174. let m = MppMethodSettings {
  175. method: key.method.clone(),
  176. unit: key.unit,
  177. mpp: settings.mpp,
  178. };
  179. let n4 = MintMethodSettings {
  180. method: key.method.clone(),
  181. unit: key.unit,
  182. min_amount: Some(settings.mint_settings.min_amount),
  183. max_amount: Some(settings.mint_settings.max_amount),
  184. };
  185. let n5 = MeltMethodSettings {
  186. method: key.method.clone(),
  187. unit: key.unit,
  188. min_amount: Some(settings.melt_settings.min_amount),
  189. max_amount: Some(settings.melt_settings.max_amount),
  190. };
  191. nut_04.methods.push(n4);
  192. nut_05.methods.push(n5);
  193. mpp.push(m);
  194. (nut_04, nut_05, mpp)
  195. },
  196. );
  197. let nuts = Nuts::new()
  198. .nut04(nut04_settings)
  199. .nut05(nut05_settings)
  200. .nut07(true)
  201. .nut08(true)
  202. .nut09(true)
  203. .nut10(true)
  204. .nut11(true)
  205. .nut12(true)
  206. .nut14(true)
  207. .nut15(mpp_settings);
  208. let mut mint_info = MintInfo::new()
  209. .name(settings.mint_info.name)
  210. .version(mint_version)
  211. .description(settings.mint_info.description)
  212. .nuts(nuts);
  213. if let Some(long_description) = &settings.mint_info.description_long {
  214. mint_info = mint_info.long_description(long_description);
  215. }
  216. if let Some(contact_info) = contact_info {
  217. mint_info = mint_info.contact_info(contact_info);
  218. }
  219. if let Some(pubkey) = settings.mint_info.pubkey {
  220. mint_info = mint_info.pubkey(pubkey);
  221. }
  222. if let Some(motd) = settings.mint_info.motd {
  223. mint_info = mint_info.motd(motd);
  224. }
  225. let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;
  226. let input_fee_ppk = settings.info.input_fee_ppk.unwrap_or(0);
  227. let mut supported_units = HashMap::new();
  228. supported_units.insert(CurrencyUnit::Sat, (input_fee_ppk, 64));
  229. let mint = Mint::new(
  230. &settings.info.url,
  231. &mnemonic.to_seed_normalized(""),
  232. mint_info,
  233. localstore,
  234. supported_units,
  235. )
  236. .await?;
  237. let mint = Arc::new(mint);
  238. // Check the status of any mint quotes that are pending
  239. // In the event that the mint server is down but the ln node is not
  240. // it is possible that a mint quote was paid but the mint has not been updated
  241. // this will check and update the mint state of those quotes
  242. check_pending_quotes(Arc::clone(&mint), Arc::clone(&ln)).await?;
  243. let mint_url = settings.info.url;
  244. let listen_addr = settings.info.listen_host;
  245. let listen_port = settings.info.listen_port;
  246. let quote_ttl = settings
  247. .info
  248. .seconds_quote_is_valid_for
  249. .unwrap_or(DEFAULT_QUOTE_TTL_SECS);
  250. let v1_service =
  251. cdk_axum::create_mint_router(&mint_url, Arc::clone(&mint), ln_backends, quote_ttl).await?;
  252. let mint_service = Router::new()
  253. .nest("/", v1_service)
  254. .layer(CorsLayer::permissive());
  255. let mint_service = match ln_router {
  256. Some(ln_router) => mint_service.nest("/", ln_router),
  257. None => mint_service,
  258. };
  259. // Spawn task to wait for invoces to be paid and update mint quotes
  260. tokio::spawn(async move {
  261. loop {
  262. match ln.wait_any_invoice().await {
  263. Ok(mut stream) => {
  264. while let Some(request_lookup_id) = stream.next().await {
  265. if let Err(err) =
  266. handle_paid_invoice(Arc::clone(&mint), &request_lookup_id).await
  267. {
  268. tracing::warn!("{:?}", err);
  269. }
  270. }
  271. }
  272. Err(err) => {
  273. tracing::warn!("Could not get invoice stream: {}", err);
  274. }
  275. }
  276. }
  277. });
  278. let listener =
  279. tokio::net::TcpListener::bind(format!("{}:{}", listen_addr, listen_port)).await?;
  280. axum::serve(listener, mint_service).await?;
  281. Ok(())
  282. }
  283. /// Update mint quote when called for a paid invoice
  284. async fn handle_paid_invoice(mint: Arc<Mint>, request_lookup_id: &str) -> Result<()> {
  285. tracing::debug!("Invoice with lookup id paid: {}", request_lookup_id);
  286. if let Ok(Some(mint_quote)) = mint
  287. .localstore
  288. .get_mint_quote_by_request_lookup_id(request_lookup_id)
  289. .await
  290. {
  291. tracing::debug!(
  292. "Quote {} paid by lookup id {}",
  293. mint_quote.id,
  294. request_lookup_id
  295. );
  296. mint.localstore
  297. .update_mint_quote_state(&mint_quote.id, cdk::nuts::MintQuoteState::Paid)
  298. .await?;
  299. }
  300. Ok(())
  301. }
  302. /// Used on mint start up to check status of all pending mint quotes
  303. async fn check_pending_quotes(
  304. mint: Arc<Mint>,
  305. ln: Arc<dyn MintLightning<Err = cdk_lightning::Error> + Send + Sync>,
  306. ) -> Result<()> {
  307. let mut pending_quotes = mint.get_pending_mint_quotes().await?;
  308. tracing::trace!("There are {} pending mint quotes.", pending_quotes.len());
  309. let mut unpaid_quotes = mint.get_unpaid_mint_quotes().await?;
  310. tracing::trace!("There are {} unpaid mint quotes.", unpaid_quotes.len());
  311. unpaid_quotes.append(&mut pending_quotes);
  312. for quote in unpaid_quotes {
  313. tracing::trace!("Checking status of mint quote: {}", quote.id);
  314. let lookup_id = quote.request_lookup_id;
  315. let state = ln.check_invoice_status(&lookup_id).await?;
  316. if state != quote.state {
  317. tracing::trace!("Mintquote status changed: {}", quote.id);
  318. mint.localstore
  319. .update_mint_quote_state(&quote.id, state)
  320. .await?;
  321. }
  322. }
  323. Ok(())
  324. }
  325. fn expand_path(path: &str) -> Option<PathBuf> {
  326. if path.starts_with('~') {
  327. if let Some(home_dir) = home::home_dir().as_mut() {
  328. let remainder = &path[2..];
  329. home_dir.push(remainder);
  330. let expanded_path = home_dir;
  331. Some(expanded_path.clone())
  332. } else {
  333. None
  334. }
  335. } else {
  336. Some(PathBuf::from(path))
  337. }
  338. }
  339. fn work_dir() -> Result<PathBuf> {
  340. let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
  341. Ok(home_dir.join(".cdk-mintd"))
  342. }