regtest.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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 seed = Mnemonic::generate(12).unwrap().to_seed_normalized("");
  206. let wallet = Wallet::new(
  207. &get_mint_url("0"),
  208. CurrencyUnit::Sat,
  209. Arc::new(memory::empty().await.unwrap()),
  210. &seed,
  211. None,
  212. )?;
  213. let mint_quote = wallet
  214. .mint_quote(100.into(), None)
  215. .await
  216. .expect("Get mint quote");
  217. lnd_client
  218. .pay_invoice(mint_quote.request)
  219. .await
  220. .expect("Could not pay invoice");
  221. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60)
  222. .await
  223. .expect("Mint invoice timeout not paid");
  224. let proofs = wallet
  225. .mint(&mint_quote.id, SplitTarget::default(), None)
  226. .await
  227. .expect("Could not mint");
  228. let mint_amount = proofs.total_amount().unwrap();
  229. assert_eq!(mint_amount, 100.into());
  230. let invoice = lnd_client
  231. .create_invoice(Some(10))
  232. .await
  233. .expect("Could not create invoice");
  234. let melt_quote = wallet
  235. .melt_quote(invoice.clone(), None)
  236. .await
  237. .expect("Could not get melt quote");
  238. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  239. let melt_two = wallet.melt_quote(invoice, None).await.unwrap();
  240. let melt_two = wallet.melt(&melt_two.id).await;
  241. match melt_two {
  242. Err(err) => match err {
  243. cdk::Error::RequestAlreadyPaid => (),
  244. err => {
  245. bail!("Wrong invoice already paid: {}", err.to_string());
  246. }
  247. },
  248. Ok(_) => {
  249. bail!("Should not have allowed second payment");
  250. }
  251. }
  252. let balance = wallet.total_balance().await.unwrap();
  253. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  254. Ok(())
  255. }
  256. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  257. async fn test_internal_payment() -> Result<()> {
  258. let lnd_client = init_lnd_client().await;
  259. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  260. let wallet = Wallet::new(
  261. &get_mint_url("0"),
  262. CurrencyUnit::Sat,
  263. Arc::new(memory::empty().await?),
  264. &seed,
  265. None,
  266. )?;
  267. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  268. lnd_client.pay_invoice(mint_quote.request).await?;
  269. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  270. let _mint_amount = wallet
  271. .mint(&mint_quote.id, SplitTarget::default(), None)
  272. .await?;
  273. assert!(wallet.total_balance().await? == 100.into());
  274. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  275. let wallet_2 = Wallet::new(
  276. &get_mint_url("0"),
  277. CurrencyUnit::Sat,
  278. Arc::new(memory::empty().await?),
  279. &seed,
  280. None,
  281. )?;
  282. let mint_quote = wallet_2.mint_quote(10.into(), None).await?;
  283. let melt = wallet.melt_quote(mint_quote.request.clone(), None).await?;
  284. assert_eq!(melt.amount, 10.into());
  285. let _melted = wallet.melt(&melt.id).await.unwrap();
  286. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  287. let _wallet_2_mint = wallet_2
  288. .mint(&mint_quote.id, SplitTarget::default(), None)
  289. .await
  290. .unwrap();
  291. let check_paid = match get_mint_port("0") {
  292. 8085 => {
  293. let cln_one_dir = get_cln_dir("one");
  294. let cln_client = ClnClient::new(cln_one_dir.clone(), None).await?;
  295. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  296. cln_client
  297. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  298. .await
  299. .expect("Could not check invoice")
  300. }
  301. 8087 => {
  302. let lnd_two_dir = get_lnd_dir("two");
  303. let lnd_client = LndClient::new(
  304. format!("https://{}", LND_TWO_RPC_ADDR),
  305. get_lnd_cert_file_path(&lnd_two_dir),
  306. get_lnd_macaroon_path(&lnd_two_dir),
  307. )
  308. .await?;
  309. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  310. lnd_client
  311. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  312. .await
  313. .expect("Could not check invoice")
  314. }
  315. _ => panic!("Unknown mint port"),
  316. };
  317. match check_paid {
  318. InvoiceStatus::Unpaid => (),
  319. _ => {
  320. bail!("Invoice has incorrect status: {:?}", check_paid);
  321. }
  322. }
  323. let wallet_2_balance = wallet_2.total_balance().await?;
  324. assert!(wallet_2_balance == 10.into());
  325. let wallet_1_balance = wallet.total_balance().await?;
  326. assert!(wallet_1_balance == 90.into());
  327. Ok(())
  328. }
  329. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  330. async fn test_cached_mint() -> Result<()> {
  331. let lnd_client = init_lnd_client().await;
  332. let wallet = Wallet::new(
  333. &get_mint_url("0"),
  334. CurrencyUnit::Sat,
  335. Arc::new(memory::empty().await?),
  336. &Mnemonic::generate(12)?.to_seed_normalized(""),
  337. None,
  338. )?;
  339. let mint_amount = Amount::from(100);
  340. let quote = wallet.mint_quote(mint_amount, None).await?;
  341. lnd_client.pay_invoice(quote.request).await?;
  342. wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
  343. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  344. let http_client = HttpClient::new(get_mint_url("0").as_str().parse()?, None);
  345. let premint_secrets =
  346. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  347. let mut request = MintBolt11Request {
  348. quote: quote.id,
  349. outputs: premint_secrets.blinded_messages(),
  350. signature: None,
  351. };
  352. let secret_key = quote.secret_key;
  353. request.sign(secret_key.expect("Secret key on quote"))?;
  354. let response = http_client.post_mint(request.clone()).await?;
  355. let response1 = http_client.post_mint(request).await?;
  356. assert!(response == response1);
  357. Ok(())
  358. }
  359. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  360. async fn test_websocket_connection() -> Result<()> {
  361. let wallet = Wallet::new(
  362. &get_mint_url("0"),
  363. CurrencyUnit::Sat,
  364. Arc::new(wallet::memory::empty().await?),
  365. &Mnemonic::generate(12)?.to_seed_normalized(""),
  366. None,
  367. )?;
  368. // Create a small mint quote to test notifications
  369. let mint_quote = wallet.mint_quote(10.into(), None).await?;
  370. // Subscribe to notifications for this quote
  371. let mut subscription = wallet
  372. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![mint_quote
  373. .id
  374. .clone()]))
  375. .await;
  376. // First check we get the unpaid state
  377. let msg = timeout(Duration::from_secs(10), subscription.recv())
  378. .await
  379. .expect("timeout waiting for unpaid notification")
  380. .ok_or_else(|| anyhow::anyhow!("No unpaid notification received"))?;
  381. match msg {
  382. NotificationPayload::MintQuoteBolt11Response(response) => {
  383. assert_eq!(response.quote.to_string(), mint_quote.id);
  384. assert_eq!(response.state, MintQuoteState::Unpaid);
  385. }
  386. _ => bail!("Unexpected notification type"),
  387. }
  388. let lnd_client = init_lnd_client().await;
  389. lnd_client.pay_invoice(mint_quote.request).await?;
  390. // Wait for paid notification with 10 second timeout
  391. let msg = timeout(Duration::from_secs(10), subscription.recv())
  392. .await
  393. .expect("timeout waiting for paid notification")
  394. .ok_or_else(|| anyhow::anyhow!("No paid notification received"))?;
  395. match msg {
  396. NotificationPayload::MintQuoteBolt11Response(response) => {
  397. assert_eq!(response.quote.to_string(), mint_quote.id);
  398. assert_eq!(response.state, MintQuoteState::Paid);
  399. Ok(())
  400. }
  401. _ => bail!("Unexpected notification type"),
  402. }
  403. }
  404. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  405. async fn test_multimint_melt() -> Result<()> {
  406. let lnd_client = init_lnd_client().await;
  407. let wallet1 = Wallet::new(
  408. &get_mint_url("0"),
  409. CurrencyUnit::Sat,
  410. Arc::new(memory::empty().await?),
  411. &Mnemonic::generate(12)?.to_seed_normalized(""),
  412. None,
  413. )?;
  414. let wallet2 = Wallet::new(
  415. &get_mint_url("1"),
  416. CurrencyUnit::Sat,
  417. Arc::new(memory::empty().await?),
  418. &Mnemonic::generate(12)?.to_seed_normalized(""),
  419. None,
  420. )?;
  421. let mint_amount = Amount::from(100);
  422. // Fund the wallets
  423. let quote = wallet1.mint_quote(mint_amount, None).await?;
  424. lnd_client.pay_invoice(quote.request.clone()).await?;
  425. wait_for_mint_to_be_paid(&wallet1, &quote.id, 60).await?;
  426. wallet1
  427. .mint(&quote.id, SplitTarget::default(), None)
  428. .await?;
  429. let quote = wallet2.mint_quote(mint_amount, None).await?;
  430. lnd_client.pay_invoice(quote.request.clone()).await?;
  431. wait_for_mint_to_be_paid(&wallet2, &quote.id, 60).await?;
  432. wallet2
  433. .mint(&quote.id, SplitTarget::default(), None)
  434. .await?;
  435. // Get an invoice
  436. let invoice = lnd_client.create_invoice(Some(50)).await?;
  437. // Get multi-part melt quotes
  438. let melt_options = MeltOptions::Mpp {
  439. mpp: Mpp {
  440. amount: Amount::from(25000),
  441. },
  442. };
  443. let quote_1 = wallet1
  444. .melt_quote(invoice.clone(), Some(melt_options))
  445. .await
  446. .expect("Could not get melt quote");
  447. let quote_2 = wallet2
  448. .melt_quote(invoice.clone(), Some(melt_options))
  449. .await
  450. .expect("Could not get melt quote");
  451. // Multimint pay invoice
  452. let result1 = wallet1.melt(&quote_1.id);
  453. let result2 = wallet2.melt(&quote_2.id);
  454. let result = join!(result1, result2);
  455. // Unpack results
  456. let result1 = result.0.unwrap();
  457. let result2 = result.1.unwrap();
  458. // Check
  459. assert!(result1.state == result2.state);
  460. assert!(result1.state == MeltQuoteState::Paid);
  461. Ok(())
  462. }
  463. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  464. async fn test_database_type() -> Result<()> {
  465. // Get the database type and work dir from environment
  466. let db_type = std::env::var("MINT_DATABASE").expect("MINT_DATABASE env var should be set");
  467. let work_dir =
  468. std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
  469. // Check that the correct database file exists
  470. match db_type.as_str() {
  471. "REDB" => {
  472. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.redb");
  473. assert!(
  474. db_path.exists(),
  475. "Expected redb database file to exist at {:?}",
  476. db_path
  477. );
  478. }
  479. "SQLITE" => {
  480. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.sqlite");
  481. assert!(
  482. db_path.exists(),
  483. "Expected sqlite database file to exist at {:?}",
  484. db_path
  485. );
  486. }
  487. "MEMORY" => {
  488. // Memory database has no file to check
  489. println!("Memory database in use - no file to check");
  490. }
  491. _ => bail!("Unknown database type: {}", db_type),
  492. }
  493. Ok(())
  494. }