mod.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //! Macro with default tests
  2. //!
  3. //! This set is generic and checks the default and expected behaviour for a mint database
  4. //! implementation
  5. use std::str::FromStr;
  6. use std::sync::atomic::{AtomicU64, Ordering};
  7. use std::time::{SystemTime, UNIX_EPOCH};
  8. // For derivation path parsing
  9. use bitcoin::bip32::DerivationPath;
  10. use cashu::secret::Secret;
  11. use cashu::{Amount, CurrencyUnit, SecretKey};
  12. use super::*;
  13. use crate::mint::MintKeySetInfo;
  14. mod kvstore;
  15. mod mint;
  16. mod proofs;
  17. pub use self::mint::*;
  18. pub use self::proofs::*;
  19. #[inline]
  20. async fn setup_keyset<DB>(db: &DB) -> Id
  21. where
  22. DB: KeysDatabase<Err = crate::database::Error>,
  23. {
  24. let keyset_id = Id::from_str("00916bbf7ef91a36").unwrap();
  25. let keyset_info = MintKeySetInfo {
  26. id: keyset_id,
  27. unit: CurrencyUnit::Sat,
  28. active: true,
  29. valid_from: 0,
  30. final_expiry: None,
  31. derivation_path: DerivationPath::from_str("m/0'/0'/0'").unwrap(),
  32. derivation_path_index: Some(0),
  33. max_order: 32,
  34. input_fee_ppk: 0,
  35. amounts: vec![],
  36. };
  37. let mut writer = db.begin_transaction().await.expect("db.begin()");
  38. writer.add_keyset_info(keyset_info).await.unwrap();
  39. writer.commit().await.expect("commit()");
  40. keyset_id
  41. }
  42. /// State transition test
  43. pub async fn state_transition<DB>(db: DB)
  44. where
  45. DB: Database<crate::database::Error> + KeysDatabase<Err = crate::database::Error>,
  46. {
  47. let keyset_id = setup_keyset(&db).await;
  48. let proofs = vec![
  49. Proof {
  50. amount: Amount::from(100),
  51. keyset_id,
  52. secret: Secret::generate(),
  53. c: SecretKey::generate().public_key(),
  54. witness: None,
  55. dleq: None,
  56. },
  57. Proof {
  58. amount: Amount::from(200),
  59. keyset_id,
  60. secret: Secret::generate(),
  61. c: SecretKey::generate().public_key(),
  62. witness: None,
  63. dleq: None,
  64. },
  65. ];
  66. // Add proofs to database
  67. let mut tx = Database::begin_transaction(&db).await.unwrap();
  68. tx.add_proofs(proofs.clone(), None).await.unwrap();
  69. // Mark one proof as `pending`
  70. assert!(tx
  71. .update_proofs_states(&[proofs[0].y().unwrap()], State::Pending)
  72. .await
  73. .is_ok());
  74. // Attempt to select the `pending` proof, as `pending` again (which should fail)
  75. assert!(tx
  76. .update_proofs_states(&[proofs[0].y().unwrap()], State::Pending)
  77. .await
  78. .is_err());
  79. tx.commit().await.unwrap();
  80. }
  81. /// Test KV store functionality including write, read, list, update, and remove operations
  82. pub async fn kvstore_functionality<DB>(db: DB)
  83. where
  84. DB: Database<crate::database::Error> + KVStoreDatabase<Err = crate::database::Error>,
  85. {
  86. // Test basic read/write operations in transaction
  87. {
  88. let mut tx = Database::begin_transaction(&db).await.unwrap();
  89. // Write some test data
  90. tx.kv_write("test_namespace", "sub_namespace", "key1", b"value1")
  91. .await
  92. .unwrap();
  93. tx.kv_write("test_namespace", "sub_namespace", "key2", b"value2")
  94. .await
  95. .unwrap();
  96. tx.kv_write("test_namespace", "other_sub", "key3", b"value3")
  97. .await
  98. .unwrap();
  99. // Read back the data in the transaction
  100. let value1 = tx
  101. .kv_read("test_namespace", "sub_namespace", "key1")
  102. .await
  103. .unwrap();
  104. assert_eq!(value1, Some(b"value1".to_vec()));
  105. // List keys in namespace
  106. let keys = tx.kv_list("test_namespace", "sub_namespace").await.unwrap();
  107. assert_eq!(keys, vec!["key1", "key2"]);
  108. // Commit transaction
  109. tx.commit().await.unwrap();
  110. }
  111. // Test read operations after commit
  112. {
  113. let value1 = db
  114. .kv_read("test_namespace", "sub_namespace", "key1")
  115. .await
  116. .unwrap();
  117. assert_eq!(value1, Some(b"value1".to_vec()));
  118. let keys = db.kv_list("test_namespace", "sub_namespace").await.unwrap();
  119. assert_eq!(keys, vec!["key1", "key2"]);
  120. let other_keys = db.kv_list("test_namespace", "other_sub").await.unwrap();
  121. assert_eq!(other_keys, vec!["key3"]);
  122. }
  123. // Test update and remove operations
  124. {
  125. let mut tx = Database::begin_transaction(&db).await.unwrap();
  126. // Update existing key
  127. tx.kv_write("test_namespace", "sub_namespace", "key1", b"updated_value1")
  128. .await
  129. .unwrap();
  130. // Remove a key
  131. tx.kv_remove("test_namespace", "sub_namespace", "key2")
  132. .await
  133. .unwrap();
  134. tx.commit().await.unwrap();
  135. }
  136. // Verify updates
  137. {
  138. let value1 = db
  139. .kv_read("test_namespace", "sub_namespace", "key1")
  140. .await
  141. .unwrap();
  142. assert_eq!(value1, Some(b"updated_value1".to_vec()));
  143. let value2 = db
  144. .kv_read("test_namespace", "sub_namespace", "key2")
  145. .await
  146. .unwrap();
  147. assert_eq!(value2, None);
  148. let keys = db.kv_list("test_namespace", "sub_namespace").await.unwrap();
  149. assert_eq!(keys, vec!["key1"]);
  150. }
  151. }
  152. static COUNTER: AtomicU64 = AtomicU64::new(0);
  153. /// Returns a unique, random-looking Base62 string (no external crates).
  154. /// Not cryptographically secure, but great for ids, keys, temp names, etc.
  155. fn unique_string() -> String {
  156. // 1) high-res timestamp (nanos since epoch)
  157. let now = SystemTime::now()
  158. .duration_since(UNIX_EPOCH)
  159. .unwrap()
  160. .as_nanos();
  161. // 2) per-process monotonic counter to avoid collisions in the same instant
  162. let n = COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
  163. // 3) process id to reduce collision chance across processes
  164. let pid = std::process::id() as u128;
  165. // Mix the components (simple XOR/shift mix; good enough for "random-looking")
  166. let mixed = now ^ (pid << 64) ^ (n << 32);
  167. base62_encode(mixed)
  168. }
  169. fn base62_encode(mut x: u128) -> String {
  170. const ALPHABET: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  171. if x == 0 {
  172. return "0".to_string();
  173. }
  174. let mut buf = [0u8; 26]; // enough for base62(u128)
  175. let mut i = buf.len();
  176. while x > 0 {
  177. let rem = (x % 62) as usize;
  178. x /= 62;
  179. i -= 1;
  180. buf[i] = ALPHABET[rem];
  181. }
  182. String::from_utf8_lossy(&buf[i..]).into_owned()
  183. }
  184. /// Unit test that is expected to be passed for a correct database implementation
  185. #[macro_export]
  186. macro_rules! mint_db_test {
  187. ($make_db_fn:ident) => {
  188. mint_db_test!(
  189. $make_db_fn,
  190. state_transition,
  191. add_and_find_proofs,
  192. add_duplicate_proofs,
  193. kvstore_functionality,
  194. add_mint_quote,
  195. add_mint_quote_only_once,
  196. register_payments,
  197. read_mint_from_db_and_tx,
  198. get_proofs_by_keyset_id,
  199. reject_duplicate_payments_same_tx,
  200. reject_duplicate_payments_diff_tx,
  201. reject_over_issue_same_tx,
  202. reject_over_issue_different_tx,
  203. reject_over_issue_with_payment,
  204. reject_over_issue_with_payment_different_tx
  205. );
  206. };
  207. ($make_db_fn:ident, $($name:ident),+ $(,)?) => {
  208. $(
  209. #[tokio::test]
  210. async fn $name() {
  211. use std::time::{SystemTime, UNIX_EPOCH};
  212. let now = SystemTime::now()
  213. .duration_since(UNIX_EPOCH)
  214. .expect("Time went backwards");
  215. cdk_common::database::mint::test::$name($make_db_fn(format!("test_{}_{}", now.as_nanos(), stringify!($name))).await).await;
  216. }
  217. )+
  218. };
  219. }