regtest.rs 18 KB

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