regtest.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. use std::fmt::Debug;
  2. use std::str::FromStr;
  3. use std::sync::Arc;
  4. use std::time::Duration;
  5. use anyhow::{bail, Result};
  6. use bip39::Mnemonic;
  7. use cashu::{MeltOptions, Mpp};
  8. use cdk::amount::{Amount, SplitTarget};
  9. use cdk::nuts::nut00::ProofsMethods;
  10. use cdk::nuts::{
  11. CurrencyUnit, MeltQuoteState, MintBolt11Request, MintQuoteState, NotificationPayload,
  12. PreMintSecrets, State,
  13. };
  14. use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
  15. use cdk_integration_tests::init_regtest::{
  16. get_cln_dir, get_lnd_cert_file_path, get_lnd_dir, get_lnd_macaroon_path, get_mint_port,
  17. get_mint_url, get_mint_ws_url, LND_RPC_ADDR, LND_TWO_RPC_ADDR,
  18. };
  19. use cdk_integration_tests::wait_for_mint_to_be_paid;
  20. use cdk_sqlite::wallet::{self, memory};
  21. use futures::{join, SinkExt, StreamExt};
  22. use lightning_invoice::Bolt11Invoice;
  23. use ln_regtest_rs::ln_client::{ClnClient, LightningClient, LndClient};
  24. use ln_regtest_rs::InvoiceStatus;
  25. use serde_json::json;
  26. use tokio::time::timeout;
  27. use tokio_tungstenite::connect_async;
  28. use tokio_tungstenite::tungstenite::protocol::Message;
  29. // This is the ln wallet we use to send/receive ln payements as the wallet
  30. async fn init_lnd_client() -> LndClient {
  31. let lnd_dir = get_lnd_dir("one");
  32. let cert_file = lnd_dir.join("tls.cert");
  33. let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
  34. LndClient::new(
  35. format!("https://{}", LND_RPC_ADDR),
  36. cert_file,
  37. macaroon_file,
  38. )
  39. .await
  40. .unwrap()
  41. }
  42. async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
  43. reader: &mut T,
  44. timeout_to_wait: Duration,
  45. ) -> (String, NotificationPayload<String>) {
  46. let msg = timeout(timeout_to_wait, reader.next())
  47. .await
  48. .expect("timeout")
  49. .unwrap()
  50. .unwrap();
  51. let mut response: serde_json::Value =
  52. serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
  53. let mut params_raw = response
  54. .as_object_mut()
  55. .expect("object")
  56. .remove("params")
  57. .expect("valid params");
  58. let params_map = params_raw.as_object_mut().expect("params is object");
  59. (
  60. params_map
  61. .remove("subId")
  62. .unwrap()
  63. .as_str()
  64. .unwrap()
  65. .to_string(),
  66. serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
  67. )
  68. }
  69. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  70. async fn test_regtest_mint_melt_round_trip() -> Result<()> {
  71. let lnd_client = init_lnd_client().await;
  72. let wallet = Wallet::new(
  73. &get_mint_url("0"),
  74. CurrencyUnit::Sat,
  75. Arc::new(memory::empty().await?),
  76. &Mnemonic::generate(12)?.to_seed_normalized(""),
  77. None,
  78. )?;
  79. let (ws_stream, _) = connect_async(get_mint_ws_url("0"))
  80. .await
  81. .expect("Failed to connect");
  82. let (mut write, mut reader) = ws_stream.split();
  83. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  84. lnd_client.pay_invoice(mint_quote.request).await.unwrap();
  85. let proofs = wallet
  86. .mint(&mint_quote.id, SplitTarget::default(), None)
  87. .await?;
  88. let mint_amount = proofs.total_amount()?;
  89. assert!(mint_amount == 100.into());
  90. let invoice = lnd_client.create_invoice(Some(50)).await?;
  91. let melt = wallet.melt_quote(invoice, None).await?;
  92. write
  93. .send(Message::Text(
  94. serde_json::to_string(&json!({
  95. "jsonrpc": "2.0",
  96. "id": 2,
  97. "method": "subscribe",
  98. "params": {
  99. "kind": "bolt11_melt_quote",
  100. "filters": [
  101. melt.id.clone(),
  102. ],
  103. "subId": "test-sub",
  104. }
  105. }))?
  106. .into(),
  107. ))
  108. .await?;
  109. assert_eq!(
  110. reader.next().await.unwrap().unwrap().to_text().unwrap(),
  111. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#
  112. );
  113. let melt_response = wallet.melt(&melt.id).await.unwrap();
  114. assert!(melt_response.preimage.is_some());
  115. assert!(melt_response.state == MeltQuoteState::Paid);
  116. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  117. // first message is the current state
  118. assert_eq!("test-sub", sub_id);
  119. let payload = match payload {
  120. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  121. _ => panic!("Wrong payload"),
  122. };
  123. assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  124. assert_eq!(payload.quote.to_string(), melt.id);
  125. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  126. // get current state
  127. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  128. assert_eq!("test-sub", sub_id);
  129. let payload = match payload {
  130. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  131. _ => panic!("Wrong payload"),
  132. };
  133. assert_eq!(payload.amount + payload.fee_reserve, 50.into());
  134. assert_eq!(payload.quote.to_string(), melt.id);
  135. assert_eq!(payload.state, MeltQuoteState::Paid);
  136. Ok(())
  137. }
  138. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  139. async fn test_regtest_mint_melt() -> Result<()> {
  140. let lnd_client = init_lnd_client().await;
  141. let wallet = Wallet::new(
  142. &get_mint_url("0"),
  143. CurrencyUnit::Sat,
  144. Arc::new(memory::empty().await?),
  145. &Mnemonic::generate(12)?.to_seed_normalized(""),
  146. None,
  147. )?;
  148. let mint_amount = Amount::from(100);
  149. let mint_quote = wallet.mint_quote(mint_amount, None).await?;
  150. assert_eq!(mint_quote.amount, mint_amount);
  151. lnd_client.pay_invoice(mint_quote.request).await?;
  152. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  153. let proofs = wallet
  154. .mint(&mint_quote.id, SplitTarget::default(), None)
  155. .await?;
  156. let mint_amount = proofs.total_amount()?;
  157. assert!(mint_amount == 100.into());
  158. Ok(())
  159. }
  160. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  161. async fn test_restore() -> Result<()> {
  162. let lnd_client = init_lnd_client().await;
  163. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  164. let wallet = Wallet::new(
  165. &get_mint_url("0"),
  166. CurrencyUnit::Sat,
  167. Arc::new(memory::empty().await?),
  168. &seed,
  169. None,
  170. )?;
  171. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  172. lnd_client.pay_invoice(mint_quote.request).await?;
  173. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  174. let _mint_amount = wallet
  175. .mint(&mint_quote.id, SplitTarget::default(), None)
  176. .await?;
  177. assert!(wallet.total_balance().await? == 100.into());
  178. let wallet_2 = Wallet::new(
  179. &get_mint_url("0"),
  180. CurrencyUnit::Sat,
  181. Arc::new(memory::empty().await?),
  182. &seed,
  183. None,
  184. )?;
  185. assert!(wallet_2.total_balance().await? == 0.into());
  186. let restored = wallet_2.restore().await?;
  187. let proofs = wallet_2.get_unspent_proofs().await?;
  188. wallet_2
  189. .swap(None, SplitTarget::default(), proofs, None, false)
  190. .await?;
  191. assert!(restored == 100.into());
  192. assert!(wallet_2.total_balance().await? == 100.into());
  193. let proofs = wallet.get_unspent_proofs().await?;
  194. let states = wallet.check_proofs_spent(proofs).await?;
  195. for state in states {
  196. if state.state != State::Spent {
  197. bail!("All proofs should be spent");
  198. }
  199. }
  200. Ok(())
  201. }
  202. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  203. async fn test_pay_invoice_twice() -> anyhow::Result<()> {
  204. let lnd_client = init_lnd_client().await;
  205. let wallet = Wallet::new(
  206. &get_mint_url("0"),
  207. CurrencyUnit::Sat,
  208. Arc::new(memory::empty().await.unwrap()),
  209. &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
  210. None,
  211. )?;
  212. let mint_quote = wallet
  213. .mint_quote(100.into(), None)
  214. .await
  215. .expect("Get mint quote");
  216. lnd_client
  217. .pay_invoice(mint_quote.request)
  218. .await
  219. .expect("Could not pay invoice");
  220. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60)
  221. .await
  222. .expect("Mint invoice timeout not paid");
  223. let proofs = wallet
  224. .mint(&mint_quote.id, SplitTarget::default(), None)
  225. .await
  226. .expect("Could not mint");
  227. let mint_amount = proofs.total_amount().unwrap();
  228. assert_eq!(mint_amount, 100.into());
  229. let invoice = lnd_client
  230. .create_invoice(Some(10))
  231. .await
  232. .expect("Could not create invoice");
  233. let melt_quote = wallet
  234. .melt_quote(invoice.clone(), None)
  235. .await
  236. .expect("Could not get melt quote");
  237. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  238. let melt_two = wallet.melt_quote(invoice, None).await.unwrap();
  239. let melt_two = wallet.melt(&melt_two.id).await;
  240. match melt_two {
  241. Err(err) => match err {
  242. cdk::Error::RequestAlreadyPaid => (),
  243. err => {
  244. bail!("Wrong invoice already paid: {}", err.to_string());
  245. }
  246. },
  247. Ok(_) => {
  248. bail!("Should not have allowed second payment");
  249. }
  250. }
  251. let balance = wallet.total_balance().await.unwrap();
  252. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  253. Ok(())
  254. }
  255. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  256. async fn test_internal_payment() -> Result<()> {
  257. let lnd_client = init_lnd_client().await;
  258. let wallet = Wallet::new(
  259. &get_mint_url("0"),
  260. CurrencyUnit::Sat,
  261. Arc::new(memory::empty().await?),
  262. &Mnemonic::generate(12)?.to_seed_normalized(""),
  263. None,
  264. )?;
  265. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  266. lnd_client.pay_invoice(mint_quote.request).await?;
  267. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  268. let _mint_amount = wallet
  269. .mint(&mint_quote.id, SplitTarget::default(), None)
  270. .await?;
  271. assert!(wallet.total_balance().await? == 100.into());
  272. let wallet_2 = Wallet::new(
  273. &get_mint_url("0"),
  274. CurrencyUnit::Sat,
  275. Arc::new(memory::empty().await?),
  276. &Mnemonic::generate(12)?.to_seed_normalized(""),
  277. None,
  278. )?;
  279. let mint_quote = wallet_2.mint_quote(10.into(), None).await?;
  280. let melt = wallet.melt_quote(mint_quote.request.clone(), None).await?;
  281. assert_eq!(melt.amount, 10.into());
  282. let _melted = wallet.melt(&melt.id).await.unwrap();
  283. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  284. let _wallet_2_mint = wallet_2
  285. .mint(&mint_quote.id, SplitTarget::default(), None)
  286. .await
  287. .unwrap();
  288. let check_paid = match get_mint_port("0") {
  289. 8085 => {
  290. let cln_one_dir = get_cln_dir("one");
  291. let cln_client = ClnClient::new(cln_one_dir.clone(), None).await?;
  292. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  293. cln_client
  294. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  295. .await
  296. .expect("Could not check invoice")
  297. }
  298. 8087 => {
  299. let lnd_two_dir = get_lnd_dir("two");
  300. let lnd_client = LndClient::new(
  301. format!("https://{}", LND_TWO_RPC_ADDR),
  302. get_lnd_cert_file_path(&lnd_two_dir),
  303. get_lnd_macaroon_path(&lnd_two_dir),
  304. )
  305. .await?;
  306. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  307. lnd_client
  308. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  309. .await
  310. .expect("Could not check invoice")
  311. }
  312. _ => panic!("Unknown mint port"),
  313. };
  314. match check_paid {
  315. InvoiceStatus::Unpaid => (),
  316. _ => {
  317. bail!("Invoice has incorrect status: {:?}", check_paid);
  318. }
  319. }
  320. let wallet_2_balance = wallet_2.total_balance().await?;
  321. assert!(wallet_2_balance == 10.into());
  322. let wallet_1_balance = wallet.total_balance().await?;
  323. assert!(wallet_1_balance == 90.into());
  324. Ok(())
  325. }
  326. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  327. async fn test_cached_mint() -> Result<()> {
  328. let lnd_client = init_lnd_client().await;
  329. let wallet = Wallet::new(
  330. &get_mint_url("0"),
  331. CurrencyUnit::Sat,
  332. Arc::new(memory::empty().await?),
  333. &Mnemonic::generate(12)?.to_seed_normalized(""),
  334. None,
  335. )?;
  336. let mint_amount = Amount::from(100);
  337. let quote = wallet.mint_quote(mint_amount, None).await?;
  338. lnd_client.pay_invoice(quote.request).await?;
  339. wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
  340. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  341. let http_client = HttpClient::new(get_mint_url("0").as_str().parse()?, None);
  342. let premint_secrets =
  343. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  344. let mut request = MintBolt11Request {
  345. quote: quote.id,
  346. outputs: premint_secrets.blinded_messages(),
  347. signature: None,
  348. };
  349. let secret_key = quote.secret_key;
  350. request.sign(secret_key.expect("Secret key on quote"))?;
  351. let response = http_client.post_mint(request.clone()).await?;
  352. let response1 = http_client.post_mint(request).await?;
  353. assert!(response == response1);
  354. Ok(())
  355. }
  356. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  357. async fn test_websocket_connection() -> Result<()> {
  358. let wallet = Wallet::new(
  359. &get_mint_url("0"),
  360. CurrencyUnit::Sat,
  361. Arc::new(wallet::memory::empty().await?),
  362. &Mnemonic::generate(12)?.to_seed_normalized(""),
  363. None,
  364. )?;
  365. // Create a small mint quote to test notifications
  366. let mint_quote = wallet.mint_quote(10.into(), None).await?;
  367. // Subscribe to notifications for this quote
  368. let mut subscription = wallet
  369. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  370. .id
  371. .clone()]))
  372. .await;
  373. // First check we get the unpaid state
  374. let msg = timeout(Duration::from_secs(10), subscription.recv())
  375. .await
  376. .expect("timeout waiting for unpaid notification")
  377. .ok_or_else(|| anyhow::anyhow!("No unpaid notification received"))?;
  378. match msg {
  379. NotificationPayload::MintQuoteBolt11Response(response) => {
  380. assert_eq!(response.quote.to_string(), mint_quote.id);
  381. assert_eq!(response.state, MintQuoteState::Unpaid);
  382. }
  383. _ => bail!("Unexpected notification type"),
  384. }
  385. let lnd_client = init_lnd_client().await;
  386. lnd_client.pay_invoice(mint_quote.request).await?;
  387. // Wait for paid notification with 10 second timeout
  388. let msg = timeout(Duration::from_secs(10), subscription.recv())
  389. .await
  390. .expect("timeout waiting for paid notification")
  391. .ok_or_else(|| anyhow::anyhow!("No paid notification received"))?;
  392. match msg {
  393. NotificationPayload::MintQuoteBolt11Response(response) => {
  394. assert_eq!(response.quote.to_string(), mint_quote.id);
  395. assert_eq!(response.state, MintQuoteState::Paid);
  396. Ok(())
  397. }
  398. _ => bail!("Unexpected notification type"),
  399. }
  400. }
  401. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  402. async fn test_multimint_melt() -> Result<()> {
  403. let lnd_client = init_lnd_client().await;
  404. let wallet1 = Wallet::new(
  405. &get_mint_url("0"),
  406. CurrencyUnit::Sat,
  407. Arc::new(memory::empty().await?),
  408. &Mnemonic::generate(12)?.to_seed_normalized(""),
  409. None,
  410. )?;
  411. let wallet2 = Wallet::new(
  412. &get_mint_url("1"),
  413. CurrencyUnit::Sat,
  414. Arc::new(memory::empty().await?),
  415. &Mnemonic::generate(12)?.to_seed_normalized(""),
  416. None,
  417. )?;
  418. let mint_amount = Amount::from(100);
  419. // Fund the wallets
  420. let quote = wallet1.mint_quote(mint_amount, None).await?;
  421. lnd_client.pay_invoice(quote.request.clone()).await?;
  422. wait_for_mint_to_be_paid(&wallet1, &quote.id, 60).await?;
  423. wallet1
  424. .mint(&quote.id, SplitTarget::default(), None)
  425. .await?;
  426. let quote = wallet2.mint_quote(mint_amount, None).await?;
  427. lnd_client.pay_invoice(quote.request.clone()).await?;
  428. wait_for_mint_to_be_paid(&wallet2, &quote.id, 60).await?;
  429. wallet2
  430. .mint(&quote.id, SplitTarget::default(), None)
  431. .await?;
  432. // Get an invoice
  433. let invoice = lnd_client.create_invoice(Some(50)).await?;
  434. // Get multi-part melt quotes
  435. let melt_options = MeltOptions::Mpp {
  436. mpp: Mpp {
  437. amount: Amount::from(25000),
  438. },
  439. };
  440. let quote_1 = wallet1
  441. .melt_quote(invoice.clone(), Some(melt_options))
  442. .await
  443. .expect("Could not get melt quote");
  444. let quote_2 = wallet2
  445. .melt_quote(invoice.clone(), Some(melt_options))
  446. .await
  447. .expect("Could not get melt quote");
  448. // Multimint pay invoice
  449. let result1 = wallet1.melt(&quote_1.id);
  450. let result2 = wallet2.melt(&quote_2.id);
  451. let result = join!(result1, result2);
  452. // Unpack results
  453. let result1 = result.0.unwrap();
  454. let result2 = result.1.unwrap();
  455. // Check
  456. assert!(result1.state == result2.state);
  457. assert!(result1.state == MeltQuoteState::Paid);
  458. Ok(())
  459. }
  460. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  461. async fn test_database_type() -> Result<()> {
  462. // Get the database type and work dir from environment
  463. let db_type = std::env::var("MINT_DATABASE").expect("MINT_DATABASE env var should be set");
  464. let work_dir =
  465. std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
  466. // Check that the correct database file exists
  467. match db_type.as_str() {
  468. "REDB" => {
  469. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.redb");
  470. assert!(
  471. db_path.exists(),
  472. "Expected redb database file to exist at {:?}",
  473. db_path
  474. );
  475. }
  476. "SQLITE" => {
  477. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.sqlite");
  478. assert!(
  479. db_path.exists(),
  480. "Expected sqlite database file to exist at {:?}",
  481. db_path
  482. );
  483. }
  484. "MEMORY" => {
  485. // Memory database has no file to check
  486. println!("Memory database in use - no file to check");
  487. }
  488. _ => bail!("Unknown database type: {}", db_type),
  489. }
  490. Ok(())
  491. }