regtest.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 cdk::amount::{Amount, SplitTarget};
  8. use cdk::cdk_database::WalletMemoryDatabase;
  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, WalletSubscription};
  16. use cdk_integration_tests::init_regtest::{
  17. get_cln_dir, get_lnd_cert_file_path, get_lnd_dir, get_lnd_macaroon_path, get_mint_port,
  18. get_mint_url, get_mint_ws_url, LND_RPC_ADDR, LND_TWO_RPC_ADDR,
  19. };
  20. use cdk_integration_tests::wait_for_mint_to_be_paid;
  21. use futures::{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(),
  74. CurrencyUnit::Sat,
  75. Arc::new(WalletMemoryDatabase::default()),
  76. &Mnemonic::generate(12)?.to_seed_normalized(""),
  77. None,
  78. )?;
  79. let (ws_stream, _) = connect_async(get_mint_ws_url())
  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. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  86. let proofs = wallet
  87. .mint(&mint_quote.id, SplitTarget::default(), None)
  88. .await?;
  89. let mint_amount = proofs.total_amount()?;
  90. assert!(mint_amount == 100.into());
  91. let invoice = lnd_client.create_invoice(Some(50)).await?;
  92. let melt = wallet.melt_quote(invoice, None).await?;
  93. write
  94. .send(Message::Text(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. .await?;
  107. assert_eq!(
  108. reader.next().await.unwrap().unwrap().to_text().unwrap(),
  109. r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#
  110. );
  111. let melt_response = wallet.melt(&melt.id).await.unwrap();
  112. assert!(melt_response.preimage.is_some());
  113. assert!(melt_response.state == MeltQuoteState::Paid);
  114. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  115. // first message is the current state
  116. assert_eq!("test-sub", sub_id);
  117. let payload = match payload {
  118. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  119. _ => panic!("Wrong payload"),
  120. };
  121. assert_eq!(payload.amount + payload.fee_reserve, 100.into());
  122. assert_eq!(payload.quote.to_string(), melt.id);
  123. assert_eq!(payload.state, MeltQuoteState::Unpaid);
  124. // get current state
  125. let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
  126. assert_eq!("test-sub", sub_id);
  127. let payload = match payload {
  128. NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
  129. _ => panic!("Wrong payload"),
  130. };
  131. assert_eq!(payload.amount + payload.fee_reserve, 100.into());
  132. assert_eq!(payload.quote.to_string(), melt.id);
  133. assert_eq!(payload.state, MeltQuoteState::Paid);
  134. Ok(())
  135. }
  136. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  137. async fn test_regtest_mint_melt() -> Result<()> {
  138. let lnd_client = init_lnd_client().await;
  139. let wallet = Wallet::new(
  140. &get_mint_url(),
  141. CurrencyUnit::Sat,
  142. Arc::new(WalletMemoryDatabase::default()),
  143. &Mnemonic::generate(12)?.to_seed_normalized(""),
  144. None,
  145. )?;
  146. let mint_amount = Amount::from(100);
  147. let mint_quote = wallet.mint_quote(mint_amount, None).await?;
  148. assert_eq!(mint_quote.amount, mint_amount);
  149. lnd_client.pay_invoice(mint_quote.request).await?;
  150. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  151. let proofs = wallet
  152. .mint(&mint_quote.id, SplitTarget::default(), None)
  153. .await?;
  154. let mint_amount = proofs.total_amount()?;
  155. assert!(mint_amount == 100.into());
  156. Ok(())
  157. }
  158. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  159. async fn test_restore() -> Result<()> {
  160. let lnd_client = init_lnd_client().await;
  161. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  162. let wallet = Wallet::new(
  163. &get_mint_url(),
  164. CurrencyUnit::Sat,
  165. Arc::new(WalletMemoryDatabase::default()),
  166. &seed,
  167. None,
  168. )?;
  169. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  170. lnd_client.pay_invoice(mint_quote.request).await?;
  171. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  172. let _mint_amount = wallet
  173. .mint(&mint_quote.id, SplitTarget::default(), None)
  174. .await?;
  175. assert!(wallet.total_balance().await? == 100.into());
  176. let wallet_2 = Wallet::new(
  177. &get_mint_url(),
  178. CurrencyUnit::Sat,
  179. Arc::new(WalletMemoryDatabase::default()),
  180. &seed,
  181. None,
  182. )?;
  183. assert!(wallet_2.total_balance().await? == 0.into());
  184. let restored = wallet_2.restore().await?;
  185. let proofs = wallet_2.get_unspent_proofs().await?;
  186. wallet_2
  187. .swap(None, SplitTarget::default(), proofs, None, false)
  188. .await?;
  189. assert!(restored == 100.into());
  190. assert!(wallet_2.total_balance().await? == 100.into());
  191. let proofs = wallet.get_unspent_proofs().await?;
  192. let states = wallet.check_proofs_spent(proofs).await?;
  193. for state in states {
  194. if state.state != State::Spent {
  195. bail!("All proofs should be spent");
  196. }
  197. }
  198. Ok(())
  199. }
  200. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  201. async fn test_pay_invoice_twice() -> Result<()> {
  202. let lnd_client = init_lnd_client().await;
  203. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  204. let wallet = Wallet::new(
  205. &get_mint_url(),
  206. CurrencyUnit::Sat,
  207. Arc::new(WalletMemoryDatabase::default()),
  208. &seed,
  209. None,
  210. )?;
  211. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  212. lnd_client
  213. .pay_invoice(mint_quote.request)
  214. .await
  215. .expect("Could not pay invoice");
  216. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  217. let proofs = wallet
  218. .mint(&mint_quote.id, SplitTarget::default(), None)
  219. .await?;
  220. let mint_amount = proofs.total_amount()?;
  221. assert_eq!(mint_amount, 100.into());
  222. let invoice = lnd_client.create_invoice(Some(10)).await?;
  223. let melt_quote = wallet.melt_quote(invoice.clone(), None).await?;
  224. let melt = wallet.melt(&melt_quote.id).await.unwrap();
  225. let melt_two = wallet.melt_quote(invoice, None).await?;
  226. let melt_two = wallet.melt(&melt_two.id).await;
  227. match melt_two {
  228. Err(err) => match err {
  229. cdk::Error::RequestAlreadyPaid => (),
  230. err => {
  231. bail!("Wrong invoice already paid: {}", err.to_string());
  232. }
  233. },
  234. Ok(_) => {
  235. bail!("Should not have allowed second payment");
  236. }
  237. }
  238. let balance = wallet.total_balance().await?;
  239. assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
  240. Ok(())
  241. }
  242. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  243. async fn test_internal_payment() -> Result<()> {
  244. let lnd_client = init_lnd_client().await;
  245. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  246. let wallet = Wallet::new(
  247. &get_mint_url(),
  248. CurrencyUnit::Sat,
  249. Arc::new(WalletMemoryDatabase::default()),
  250. &seed,
  251. None,
  252. )?;
  253. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  254. lnd_client.pay_invoice(mint_quote.request).await?;
  255. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  256. let _mint_amount = wallet
  257. .mint(&mint_quote.id, SplitTarget::default(), None)
  258. .await?;
  259. assert!(wallet.total_balance().await? == 100.into());
  260. let seed = Mnemonic::generate(12)?.to_seed_normalized("");
  261. let wallet_2 = Wallet::new(
  262. &get_mint_url(),
  263. CurrencyUnit::Sat,
  264. Arc::new(WalletMemoryDatabase::default()),
  265. &seed,
  266. None,
  267. )?;
  268. let mint_quote = wallet_2.mint_quote(10.into(), None).await?;
  269. let melt = wallet.melt_quote(mint_quote.request.clone(), None).await?;
  270. assert_eq!(melt.amount, 10.into());
  271. let _melted = wallet.melt(&melt.id).await.unwrap();
  272. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  273. let _wallet_2_mint = wallet_2
  274. .mint(&mint_quote.id, SplitTarget::default(), None)
  275. .await
  276. .unwrap();
  277. let check_paid = match get_mint_port() {
  278. 8085 => {
  279. let cln_one_dir = get_cln_dir("one");
  280. let cln_client = ClnClient::new(cln_one_dir.clone(), None).await?;
  281. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  282. cln_client
  283. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  284. .await
  285. .expect("Could not check invoice")
  286. }
  287. 8087 => {
  288. let lnd_two_dir = get_lnd_dir("two");
  289. let lnd_client = LndClient::new(
  290. format!("https://{}", LND_TWO_RPC_ADDR),
  291. get_lnd_cert_file_path(&lnd_two_dir),
  292. get_lnd_macaroon_path(&lnd_two_dir),
  293. )
  294. .await?;
  295. let payment_hash = Bolt11Invoice::from_str(&mint_quote.request)?;
  296. lnd_client
  297. .check_incoming_payment_status(&payment_hash.payment_hash().to_string())
  298. .await
  299. .expect("Could not check invoice")
  300. }
  301. _ => panic!("Unknown mint port"),
  302. };
  303. match check_paid {
  304. InvoiceStatus::Unpaid => (),
  305. _ => {
  306. bail!("Invoice has incorrect status: {:?}", check_paid);
  307. }
  308. }
  309. let wallet_2_balance = wallet_2.total_balance().await?;
  310. assert!(wallet_2_balance == 10.into());
  311. let wallet_1_balance = wallet.total_balance().await?;
  312. assert!(wallet_1_balance == 90.into());
  313. Ok(())
  314. }
  315. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  316. async fn test_cached_mint() -> Result<()> {
  317. let lnd_client = init_lnd_client().await;
  318. let wallet = Wallet::new(
  319. &get_mint_url(),
  320. CurrencyUnit::Sat,
  321. Arc::new(WalletMemoryDatabase::default()),
  322. &Mnemonic::generate(12)?.to_seed_normalized(""),
  323. None,
  324. )?;
  325. let mint_amount = Amount::from(100);
  326. let quote = wallet.mint_quote(mint_amount, None).await?;
  327. lnd_client.pay_invoice(quote.request).await?;
  328. let mut subscription = wallet
  329. .subscribe(WalletSubscription::Bolt11MintQuoteState(vec![quote
  330. .id
  331. .clone()]))
  332. .await;
  333. while let Some(msg) = subscription.recv().await {
  334. if let NotificationPayload::MintQuoteBolt11Response(response) = msg {
  335. if response.state == MintQuoteState::Paid {
  336. break;
  337. }
  338. }
  339. }
  340. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  341. let http_client = HttpClient::new(get_mint_url().as_str().parse()?);
  342. let premint_secrets =
  343. PreMintSecrets::random(active_keyset_id, 31.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. }