mint.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. //! Mint tests
  2. use anyhow::{bail, Result};
  3. use bip39::Mnemonic;
  4. use cdk::amount::{Amount, SplitTarget};
  5. use cdk::cdk_database::mint_memory::MintMemoryDatabase;
  6. use cdk::dhke::construct_proofs;
  7. use cdk::mint::MintQuote;
  8. use cdk::nuts::nut00::ProofsMethods;
  9. use cdk::nuts::nut17::Params;
  10. use cdk::nuts::{
  11. CurrencyUnit, Id, MintBolt11Request, MintInfo, NotificationPayload, Nuts, PreMintSecrets,
  12. ProofState, Proofs, SecretKey, SpendingConditions, State, SwapRequest,
  13. };
  14. use cdk::types::QuoteTTL;
  15. use cdk::util::unix_time;
  16. use cdk::Mint;
  17. use std::collections::HashMap;
  18. use std::sync::Arc;
  19. use std::time::Duration;
  20. use tokio::sync::OnceCell;
  21. use tokio::time::sleep;
  22. pub const MINT_URL: &str = "http://127.0.0.1:8088";
  23. static INSTANCE: OnceCell<Mint> = OnceCell::const_new();
  24. async fn new_mint(fee: u64) -> Mint {
  25. let mut supported_units = HashMap::new();
  26. supported_units.insert(CurrencyUnit::Sat, (fee, 32));
  27. let nuts = Nuts::new()
  28. .nut07(true)
  29. .nut08(true)
  30. .nut09(true)
  31. .nut10(true)
  32. .nut11(true)
  33. .nut12(true)
  34. .nut14(true);
  35. let mint_info = MintInfo::new().nuts(nuts);
  36. let mnemonic = Mnemonic::generate(12).unwrap();
  37. let quote_ttl = QuoteTTL::new(10000, 10000);
  38. Mint::new(
  39. MINT_URL,
  40. &mnemonic.to_seed_normalized(""),
  41. mint_info,
  42. quote_ttl,
  43. Arc::new(MintMemoryDatabase::default()),
  44. HashMap::new(),
  45. supported_units,
  46. )
  47. .await
  48. .unwrap()
  49. }
  50. async fn initialize() -> &'static Mint {
  51. INSTANCE.get_or_init(|| new_mint(0)).await
  52. }
  53. async fn mint_proofs(
  54. mint: &Mint,
  55. amount: Amount,
  56. split_target: &SplitTarget,
  57. keys: cdk::nuts::Keys,
  58. ) -> Result<Proofs> {
  59. let request_lookup = uuid::Uuid::new_v4().to_string();
  60. let quote = MintQuote::new(
  61. mint.mint_url.clone(),
  62. "".to_string(),
  63. CurrencyUnit::Sat,
  64. amount,
  65. unix_time() + 36000,
  66. request_lookup.to_string(),
  67. );
  68. mint.localstore.add_mint_quote(quote.clone()).await?;
  69. mint.pay_mint_quote_for_request_id(&request_lookup).await?;
  70. let keyset_id = Id::from(&keys);
  71. let premint = PreMintSecrets::random(keyset_id, amount, split_target)?;
  72. let mint_request = MintBolt11Request {
  73. quote: quote.id,
  74. outputs: premint.blinded_messages(),
  75. };
  76. let after_mint = mint.process_mint_request(mint_request).await?;
  77. let proofs = construct_proofs(
  78. after_mint.signatures,
  79. premint.rs(),
  80. premint.secrets(),
  81. &keys,
  82. )?;
  83. Ok(proofs)
  84. }
  85. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  86. async fn test_mint_double_spend() -> Result<()> {
  87. let mint = initialize().await;
  88. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  89. let keyset_id = Id::from(&keys);
  90. let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
  91. let preswap = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())?;
  92. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  93. let swap = mint.process_swap_request(swap_request).await;
  94. assert!(swap.is_ok());
  95. let preswap_two = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())?;
  96. let swap_two_request = SwapRequest::new(proofs, preswap_two.blinded_messages());
  97. match mint.process_swap_request(swap_two_request).await {
  98. Ok(_) => bail!("Proofs double spent"),
  99. Err(err) => match err {
  100. cdk::Error::TokenAlreadySpent => (),
  101. _ => bail!("Wrong error returned"),
  102. },
  103. }
  104. Ok(())
  105. }
  106. /// This attempts to swap for more outputs then inputs.
  107. /// This will work if the mint does not check for outputs amounts overflowing
  108. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  109. async fn test_attempt_to_swap_by_overflowing() -> Result<()> {
  110. let mint = initialize().await;
  111. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  112. let keyset_id = Id::from(&keys);
  113. let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
  114. let amount = 2_u64.pow(63);
  115. let pre_mint_amount =
  116. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default())?;
  117. let pre_mint_amount_two =
  118. PreMintSecrets::random(keyset_id, amount.into(), &SplitTarget::default())?;
  119. let mut pre_mint = PreMintSecrets::random(keyset_id, 1.into(), &SplitTarget::default())?;
  120. pre_mint.combine(pre_mint_amount);
  121. pre_mint.combine(pre_mint_amount_two);
  122. let swap_request = SwapRequest::new(proofs.clone(), pre_mint.blinded_messages());
  123. match mint.process_swap_request(swap_request).await {
  124. Ok(_) => bail!("Swap occurred with overflow"),
  125. Err(err) => match err {
  126. cdk::Error::NUT03(cdk::nuts::nut03::Error::Amount(_)) => (),
  127. _ => {
  128. println!("{:?}", err);
  129. bail!("Wrong error returned in swap overflow")
  130. }
  131. },
  132. }
  133. Ok(())
  134. }
  135. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  136. pub async fn test_p2pk_swap() -> Result<()> {
  137. let mint = initialize().await;
  138. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  139. let keyset_id = Id::from(&keys);
  140. let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
  141. let secret = SecretKey::generate();
  142. let spending_conditions = SpendingConditions::new_p2pk(secret.public_key(), None);
  143. let pre_swap = PreMintSecrets::with_conditions(
  144. keyset_id,
  145. 100.into(),
  146. &SplitTarget::default(),
  147. &spending_conditions,
  148. )?;
  149. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  150. let keys = mint.pubkeys().await?.keysets.first().cloned().unwrap().keys;
  151. let post_swap = mint.process_swap_request(swap_request).await?;
  152. let mut proofs = construct_proofs(
  153. post_swap.signatures,
  154. pre_swap.rs(),
  155. pre_swap.secrets(),
  156. &keys,
  157. )?;
  158. let pre_swap = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())?;
  159. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  160. let public_keys_to_listen: Vec<_> = swap_request
  161. .inputs
  162. .ys()
  163. .expect("key")
  164. .into_iter()
  165. .enumerate()
  166. .filter_map(|(key, pk)| {
  167. if key % 2 == 0 {
  168. // Only expect messages from every other key
  169. Some(pk.to_string())
  170. } else {
  171. None
  172. }
  173. })
  174. .collect();
  175. let mut listener = mint
  176. .pubsub_manager
  177. .subscribe(Params {
  178. kind: cdk::nuts::nut17::Kind::ProofState,
  179. filters: public_keys_to_listen.clone(),
  180. id: "test".into(),
  181. })
  182. .await;
  183. match mint.process_swap_request(swap_request).await {
  184. Ok(_) => bail!("Proofs spent without sig"),
  185. Err(err) => match err {
  186. cdk::Error::NUT11(cdk::nuts::nut11::Error::SignaturesNotProvided) => (),
  187. _ => {
  188. println!("{:?}", err);
  189. bail!("Wrong error returned")
  190. }
  191. },
  192. }
  193. for proof in &mut proofs {
  194. proof.sign_p2pk(secret.clone())?;
  195. }
  196. let swap_request = SwapRequest::new(proofs.clone(), pre_swap.blinded_messages());
  197. let attempt_swap = mint.process_swap_request(swap_request).await;
  198. assert!(attempt_swap.is_ok());
  199. sleep(Duration::from_millis(10)).await;
  200. let mut msgs = HashMap::new();
  201. while let Ok((sub_id, msg)) = listener.try_recv() {
  202. assert_eq!(sub_id, "test".into());
  203. match msg {
  204. NotificationPayload::ProofState(ProofState { y, state, .. }) => {
  205. let pk = y.to_string();
  206. msgs.get_mut(&pk)
  207. .map(|x: &mut Vec<State>| {
  208. x.push(state);
  209. })
  210. .unwrap_or_else(|| {
  211. msgs.insert(pk, vec![state]);
  212. });
  213. }
  214. _ => bail!("Wrong message received"),
  215. }
  216. }
  217. for keys in public_keys_to_listen {
  218. let statuses = msgs.remove(&keys).expect("some events");
  219. assert_eq!(statuses, vec![State::Pending, State::Pending, State::Spent]);
  220. }
  221. assert!(listener.try_recv().is_err(), "no other event is happening");
  222. assert!(msgs.is_empty(), "Only expected key events are received");
  223. Ok(())
  224. }
  225. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  226. async fn test_swap_unbalanced() -> Result<()> {
  227. let mint = initialize().await;
  228. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  229. let keyset_id = Id::from(&keys);
  230. let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
  231. let preswap = PreMintSecrets::random(keyset_id, 95.into(), &SplitTarget::default())?;
  232. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  233. match mint.process_swap_request(swap_request).await {
  234. Ok(_) => bail!("Swap was allowed unbalanced"),
  235. Err(err) => match err {
  236. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  237. _ => bail!("Wrong error returned"),
  238. },
  239. }
  240. let preswap = PreMintSecrets::random(keyset_id, 101.into(), &SplitTarget::default())?;
  241. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  242. match mint.process_swap_request(swap_request).await {
  243. Ok(_) => bail!("Swap was allowed unbalanced"),
  244. Err(err) => match err {
  245. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  246. _ => bail!("Wrong error returned"),
  247. },
  248. }
  249. Ok(())
  250. }
  251. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  252. async fn test_swap_overpay_underpay_fee() -> Result<()> {
  253. let mint = new_mint(1).await;
  254. mint.rotate_keyset(CurrencyUnit::Sat, 1, 32, 1).await?;
  255. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  256. let keyset_id = Id::from(&keys);
  257. let proofs = mint_proofs(&mint, 1000.into(), &SplitTarget::default(), keys).await?;
  258. let preswap = PreMintSecrets::random(keyset_id, 9998.into(), &SplitTarget::default())?;
  259. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  260. // Attempt to swap overpaying fee
  261. match mint.process_swap_request(swap_request).await {
  262. Ok(_) => bail!("Swap was allowed unbalanced"),
  263. Err(err) => match err {
  264. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  265. _ => {
  266. println!("{:?}", err);
  267. bail!("Wrong error returned")
  268. }
  269. },
  270. }
  271. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default())?;
  272. let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());
  273. // Attempt to swap underpaying fee
  274. match mint.process_swap_request(swap_request).await {
  275. Ok(_) => bail!("Swap was allowed unbalanced"),
  276. Err(err) => match err {
  277. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  278. _ => {
  279. println!("{:?}", err);
  280. bail!("Wrong error returned")
  281. }
  282. },
  283. }
  284. Ok(())
  285. }
  286. #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
  287. async fn test_mint_enforce_fee() -> Result<()> {
  288. let mint = new_mint(1).await;
  289. let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
  290. let keyset_id = Id::from(&keys);
  291. let mut proofs = mint_proofs(&mint, 1010.into(), &SplitTarget::Value(1.into()), keys).await?;
  292. let five_proofs: Vec<_> = proofs.drain(..5).collect();
  293. let preswap = PreMintSecrets::random(keyset_id, 5.into(), &SplitTarget::default())?;
  294. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  295. // Attempt to swap underpaying fee
  296. match mint.process_swap_request(swap_request).await {
  297. Ok(_) => bail!("Swap was allowed unbalanced"),
  298. Err(err) => match err {
  299. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  300. _ => {
  301. println!("{:?}", err);
  302. bail!("Wrong error returned")
  303. }
  304. },
  305. }
  306. let preswap = PreMintSecrets::random(keyset_id, 4.into(), &SplitTarget::default())?;
  307. let swap_request = SwapRequest::new(five_proofs.clone(), preswap.blinded_messages());
  308. let _ = mint.process_swap_request(swap_request).await?;
  309. let thousnad_proofs: Vec<_> = proofs.drain(..1001).collect();
  310. let preswap = PreMintSecrets::random(keyset_id, 1000.into(), &SplitTarget::default())?;
  311. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  312. // Attempt to swap underpaying fee
  313. match mint.process_swap_request(swap_request).await {
  314. Ok(_) => bail!("Swap was allowed unbalanced"),
  315. Err(err) => match err {
  316. cdk::Error::TransactionUnbalanced(_, _, _) => (),
  317. _ => {
  318. println!("{:?}", err);
  319. bail!("Wrong error returned")
  320. }
  321. },
  322. }
  323. let preswap = PreMintSecrets::random(keyset_id, 999.into(), &SplitTarget::default())?;
  324. let swap_request = SwapRequest::new(thousnad_proofs.clone(), preswap.blinded_messages());
  325. let _ = mint.process_swap_request(swap_request).await?;
  326. Ok(())
  327. }