integration_tests_pure.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #[cfg(test)]
  2. mod integration_tests_pure {
  3. use std::assert_eq;
  4. use std::collections::HashMap;
  5. use std::fmt::{Debug, Formatter};
  6. use std::str::FromStr;
  7. use std::sync::Arc;
  8. use async_trait::async_trait;
  9. use cdk::amount::SplitTarget;
  10. use cdk::cdk_database::mint_memory::MintMemoryDatabase;
  11. use cdk::cdk_database::WalletMemoryDatabase;
  12. use cdk::nuts::{
  13. CheckStateRequest, CheckStateResponse, CurrencyUnit, Id, KeySet, KeysetResponse,
  14. MeltBolt11Request, MeltQuoteBolt11Request, MeltQuoteBolt11Response, MintBolt11Request,
  15. MintBolt11Response, MintInfo, MintQuoteBolt11Request, MintQuoteBolt11Response,
  16. MintQuoteState, Nuts, RestoreRequest, RestoreResponse, SwapRequest, SwapResponse,
  17. };
  18. use cdk::types::QuoteTTL;
  19. use cdk::util::unix_time;
  20. use cdk::wallet::client::MintConnector;
  21. use cdk::{Amount, Error, Mint, Wallet};
  22. use cdk_integration_tests::create_backends_fake_wallet;
  23. use rand::random;
  24. use tokio::sync::Notify;
  25. use uuid::Uuid;
  26. struct DirectMintConnection {
  27. mint: Arc<Mint>,
  28. }
  29. impl Debug for DirectMintConnection {
  30. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  31. write!(
  32. f,
  33. "DirectMintConnection {{ mint_info: {:?} }}",
  34. self.mint.mint_info
  35. )
  36. }
  37. }
  38. /// Implements the generic [MintConnector] (i.e. use the interface that expects to communicate
  39. /// to a generic mint, where we don't know that quote ID's are [Uuid]s) for [DirectMintConnection],
  40. /// where we know we're dealing with a mint that uses [Uuid]s for quotes.
  41. /// Convert the requests and responses between the [String] and [Uuid] variants as necessary.
  42. #[async_trait]
  43. impl MintConnector for DirectMintConnection {
  44. async fn get_mint_keys(&self) -> Result<Vec<KeySet>, Error> {
  45. self.mint.pubkeys().await.map(|pks| pks.keysets)
  46. }
  47. async fn get_mint_keyset(&self, keyset_id: Id) -> Result<KeySet, Error> {
  48. self.mint
  49. .keyset(&keyset_id)
  50. .await
  51. .and_then(|res| res.ok_or(Error::UnknownKeySet))
  52. }
  53. async fn get_mint_keysets(&self) -> Result<KeysetResponse, Error> {
  54. self.mint.keysets().await
  55. }
  56. async fn post_mint_quote(
  57. &self,
  58. request: MintQuoteBolt11Request,
  59. ) -> Result<MintQuoteBolt11Response<String>, Error> {
  60. self.mint
  61. .get_mint_bolt11_quote(request)
  62. .await
  63. .map(Into::into)
  64. }
  65. async fn get_mint_quote_status(
  66. &self,
  67. quote_id: &str,
  68. ) -> Result<MintQuoteBolt11Response<String>, Error> {
  69. let quote_id_uuid = Uuid::from_str(quote_id).unwrap();
  70. self.mint
  71. .check_mint_quote(&quote_id_uuid)
  72. .await
  73. .map(Into::into)
  74. }
  75. async fn post_mint(
  76. &self,
  77. request: MintBolt11Request<String>,
  78. ) -> Result<MintBolt11Response, Error> {
  79. let request_uuid = request.try_into().unwrap();
  80. self.mint.process_mint_request(request_uuid).await
  81. }
  82. async fn post_melt_quote(
  83. &self,
  84. request: MeltQuoteBolt11Request,
  85. ) -> Result<MeltQuoteBolt11Response<String>, Error> {
  86. self.mint
  87. .get_melt_bolt11_quote(&request)
  88. .await
  89. .map(Into::into)
  90. }
  91. async fn get_melt_quote_status(
  92. &self,
  93. quote_id: &str,
  94. ) -> Result<MeltQuoteBolt11Response<String>, Error> {
  95. let quote_id_uuid = Uuid::from_str(quote_id).unwrap();
  96. self.mint
  97. .check_melt_quote(&quote_id_uuid)
  98. .await
  99. .map(Into::into)
  100. }
  101. async fn post_melt(
  102. &self,
  103. request: MeltBolt11Request<String>,
  104. ) -> Result<MeltQuoteBolt11Response<String>, Error> {
  105. let request_uuid = request.try_into().unwrap();
  106. self.mint.melt_bolt11(&request_uuid).await.map(Into::into)
  107. }
  108. async fn post_swap(&self, swap_request: SwapRequest) -> Result<SwapResponse, Error> {
  109. self.mint.process_swap_request(swap_request).await
  110. }
  111. async fn get_mint_info(&self) -> Result<MintInfo, Error> {
  112. Ok(self.mint.mint_info().clone().time(unix_time()))
  113. }
  114. async fn post_check_state(
  115. &self,
  116. request: CheckStateRequest,
  117. ) -> Result<CheckStateResponse, Error> {
  118. self.mint.check_state(&request).await
  119. }
  120. async fn post_restore(&self, request: RestoreRequest) -> Result<RestoreResponse, Error> {
  121. self.mint.restore(request).await
  122. }
  123. }
  124. fn get_mint_connector(mint: Arc<Mint>) -> DirectMintConnection {
  125. DirectMintConnection { mint }
  126. }
  127. async fn create_and_start_test_mint() -> anyhow::Result<Arc<Mint>> {
  128. let fee: u64 = 0;
  129. let mut supported_units = HashMap::new();
  130. supported_units.insert(CurrencyUnit::Sat, (fee, 32));
  131. let nuts = Nuts::new()
  132. .nut07(true)
  133. .nut08(true)
  134. .nut09(true)
  135. .nut10(true)
  136. .nut11(true)
  137. .nut12(true)
  138. .nut14(true);
  139. let mint_info = MintInfo::new().nuts(nuts);
  140. let quote_ttl = QuoteTTL::new(10000, 10000);
  141. let mint_url = "http://aaa";
  142. let seed = random::<[u8; 32]>();
  143. let mint: Mint = Mint::new(
  144. mint_url,
  145. &seed,
  146. mint_info,
  147. quote_ttl,
  148. Arc::new(MintMemoryDatabase::default()),
  149. create_backends_fake_wallet(),
  150. supported_units,
  151. HashMap::new(),
  152. )
  153. .await?;
  154. let mint_arc = Arc::new(mint);
  155. let mint_arc_clone = Arc::clone(&mint_arc);
  156. let shutdown = Arc::new(Notify::new());
  157. tokio::spawn({
  158. let shutdown = Arc::clone(&shutdown);
  159. async move { mint_arc_clone.wait_for_paid_invoices(shutdown).await }
  160. });
  161. Ok(mint_arc)
  162. }
  163. fn create_test_wallet_for_mint(mint: Arc<Mint>) -> anyhow::Result<Arc<Wallet>> {
  164. let connector = get_mint_connector(mint);
  165. let seed = random::<[u8; 32]>();
  166. let mint_url = connector.mint.mint_url.to_string();
  167. let unit = CurrencyUnit::Sat;
  168. let localstore = WalletMemoryDatabase::default();
  169. let mut wallet = Wallet::new(&mint_url, unit, Arc::new(localstore), &seed, None)?;
  170. wallet.set_client(connector);
  171. Ok(Arc::new(wallet))
  172. }
  173. /// Creates a mint quote for the given amount and checks its state in a loop. Returns when
  174. /// amount is minted.
  175. async fn receive(wallet: Arc<Wallet>, amount: u64) -> anyhow::Result<Amount> {
  176. let desired_amount = Amount::from(amount);
  177. let quote = wallet.mint_quote(desired_amount, None).await?;
  178. loop {
  179. let status = wallet.mint_quote_state(&quote.id).await?;
  180. if status.state == MintQuoteState::Paid {
  181. break;
  182. }
  183. }
  184. wallet
  185. .mint(&quote.id, SplitTarget::default(), None)
  186. .await
  187. .map_err(Into::into)
  188. }
  189. mod nut03 {
  190. use cdk::nuts::nut00::ProofsMethods;
  191. use cdk::wallet::SendKind;
  192. use crate::integration_tests_pure::*;
  193. #[tokio::test]
  194. async fn test_swap_to_send() -> anyhow::Result<()> {
  195. let mint_bob = create_and_start_test_mint().await?;
  196. let wallet_alice = create_test_wallet_for_mint(mint_bob.clone())?;
  197. // Alice gets 64 sats
  198. receive(wallet_alice.clone(), 64).await?;
  199. let balance_alice = wallet_alice.total_balance().await?;
  200. assert_eq!(Amount::from(64), balance_alice);
  201. // Alice wants to send 40 sats, which internally swaps
  202. let token = wallet_alice
  203. .send(
  204. Amount::from(40),
  205. None,
  206. None,
  207. &SplitTarget::None,
  208. &SendKind::OnlineExact,
  209. false,
  210. )
  211. .await?;
  212. assert_eq!(Amount::from(40), token.proofs().total_amount()?);
  213. assert_eq!(Amount::from(24), wallet_alice.total_balance().await?);
  214. // Alice sends cashu, Carol receives
  215. let wallet_carol = create_test_wallet_for_mint(mint_bob.clone())?;
  216. let received_amount = wallet_carol
  217. .receive_proofs(token.proofs(), SplitTarget::None, &[], &[])
  218. .await?;
  219. assert_eq!(Amount::from(40), received_amount);
  220. assert_eq!(Amount::from(40), wallet_carol.total_balance().await?);
  221. Ok(())
  222. }
  223. }
  224. }