fake_wallet.rs 38 KB

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