regtest.rs 18 KB

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