regtest.rs 18 KB

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