mint.rs 13 KB

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