mint.rs 13 KB

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