mint.rs 13 KB

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