common.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. //! Types
  2. use serde::{Deserialize, Serialize};
  3. use crate::error::Error;
  4. use crate::mint_url::MintUrl;
  5. use crate::nuts::nut00::ProofsMethods;
  6. use crate::nuts::{
  7. CurrencyUnit, MeltQuoteState, PaymentMethod, Proof, Proofs, PublicKey, SpendingConditions,
  8. State,
  9. };
  10. use crate::Amount;
  11. /// Melt response with proofs
  12. #[derive(Debug, Clone, Hash, PartialEq, Eq, Default, Serialize, Deserialize)]
  13. pub struct Melted {
  14. /// State of quote
  15. pub state: MeltQuoteState,
  16. /// Preimage of melt payment
  17. pub preimage: Option<String>,
  18. /// Melt change
  19. pub change: Option<Proofs>,
  20. /// Melt amount
  21. pub amount: Amount,
  22. /// Fee paid
  23. pub fee_paid: Amount,
  24. }
  25. impl Melted {
  26. /// Create new [`Melted`]
  27. pub fn from_proofs(
  28. state: MeltQuoteState,
  29. preimage: Option<String>,
  30. amount: Amount,
  31. proofs: Proofs,
  32. change_proofs: Option<Proofs>,
  33. ) -> Result<Self, Error> {
  34. let proofs_amount = proofs.total_amount()?;
  35. let change_amount = match &change_proofs {
  36. Some(change_proofs) => change_proofs.total_amount()?,
  37. None => Amount::ZERO,
  38. };
  39. let fee_paid = proofs_amount
  40. .checked_sub(amount + change_amount)
  41. .ok_or(Error::AmountOverflow)
  42. .unwrap();
  43. Ok(Self {
  44. state,
  45. preimage,
  46. change: change_proofs,
  47. amount,
  48. fee_paid,
  49. })
  50. }
  51. /// Total amount melted
  52. pub fn total_amount(&self) -> Amount {
  53. self.amount + self.fee_paid
  54. }
  55. }
  56. /// Prooinfo
  57. #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
  58. pub struct ProofInfo {
  59. /// Proof
  60. pub proof: Proof,
  61. /// y
  62. pub y: PublicKey,
  63. /// Mint Url
  64. pub mint_url: MintUrl,
  65. /// Proof State
  66. pub state: State,
  67. /// Proof Spending Conditions
  68. pub spending_condition: Option<SpendingConditions>,
  69. /// Unit
  70. pub unit: CurrencyUnit,
  71. }
  72. impl ProofInfo {
  73. /// Create new [`ProofInfo`]
  74. pub fn new(
  75. proof: Proof,
  76. mint_url: MintUrl,
  77. state: State,
  78. unit: CurrencyUnit,
  79. ) -> Result<Self, Error> {
  80. let y = proof.y()?;
  81. let spending_condition: Option<SpendingConditions> = (&proof.secret).try_into().ok();
  82. Ok(Self {
  83. proof,
  84. y,
  85. mint_url,
  86. state,
  87. spending_condition,
  88. unit,
  89. })
  90. }
  91. /// Check if [`Proof`] matches conditions
  92. pub fn matches_conditions(
  93. &self,
  94. mint_url: &Option<MintUrl>,
  95. unit: &Option<CurrencyUnit>,
  96. state: &Option<Vec<State>>,
  97. spending_conditions: &Option<Vec<SpendingConditions>>,
  98. ) -> bool {
  99. if let Some(mint_url) = mint_url {
  100. if mint_url.ne(&self.mint_url) {
  101. return false;
  102. }
  103. }
  104. if let Some(unit) = unit {
  105. if unit.ne(&self.unit) {
  106. return false;
  107. }
  108. }
  109. if let Some(state) = state {
  110. if !state.contains(&self.state) {
  111. return false;
  112. }
  113. }
  114. if let Some(spending_conditions) = spending_conditions {
  115. match &self.spending_condition {
  116. None => {
  117. if !spending_conditions.is_empty() {
  118. return false;
  119. }
  120. }
  121. Some(s) => {
  122. if !spending_conditions.contains(s) {
  123. return false;
  124. }
  125. }
  126. }
  127. }
  128. true
  129. }
  130. }
  131. /// Key used in hashmap of ln backends to identify what unit and payment method
  132. /// it is for
  133. #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
  134. pub struct PaymentProcessorKey {
  135. /// Unit of Payment backend
  136. pub unit: CurrencyUnit,
  137. /// Method of payment backend
  138. pub method: PaymentMethod,
  139. }
  140. impl PaymentProcessorKey {
  141. /// Create new [`PaymentProcessorKey`]
  142. pub fn new(unit: CurrencyUnit, method: PaymentMethod) -> Self {
  143. Self { unit, method }
  144. }
  145. }
  146. /// Seconds quotes are valid
  147. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
  148. pub struct QuoteTTL {
  149. /// Seconds mint quote is valid
  150. pub mint_ttl: u64,
  151. /// Seconds melt quote is valid
  152. pub melt_ttl: u64,
  153. }
  154. impl QuoteTTL {
  155. /// Create new [`QuoteTTL`]
  156. pub fn new(mint_ttl: u64, melt_ttl: u64) -> QuoteTTL {
  157. Self { mint_ttl, melt_ttl }
  158. }
  159. }
  160. impl Default for QuoteTTL {
  161. fn default() -> Self {
  162. Self {
  163. mint_ttl: 60 * 60, // 1 hour
  164. melt_ttl: 60, // 1 minute
  165. }
  166. }
  167. }
  168. #[cfg(test)]
  169. mod tests {
  170. use std::str::FromStr;
  171. use cashu::SecretKey;
  172. use super::{Melted, ProofInfo};
  173. use crate::mint_url::MintUrl;
  174. use crate::nuts::{CurrencyUnit, Id, Proof, PublicKey, SpendingConditions, State};
  175. use crate::secret::Secret;
  176. use crate::Amount;
  177. #[test]
  178. fn test_melted() {
  179. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  180. let proof = Proof::new(
  181. Amount::from(64),
  182. keyset_id,
  183. Secret::generate(),
  184. PublicKey::from_hex(
  185. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  186. )
  187. .unwrap(),
  188. );
  189. let melted = Melted::from_proofs(
  190. super::MeltQuoteState::Paid,
  191. Some("preimage".to_string()),
  192. Amount::from(64),
  193. vec![proof.clone()],
  194. None,
  195. )
  196. .unwrap();
  197. assert_eq!(melted.amount, Amount::from(64));
  198. assert_eq!(melted.fee_paid, Amount::ZERO);
  199. assert_eq!(melted.total_amount(), Amount::from(64));
  200. }
  201. #[test]
  202. fn test_melted_with_change() {
  203. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  204. let proof = Proof::new(
  205. Amount::from(64),
  206. keyset_id,
  207. Secret::generate(),
  208. PublicKey::from_hex(
  209. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  210. )
  211. .unwrap(),
  212. );
  213. let change_proof = Proof::new(
  214. Amount::from(32),
  215. keyset_id,
  216. Secret::generate(),
  217. PublicKey::from_hex(
  218. "03deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  219. )
  220. .unwrap(),
  221. );
  222. let melted = Melted::from_proofs(
  223. super::MeltQuoteState::Paid,
  224. Some("preimage".to_string()),
  225. Amount::from(31),
  226. vec![proof.clone()],
  227. Some(vec![change_proof.clone()]),
  228. )
  229. .unwrap();
  230. assert_eq!(melted.amount, Amount::from(31));
  231. assert_eq!(melted.fee_paid, Amount::from(1));
  232. assert_eq!(melted.total_amount(), Amount::from(32));
  233. }
  234. #[test]
  235. fn test_matches_conditions() {
  236. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  237. let proof = Proof::new(
  238. Amount::from(64),
  239. keyset_id,
  240. Secret::new("test_secret"),
  241. PublicKey::from_hex(
  242. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  243. )
  244. .unwrap(),
  245. );
  246. let mint_url = MintUrl::from_str("https://example.com").unwrap();
  247. let proof_info =
  248. ProofInfo::new(proof, mint_url.clone(), State::Unspent, CurrencyUnit::Sat).unwrap();
  249. // Test matching mint_url
  250. assert!(proof_info.matches_conditions(&Some(mint_url.clone()), &None, &None, &None));
  251. assert!(!proof_info.matches_conditions(
  252. &Some(MintUrl::from_str("https://different.com").unwrap()),
  253. &None,
  254. &None,
  255. &None
  256. ));
  257. // Test matching unit
  258. assert!(proof_info.matches_conditions(&None, &Some(CurrencyUnit::Sat), &None, &None));
  259. assert!(!proof_info.matches_conditions(&None, &Some(CurrencyUnit::Msat), &None, &None));
  260. // Test matching state
  261. assert!(proof_info.matches_conditions(&None, &None, &Some(vec![State::Unspent]), &None));
  262. assert!(proof_info.matches_conditions(
  263. &None,
  264. &None,
  265. &Some(vec![State::Unspent, State::Spent]),
  266. &None
  267. ));
  268. assert!(!proof_info.matches_conditions(&None, &None, &Some(vec![State::Spent]), &None));
  269. // Test with no conditions (should match)
  270. assert!(proof_info.matches_conditions(&None, &None, &None, &None));
  271. // Test with multiple conditions
  272. assert!(proof_info.matches_conditions(
  273. &Some(mint_url),
  274. &Some(CurrencyUnit::Sat),
  275. &Some(vec![State::Unspent]),
  276. &None
  277. ));
  278. }
  279. #[test]
  280. fn test_matches_conditions_with_spending_conditions() {
  281. // This test would need to be expanded with actual SpendingConditions
  282. // implementation, but we can test the basic case where no spending
  283. // conditions are present
  284. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  285. let proof = Proof::new(
  286. Amount::from(64),
  287. keyset_id,
  288. Secret::new("test_secret"),
  289. PublicKey::from_hex(
  290. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  291. )
  292. .unwrap(),
  293. );
  294. let mint_url = MintUrl::from_str("https://example.com").unwrap();
  295. let proof_info =
  296. ProofInfo::new(proof, mint_url, State::Unspent, CurrencyUnit::Sat).unwrap();
  297. // Test with empty spending conditions (should match when proof has none)
  298. assert!(proof_info.matches_conditions(&None, &None, &None, &Some(vec![])));
  299. // Test with non-empty spending conditions (should not match when proof has none)
  300. let dummy_condition = SpendingConditions::P2PKConditions {
  301. data: SecretKey::generate().public_key(),
  302. conditions: None,
  303. };
  304. assert!(!proof_info.matches_conditions(&None, &None, &None, &Some(vec![dummy_condition])));
  305. }
  306. }
  307. /// Mint Fee Reserve
  308. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  309. pub struct FeeReserve {
  310. /// Absolute expected min fee
  311. pub min_fee_reserve: Amount,
  312. /// Percentage expected fee
  313. pub percent_fee_reserve: f32,
  314. }