fake_wallet.rs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. use std::sync::Arc;
  2. use anyhow::{bail, Result};
  3. use bip39::Mnemonic;
  4. use cdk::amount::SplitTarget;
  5. use cdk::nuts::nut00::ProofsMethods;
  6. use cdk::nuts::{
  7. CurrencyUnit, MeltBolt11Request, MeltQuoteState, MintBolt11Request, PreMintSecrets, Proofs,
  8. SecretKey, State, SwapRequest,
  9. };
  10. use cdk::wallet::{HttpClient, MintConnector, Wallet};
  11. use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};
  12. use cdk_integration_tests::{attempt_to_swap_pending, wait_for_mint_to_be_paid};
  13. use cdk_sqlite::wallet::memory;
  14. const MINT_URL: &str = "http://127.0.0.1:8086";
  15. /// Tests that when both pay and check return pending status, input proofs should remain pending
  16. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  17. async fn test_fake_tokens_pending() -> Result<()> {
  18. let wallet = Wallet::new(
  19. MINT_URL,
  20. CurrencyUnit::Sat,
  21. Arc::new(memory::empty().await?),
  22. &Mnemonic::generate(12)?.to_seed_normalized(""),
  23. None,
  24. )?;
  25. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  26. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  27. let _mint_amount = wallet
  28. .mint(&mint_quote.id, SplitTarget::default(), None)
  29. .await?;
  30. let fake_description = FakeInvoiceDescription {
  31. pay_invoice_state: MeltQuoteState::Pending,
  32. check_payment_state: MeltQuoteState::Pending,
  33. pay_err: false,
  34. check_err: false,
  35. };
  36. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  37. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  38. let melt = wallet.melt(&melt_quote.id).await;
  39. assert!(melt.is_err());
  40. attempt_to_swap_pending(&wallet).await?;
  41. Ok(())
  42. }
  43. /// Tests that if the pay error fails and the check returns unknown or failed,
  44. /// the input proofs should be unset as spending (returned to unspent state)
  45. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  46. async fn test_fake_melt_payment_fail() -> Result<()> {
  47. let wallet = Wallet::new(
  48. MINT_URL,
  49. CurrencyUnit::Sat,
  50. Arc::new(memory::empty().await?),
  51. &Mnemonic::generate(12)?.to_seed_normalized(""),
  52. None,
  53. )?;
  54. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  55. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  56. let _mint_amount = wallet
  57. .mint(&mint_quote.id, SplitTarget::default(), None)
  58. .await?;
  59. let fake_description = FakeInvoiceDescription {
  60. pay_invoice_state: MeltQuoteState::Unknown,
  61. check_payment_state: MeltQuoteState::Unknown,
  62. pay_err: true,
  63. check_err: false,
  64. };
  65. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  66. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  67. // The melt should error at the payment invoice command
  68. let melt = wallet.melt(&melt_quote.id).await;
  69. assert!(melt.is_err());
  70. let fake_description = FakeInvoiceDescription {
  71. pay_invoice_state: MeltQuoteState::Failed,
  72. check_payment_state: MeltQuoteState::Failed,
  73. pay_err: true,
  74. check_err: false,
  75. };
  76. let invoice = create_fake_invoice(1000, serde_json::to_string(&fake_description).unwrap());
  77. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  78. // The melt should error at the payment invoice command
  79. let melt = wallet.melt(&melt_quote.id).await;
  80. assert!(melt.is_err());
  81. // The mint should have unset proofs from pending since payment failed
  82. let all_proof = wallet.get_unspent_proofs().await?;
  83. let states = wallet.check_proofs_spent(all_proof).await?;
  84. for state in states {
  85. assert!(state.state == State::Unspent);
  86. }
  87. let wallet_bal = wallet.total_balance().await?;
  88. assert_eq!(wallet_bal, 100.into());
  89. Ok(())
  90. }
  91. /// Tests that when both the pay_invoice and check_invoice both fail,
  92. /// the proofs should remain in pending state
  93. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  94. async fn test_fake_melt_payment_fail_and_check() -> Result<()> {
  95. let wallet = Wallet::new(
  96. MINT_URL,
  97. CurrencyUnit::Sat,
  98. Arc::new(memory::empty().await?),
  99. &Mnemonic::generate(12)?.to_seed_normalized(""),
  100. None,
  101. )?;
  102. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  103. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  104. let _mint_amount = wallet
  105. .mint(&mint_quote.id, SplitTarget::default(), None)
  106. .await?;
  107. let fake_description = FakeInvoiceDescription {
  108. pay_invoice_state: MeltQuoteState::Unknown,
  109. check_payment_state: MeltQuoteState::Unknown,
  110. pay_err: true,
  111. check_err: true,
  112. };
  113. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  114. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  115. // The melt should error at the payment invoice command
  116. let melt = wallet.melt(&melt_quote.id).await;
  117. assert!(melt.is_err());
  118. let pending = wallet
  119. .localstore
  120. .get_proofs(None, None, Some(vec![State::Pending]), None)
  121. .await?;
  122. assert!(!pending.is_empty());
  123. Ok(())
  124. }
  125. /// Tests that when the ln backend returns a failed status but does not error,
  126. /// the mint should do a second check, then remove proofs from pending state
  127. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  128. async fn test_fake_melt_payment_return_fail_status() -> Result<()> {
  129. let wallet = Wallet::new(
  130. MINT_URL,
  131. CurrencyUnit::Sat,
  132. Arc::new(memory::empty().await?),
  133. &Mnemonic::generate(12)?.to_seed_normalized(""),
  134. None,
  135. )?;
  136. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  137. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  138. let _mint_amount = wallet
  139. .mint(&mint_quote.id, SplitTarget::default(), None)
  140. .await?;
  141. let fake_description = FakeInvoiceDescription {
  142. pay_invoice_state: MeltQuoteState::Failed,
  143. check_payment_state: MeltQuoteState::Failed,
  144. pay_err: false,
  145. check_err: false,
  146. };
  147. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  148. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  149. // The melt should error at the payment invoice command
  150. let melt = wallet.melt(&melt_quote.id).await;
  151. assert!(melt.is_err());
  152. let fake_description = FakeInvoiceDescription {
  153. pay_invoice_state: MeltQuoteState::Unknown,
  154. check_payment_state: MeltQuoteState::Unknown,
  155. pay_err: false,
  156. check_err: false,
  157. };
  158. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  159. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  160. // The melt should error at the payment invoice command
  161. let melt = wallet.melt(&melt_quote.id).await;
  162. assert!(melt.is_err());
  163. let pending = wallet
  164. .localstore
  165. .get_proofs(None, None, Some(vec![State::Pending]), None)
  166. .await?;
  167. assert!(pending.is_empty());
  168. Ok(())
  169. }
  170. /// Tests that when the ln backend returns an error with unknown status,
  171. /// the mint should do a second check, then remove proofs from pending state
  172. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  173. async fn test_fake_melt_payment_error_unknown() -> Result<()> {
  174. let wallet = Wallet::new(
  175. MINT_URL,
  176. CurrencyUnit::Sat,
  177. Arc::new(memory::empty().await?),
  178. &Mnemonic::generate(12)?.to_seed_normalized(""),
  179. None,
  180. )?;
  181. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  182. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  183. let _mint_amount = wallet
  184. .mint(&mint_quote.id, SplitTarget::default(), None)
  185. .await?;
  186. let fake_description = FakeInvoiceDescription {
  187. pay_invoice_state: MeltQuoteState::Failed,
  188. check_payment_state: MeltQuoteState::Unknown,
  189. pay_err: true,
  190. check_err: false,
  191. };
  192. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  193. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  194. // The melt should error at the payment invoice command
  195. let melt = wallet.melt(&melt_quote.id).await;
  196. assert_eq!(melt.unwrap_err().to_string(), "Payment failed");
  197. let fake_description = FakeInvoiceDescription {
  198. pay_invoice_state: MeltQuoteState::Unknown,
  199. check_payment_state: MeltQuoteState::Unknown,
  200. pay_err: true,
  201. check_err: false,
  202. };
  203. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  204. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  205. // The melt should error at the payment invoice command
  206. let melt = wallet.melt(&melt_quote.id).await;
  207. assert_eq!(melt.unwrap_err().to_string(), "Payment failed");
  208. let pending = wallet
  209. .localstore
  210. .get_proofs(None, None, Some(vec![State::Pending]), None)
  211. .await?;
  212. assert!(pending.is_empty());
  213. Ok(())
  214. }
  215. /// Tests that when the ln backend returns an error but the second check returns paid,
  216. /// proofs should remain in pending state
  217. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  218. async fn test_fake_melt_payment_err_paid() -> Result<()> {
  219. let wallet = Wallet::new(
  220. MINT_URL,
  221. CurrencyUnit::Sat,
  222. Arc::new(memory::empty().await?),
  223. &Mnemonic::generate(12)?.to_seed_normalized(""),
  224. None,
  225. )?;
  226. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  227. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  228. let _mint_amount = wallet
  229. .mint(&mint_quote.id, SplitTarget::default(), None)
  230. .await?;
  231. let fake_description = FakeInvoiceDescription {
  232. pay_invoice_state: MeltQuoteState::Failed,
  233. check_payment_state: MeltQuoteState::Paid,
  234. pay_err: true,
  235. check_err: false,
  236. };
  237. let invoice = create_fake_invoice(7000, serde_json::to_string(&fake_description).unwrap());
  238. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  239. // The melt should error at the payment invoice command
  240. let melt = wallet.melt(&melt_quote.id).await;
  241. assert!(melt.is_err());
  242. attempt_to_swap_pending(&wallet).await?;
  243. Ok(())
  244. }
  245. /// Tests that change outputs in a melt quote are correctly handled
  246. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  247. async fn test_fake_melt_change_in_quote() -> Result<()> {
  248. let wallet = Wallet::new(
  249. MINT_URL,
  250. CurrencyUnit::Sat,
  251. Arc::new(memory::empty().await?),
  252. &Mnemonic::generate(12)?.to_seed_normalized(""),
  253. None,
  254. )?;
  255. let mint_quote = wallet.mint_quote(100.into(), None).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. let fake_description = FakeInvoiceDescription::default();
  261. let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
  262. let proofs = wallet.get_unspent_proofs().await?;
  263. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  264. let keyset = wallet.get_active_mint_keyset().await?;
  265. let premint_secrets = PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default())?;
  266. let client = HttpClient::new(MINT_URL.parse()?, None);
  267. let melt_request = MeltBolt11Request::new(
  268. melt_quote.id.clone(),
  269. proofs.clone(),
  270. Some(premint_secrets.blinded_messages()),
  271. );
  272. let melt_response = client.post_melt(melt_request).await?;
  273. assert!(melt_response.change.is_some());
  274. let check = wallet.melt_quote_status(&melt_quote.id).await?;
  275. let mut melt_change = melt_response.change.unwrap();
  276. melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
  277. let mut check = check.change.unwrap();
  278. check.sort_by(|a, b| a.amount.cmp(&b.amount));
  279. assert_eq!(melt_change, check);
  280. Ok(())
  281. }
  282. /// Tests that the correct database type is used based on environment variables
  283. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  284. async fn test_database_type() -> Result<()> {
  285. // Get the database type and work dir from environment
  286. let db_type = std::env::var("MINT_DATABASE").expect("MINT_DATABASE env var should be set");
  287. let work_dir =
  288. std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
  289. // Check that the correct database file exists
  290. match db_type.as_str() {
  291. "REDB" => {
  292. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.redb");
  293. assert!(
  294. db_path.exists(),
  295. "Expected redb database file to exist at {:?}",
  296. db_path
  297. );
  298. }
  299. "SQLITE" => {
  300. let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.sqlite");
  301. assert!(
  302. db_path.exists(),
  303. "Expected sqlite database file to exist at {:?}",
  304. db_path
  305. );
  306. }
  307. "MEMORY" => {
  308. // Memory database has no file to check
  309. println!("Memory database in use - no file to check");
  310. }
  311. _ => bail!("Unknown database type: {}", db_type),
  312. }
  313. Ok(())
  314. }
  315. /// Tests minting tokens with a valid witness signature
  316. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  317. async fn test_fake_mint_with_witness() -> Result<()> {
  318. let wallet = Wallet::new(
  319. MINT_URL,
  320. CurrencyUnit::Sat,
  321. Arc::new(memory::empty().await?),
  322. &Mnemonic::generate(12)?.to_seed_normalized(""),
  323. None,
  324. )?;
  325. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  326. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  327. let proofs = wallet
  328. .mint(&mint_quote.id, SplitTarget::default(), None)
  329. .await?;
  330. let mint_amount = proofs.total_amount()?;
  331. assert!(mint_amount == 100.into());
  332. Ok(())
  333. }
  334. /// Tests that minting without a witness signature fails with the correct error
  335. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  336. async fn test_fake_mint_without_witness() -> Result<()> {
  337. let wallet = Wallet::new(
  338. MINT_URL,
  339. CurrencyUnit::Sat,
  340. Arc::new(memory::empty().await?),
  341. &Mnemonic::generate(12)?.to_seed_normalized(""),
  342. None,
  343. )?;
  344. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  345. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  346. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  347. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  348. let premint_secrets =
  349. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  350. let request = MintBolt11Request {
  351. quote: mint_quote.id,
  352. outputs: premint_secrets.blinded_messages(),
  353. signature: None,
  354. };
  355. let response = http_client.post_mint(request.clone()).await;
  356. match response {
  357. Err(cdk::error::Error::SignatureMissingOrInvalid) => Ok(()),
  358. Err(err) => bail!("Wrong mint response for minting without witness: {}", err),
  359. Ok(_) => bail!("Minting should not have succeed without a witness"),
  360. }
  361. }
  362. /// Tests that minting with an incorrect witness signature fails with the correct error
  363. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  364. async fn test_fake_mint_with_wrong_witness() -> Result<()> {
  365. let wallet = Wallet::new(
  366. MINT_URL,
  367. CurrencyUnit::Sat,
  368. Arc::new(memory::empty().await?),
  369. &Mnemonic::generate(12)?.to_seed_normalized(""),
  370. None,
  371. )?;
  372. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  373. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  374. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  375. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  376. let premint_secrets =
  377. PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
  378. let mut request = MintBolt11Request {
  379. quote: mint_quote.id,
  380. outputs: premint_secrets.blinded_messages(),
  381. signature: None,
  382. };
  383. let secret_key = SecretKey::generate();
  384. request.sign(secret_key)?;
  385. let response = http_client.post_mint(request.clone()).await;
  386. match response {
  387. Err(cdk::error::Error::SignatureMissingOrInvalid) => Ok(()),
  388. Err(err) => bail!("Wrong mint response for minting without witness: {}", err),
  389. Ok(_) => bail!("Minting should not have succeed without a witness"),
  390. }
  391. }
  392. /// Tests that attempting to mint more tokens than allowed by the quote fails
  393. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  394. async fn test_fake_mint_inflated() -> Result<()> {
  395. let wallet = Wallet::new(
  396. MINT_URL,
  397. CurrencyUnit::Sat,
  398. Arc::new(memory::empty().await?),
  399. &Mnemonic::generate(12)?.to_seed_normalized(""),
  400. None,
  401. )?;
  402. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  403. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  404. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  405. let pre_mint = PreMintSecrets::random(active_keyset_id, 500.into(), &SplitTarget::None)?;
  406. let quote_info = wallet
  407. .localstore
  408. .get_mint_quote(&mint_quote.id)
  409. .await?
  410. .expect("there is a quote");
  411. let mut mint_request = MintBolt11Request {
  412. quote: mint_quote.id,
  413. outputs: pre_mint.blinded_messages(),
  414. signature: None,
  415. };
  416. if let Some(secret_key) = quote_info.secret_key {
  417. mint_request.sign(secret_key)?;
  418. }
  419. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  420. let response = http_client.post_mint(mint_request.clone()).await;
  421. match response {
  422. Err(err) => match err {
  423. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  424. err => {
  425. bail!("Wrong mint error returned: {}", err.to_string());
  426. }
  427. },
  428. Ok(_) => {
  429. bail!("Should not have allowed second payment");
  430. }
  431. }
  432. Ok(())
  433. }
  434. /// Tests that attempting to mint with multiple currency units in the same request fails
  435. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  436. async fn test_fake_mint_multiple_units() -> Result<()> {
  437. let wallet = Wallet::new(
  438. MINT_URL,
  439. CurrencyUnit::Sat,
  440. Arc::new(memory::empty().await?),
  441. &Mnemonic::generate(12)?.to_seed_normalized(""),
  442. None,
  443. )?;
  444. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  445. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  446. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  447. let pre_mint = PreMintSecrets::random(active_keyset_id, 50.into(), &SplitTarget::None)?;
  448. let wallet_usd = Wallet::new(
  449. MINT_URL,
  450. CurrencyUnit::Usd,
  451. Arc::new(memory::empty().await?),
  452. &Mnemonic::generate(12)?.to_seed_normalized(""),
  453. None,
  454. )?;
  455. let active_keyset_id = wallet_usd.get_active_mint_keyset().await?.id;
  456. let usd_pre_mint = PreMintSecrets::random(active_keyset_id, 50.into(), &SplitTarget::None)?;
  457. let quote_info = wallet
  458. .localstore
  459. .get_mint_quote(&mint_quote.id)
  460. .await?
  461. .expect("there is a quote");
  462. let mut sat_outputs = pre_mint.blinded_messages();
  463. let mut usd_outputs = usd_pre_mint.blinded_messages();
  464. sat_outputs.append(&mut usd_outputs);
  465. let mut mint_request = MintBolt11Request {
  466. quote: mint_quote.id,
  467. outputs: sat_outputs,
  468. signature: None,
  469. };
  470. if let Some(secret_key) = quote_info.secret_key {
  471. mint_request.sign(secret_key)?;
  472. }
  473. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  474. let response = http_client.post_mint(mint_request.clone()).await;
  475. match response {
  476. Err(err) => match err {
  477. cdk::Error::MultipleUnits => (),
  478. err => {
  479. bail!("Wrong mint error returned: {}", err.to_string());
  480. }
  481. },
  482. Ok(_) => {
  483. bail!("Should not have allowed to mint with multiple units");
  484. }
  485. }
  486. Ok(())
  487. }
  488. /// Tests that attempting to swap tokens with multiple currency units fails
  489. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  490. async fn test_fake_mint_multiple_unit_swap() -> Result<()> {
  491. let wallet = Wallet::new(
  492. MINT_URL,
  493. CurrencyUnit::Sat,
  494. Arc::new(memory::empty().await?),
  495. &Mnemonic::generate(12)?.to_seed_normalized(""),
  496. None,
  497. )?;
  498. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  499. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  500. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  501. let wallet_usd = Wallet::new(
  502. MINT_URL,
  503. CurrencyUnit::Usd,
  504. Arc::new(memory::empty().await?),
  505. &Mnemonic::generate(12)?.to_seed_normalized(""),
  506. None,
  507. )?;
  508. let mint_quote = wallet_usd.mint_quote(100.into(), None).await?;
  509. wait_for_mint_to_be_paid(&wallet_usd, &mint_quote.id, 60).await?;
  510. let usd_proofs = wallet_usd
  511. .mint(&mint_quote.id, SplitTarget::None, None)
  512. .await?;
  513. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  514. {
  515. let inputs: Proofs = vec![
  516. proofs.first().expect("There is a proof").clone(),
  517. usd_proofs.first().expect("There is a proof").clone(),
  518. ];
  519. let pre_mint =
  520. PreMintSecrets::random(active_keyset_id, inputs.total_amount()?, &SplitTarget::None)?;
  521. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  522. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  523. let response = http_client.post_swap(swap_request.clone()).await;
  524. match response {
  525. Err(err) => match err {
  526. cdk::Error::MultipleUnits => (),
  527. err => {
  528. bail!("Wrong mint error returned: {}", err.to_string());
  529. }
  530. },
  531. Ok(_) => {
  532. bail!("Should not have allowed to mint with multiple units");
  533. }
  534. }
  535. }
  536. {
  537. let usd_active_keyset_id = wallet_usd.get_active_mint_keyset().await?.id;
  538. let inputs: Proofs = proofs.into_iter().take(2).collect();
  539. let total_inputs = inputs.total_amount()?;
  540. let half = total_inputs / 2.into();
  541. let usd_pre_mint = PreMintSecrets::random(usd_active_keyset_id, half, &SplitTarget::None)?;
  542. let pre_mint =
  543. PreMintSecrets::random(active_keyset_id, total_inputs - half, &SplitTarget::None)?;
  544. let mut usd_outputs = usd_pre_mint.blinded_messages();
  545. let mut sat_outputs = pre_mint.blinded_messages();
  546. usd_outputs.append(&mut sat_outputs);
  547. let swap_request = SwapRequest::new(inputs, usd_outputs);
  548. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  549. let response = http_client.post_swap(swap_request.clone()).await;
  550. match response {
  551. Err(err) => match err {
  552. cdk::Error::MultipleUnits => (),
  553. err => {
  554. bail!("Wrong mint error returned: {}", err.to_string());
  555. }
  556. },
  557. Ok(_) => {
  558. bail!("Should not have allowed to mint with multiple units");
  559. }
  560. }
  561. }
  562. Ok(())
  563. }
  564. /// Tests that attempting to melt tokens with multiple currency units fails
  565. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  566. async fn test_fake_mint_multiple_unit_melt() -> Result<()> {
  567. let wallet = Wallet::new(
  568. MINT_URL,
  569. CurrencyUnit::Sat,
  570. Arc::new(memory::empty().await?),
  571. &Mnemonic::generate(12)?.to_seed_normalized(""),
  572. None,
  573. )?;
  574. let mint_quote = wallet.mint_quote(100.into(), None).await.unwrap();
  575. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  576. let proofs = wallet
  577. .mint(&mint_quote.id, SplitTarget::None, None)
  578. .await
  579. .unwrap();
  580. println!("Minted sat");
  581. let wallet_usd = Wallet::new(
  582. MINT_URL,
  583. CurrencyUnit::Usd,
  584. Arc::new(memory::empty().await?),
  585. &Mnemonic::generate(12)?.to_seed_normalized(""),
  586. None,
  587. )?;
  588. let mint_quote = wallet_usd.mint_quote(100.into(), None).await.unwrap();
  589. println!("Minted quote usd");
  590. wait_for_mint_to_be_paid(&wallet_usd, &mint_quote.id, 60).await?;
  591. let usd_proofs = wallet_usd
  592. .mint(&mint_quote.id, SplitTarget::None, None)
  593. .await
  594. .unwrap();
  595. {
  596. let inputs: Proofs = vec![
  597. proofs.first().expect("There is a proof").clone(),
  598. usd_proofs.first().expect("There is a proof").clone(),
  599. ];
  600. let input_amount: u64 = inputs.total_amount()?.into();
  601. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  602. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  603. let melt_request = MeltBolt11Request::new(melt_quote.id, inputs, None);
  604. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  605. let response = http_client.post_melt(melt_request.clone()).await;
  606. match response {
  607. Err(err) => match err {
  608. cdk::Error::MultipleUnits => (),
  609. err => {
  610. bail!("Wrong mint error returned: {}", err.to_string());
  611. }
  612. },
  613. Ok(_) => {
  614. bail!("Should not have allowed to melt with multiple units");
  615. }
  616. }
  617. }
  618. {
  619. let inputs: Proofs = vec![proofs.first().expect("There is a proof").clone()];
  620. let input_amount: u64 = inputs.total_amount()?.into();
  621. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  622. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  623. let usd_active_keyset_id = wallet_usd.get_active_mint_keyset().await?.id;
  624. let usd_pre_mint = PreMintSecrets::random(
  625. usd_active_keyset_id,
  626. inputs.total_amount()? + 100.into(),
  627. &SplitTarget::None,
  628. )?;
  629. let pre_mint = PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::None)?;
  630. let mut usd_outputs = usd_pre_mint.blinded_messages();
  631. let mut sat_outputs = pre_mint.blinded_messages();
  632. usd_outputs.append(&mut sat_outputs);
  633. let quote = wallet.melt_quote(invoice.to_string(), None).await?;
  634. let melt_request = MeltBolt11Request::new(quote.id, inputs, Some(usd_outputs));
  635. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  636. let response = http_client.post_melt(melt_request.clone()).await;
  637. match response {
  638. Err(err) => match err {
  639. cdk::Error::MultipleUnits => (),
  640. err => {
  641. bail!("Wrong mint error returned: {}", err.to_string());
  642. }
  643. },
  644. Ok(_) => {
  645. bail!("Should not have allowed to melt with multiple units");
  646. }
  647. }
  648. }
  649. Ok(())
  650. }
  651. /// Tests that swapping tokens where input unit doesn't match output unit fails
  652. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  653. async fn test_fake_mint_input_output_mismatch() -> Result<()> {
  654. let wallet = Wallet::new(
  655. MINT_URL,
  656. CurrencyUnit::Sat,
  657. Arc::new(memory::empty().await?),
  658. &Mnemonic::generate(12)?.to_seed_normalized(""),
  659. None,
  660. )?;
  661. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  662. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  663. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  664. let wallet_usd = Wallet::new(
  665. MINT_URL,
  666. CurrencyUnit::Usd,
  667. Arc::new(memory::empty().await?),
  668. &Mnemonic::generate(12)?.to_seed_normalized(""),
  669. None,
  670. )?;
  671. let usd_active_keyset_id = wallet_usd.get_active_mint_keyset().await?.id;
  672. let inputs = proofs;
  673. let pre_mint = PreMintSecrets::random(
  674. usd_active_keyset_id,
  675. inputs.total_amount()?,
  676. &SplitTarget::None,
  677. )?;
  678. let swap_request = SwapRequest::new(inputs, pre_mint.blinded_messages());
  679. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  680. let response = http_client.post_swap(swap_request.clone()).await;
  681. match response {
  682. Err(err) => match err {
  683. cdk::Error::UnitMismatch => (),
  684. err => bail!("Wrong error returned: {}", err),
  685. },
  686. Ok(_) => {
  687. bail!("Should not have allowed to mint with multiple units");
  688. }
  689. }
  690. Ok(())
  691. }
  692. /// Tests that swapping tokens where output amount is greater than input amount fails
  693. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  694. async fn test_fake_mint_swap_inflated() -> Result<()> {
  695. let wallet = Wallet::new(
  696. MINT_URL,
  697. CurrencyUnit::Sat,
  698. Arc::new(memory::empty().await?),
  699. &Mnemonic::generate(12)?.to_seed_normalized(""),
  700. None,
  701. )?;
  702. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  703. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  704. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  705. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  706. let pre_mint = PreMintSecrets::random(active_keyset_id, 101.into(), &SplitTarget::None)?;
  707. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  708. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  709. let response = http_client.post_swap(swap_request.clone()).await;
  710. match response {
  711. Err(err) => match err {
  712. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  713. err => {
  714. bail!("Wrong mint error returned: {}", err.to_string());
  715. }
  716. },
  717. Ok(_) => {
  718. bail!("Should not have allowed to mint with multiple units");
  719. }
  720. }
  721. Ok(())
  722. }
  723. /// Tests that tokens cannot be spent again after a failed swap attempt
  724. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  725. async fn test_fake_mint_swap_spend_after_fail() -> Result<()> {
  726. let wallet = Wallet::new(
  727. MINT_URL,
  728. CurrencyUnit::Sat,
  729. Arc::new(memory::empty().await?),
  730. &Mnemonic::generate(12)?.to_seed_normalized(""),
  731. None,
  732. )?;
  733. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  734. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  735. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  736. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  737. let pre_mint = PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::None)?;
  738. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  739. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  740. let response = http_client.post_swap(swap_request.clone()).await;
  741. assert!(response.is_ok());
  742. let pre_mint = PreMintSecrets::random(active_keyset_id, 101.into(), &SplitTarget::None)?;
  743. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  744. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  745. let response = http_client.post_swap(swap_request.clone()).await;
  746. match response {
  747. Err(err) => match err {
  748. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  749. err => bail!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  750. },
  751. Ok(_) => bail!("Should not have allowed swap with unbalanced"),
  752. }
  753. let pre_mint = PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::None)?;
  754. let swap_request = SwapRequest::new(proofs, pre_mint.blinded_messages());
  755. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  756. let response = http_client.post_swap(swap_request.clone()).await;
  757. match response {
  758. Err(err) => match err {
  759. cdk::Error::TokenAlreadySpent => (),
  760. err => {
  761. bail!("Wrong mint error returned: {}", err.to_string());
  762. }
  763. },
  764. Ok(_) => {
  765. bail!("Should not have allowed to mint with multiple units");
  766. }
  767. }
  768. Ok(())
  769. }
  770. /// Tests that tokens cannot be melted after a failed swap attempt
  771. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  772. async fn test_fake_mint_melt_spend_after_fail() -> Result<()> {
  773. let wallet = Wallet::new(
  774. MINT_URL,
  775. CurrencyUnit::Sat,
  776. Arc::new(memory::empty().await?),
  777. &Mnemonic::generate(12)?.to_seed_normalized(""),
  778. None,
  779. )?;
  780. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  781. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  782. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  783. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  784. let pre_mint = PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::None)?;
  785. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  786. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  787. let response = http_client.post_swap(swap_request.clone()).await;
  788. assert!(response.is_ok());
  789. let pre_mint = PreMintSecrets::random(active_keyset_id, 101.into(), &SplitTarget::None)?;
  790. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  791. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  792. let response = http_client.post_swap(swap_request.clone()).await;
  793. match response {
  794. Err(err) => match err {
  795. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  796. err => bail!("Wrong mint error returned expected TransactionUnbalanced, got: {err}"),
  797. },
  798. Ok(_) => bail!("Should not have allowed swap with unbalanced"),
  799. }
  800. let input_amount: u64 = proofs.total_amount()?.into();
  801. let invoice = create_fake_invoice((input_amount - 1) * 1000, "".to_string());
  802. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  803. let melt_request = MeltBolt11Request::new(melt_quote.id, proofs, None);
  804. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  805. let response = http_client.post_melt(melt_request.clone()).await;
  806. match response {
  807. Err(err) => match err {
  808. cdk::Error::TokenAlreadySpent => (),
  809. err => {
  810. bail!("Wrong mint error returned: {}", err.to_string());
  811. }
  812. },
  813. Ok(_) => {
  814. bail!("Should not have allowed to melt with multiple units");
  815. }
  816. }
  817. Ok(())
  818. }
  819. /// Tests that attempting to swap with duplicate proofs fails
  820. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  821. async fn test_fake_mint_duplicate_proofs_swap() -> Result<()> {
  822. let wallet = Wallet::new(
  823. MINT_URL,
  824. CurrencyUnit::Sat,
  825. Arc::new(memory::empty().await?),
  826. &Mnemonic::generate(12)?.to_seed_normalized(""),
  827. None,
  828. )?;
  829. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  830. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  831. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  832. let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
  833. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  834. let pre_mint =
  835. PreMintSecrets::random(active_keyset_id, inputs.total_amount()?, &SplitTarget::None)?;
  836. let swap_request = SwapRequest::new(inputs.clone(), pre_mint.blinded_messages());
  837. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  838. let response = http_client.post_swap(swap_request.clone()).await;
  839. match response {
  840. Err(err) => match err {
  841. cdk::Error::DuplicateInputs => (),
  842. err => {
  843. bail!(
  844. "Wrong mint error returned, expected duplicate inputs: {}",
  845. err.to_string()
  846. );
  847. }
  848. },
  849. Ok(_) => {
  850. bail!("Should not have allowed duplicate inputs");
  851. }
  852. }
  853. let blinded_message = pre_mint.blinded_messages();
  854. let outputs = vec![blinded_message[0].clone(), blinded_message[0].clone()];
  855. let swap_request = SwapRequest::new(inputs, outputs);
  856. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  857. let response = http_client.post_swap(swap_request.clone()).await;
  858. match response {
  859. Err(err) => match err {
  860. cdk::Error::DuplicateOutputs => (),
  861. err => {
  862. bail!(
  863. "Wrong mint error returned, expected duplicate outputs: {}",
  864. err.to_string()
  865. );
  866. }
  867. },
  868. Ok(_) => {
  869. bail!("Should not have allow duplicate inputs");
  870. }
  871. }
  872. Ok(())
  873. }
  874. /// Tests that attempting to melt with duplicate proofs fails
  875. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  876. async fn test_fake_mint_duplicate_proofs_melt() -> Result<()> {
  877. let wallet = Wallet::new(
  878. MINT_URL,
  879. CurrencyUnit::Sat,
  880. Arc::new(memory::empty().await?),
  881. &Mnemonic::generate(12)?.to_seed_normalized(""),
  882. None,
  883. )?;
  884. let mint_quote = wallet.mint_quote(100.into(), None).await?;
  885. wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
  886. let proofs = wallet.mint(&mint_quote.id, SplitTarget::None, None).await?;
  887. let inputs = vec![proofs[0].clone(), proofs[0].clone()];
  888. let invoice = create_fake_invoice(7000, "".to_string());
  889. let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
  890. let melt_request = MeltBolt11Request::new(melt_quote.id, inputs, None);
  891. let http_client = HttpClient::new(MINT_URL.parse()?, None);
  892. let response = http_client.post_melt(melt_request.clone()).await;
  893. match response {
  894. Err(err) => match err {
  895. cdk::Error::DuplicateInputs => (),
  896. err => {
  897. bail!("Wrong mint error returned: {}", err.to_string());
  898. }
  899. },
  900. Ok(_) => {
  901. bail!("Should not have allow duplicate inputs");
  902. }
  903. }
  904. Ok(())
  905. }