common.rs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. /// Secs wuotes are valid
  147. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
  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. #[cfg(test)]
  161. mod tests {
  162. use std::str::FromStr;
  163. use cashu::SecretKey;
  164. use super::{Melted, ProofInfo};
  165. use crate::mint_url::MintUrl;
  166. use crate::nuts::{CurrencyUnit, Id, Proof, PublicKey, SpendingConditions, State};
  167. use crate::secret::Secret;
  168. use crate::Amount;
  169. #[test]
  170. fn test_melted() {
  171. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  172. let proof = Proof::new(
  173. Amount::from(64),
  174. keyset_id,
  175. Secret::generate(),
  176. PublicKey::from_hex(
  177. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  178. )
  179. .unwrap(),
  180. );
  181. let melted = Melted::from_proofs(
  182. super::MeltQuoteState::Paid,
  183. Some("preimage".to_string()),
  184. Amount::from(64),
  185. vec![proof.clone()],
  186. None,
  187. )
  188. .unwrap();
  189. assert_eq!(melted.amount, Amount::from(64));
  190. assert_eq!(melted.fee_paid, Amount::ZERO);
  191. assert_eq!(melted.total_amount(), Amount::from(64));
  192. }
  193. #[test]
  194. fn test_melted_with_change() {
  195. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  196. let proof = Proof::new(
  197. Amount::from(64),
  198. keyset_id,
  199. Secret::generate(),
  200. PublicKey::from_hex(
  201. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  202. )
  203. .unwrap(),
  204. );
  205. let change_proof = Proof::new(
  206. Amount::from(32),
  207. keyset_id,
  208. Secret::generate(),
  209. PublicKey::from_hex(
  210. "03deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  211. )
  212. .unwrap(),
  213. );
  214. let melted = Melted::from_proofs(
  215. super::MeltQuoteState::Paid,
  216. Some("preimage".to_string()),
  217. Amount::from(31),
  218. vec![proof.clone()],
  219. Some(vec![change_proof.clone()]),
  220. )
  221. .unwrap();
  222. assert_eq!(melted.amount, Amount::from(31));
  223. assert_eq!(melted.fee_paid, Amount::from(1));
  224. assert_eq!(melted.total_amount(), Amount::from(32));
  225. }
  226. #[test]
  227. fn test_matches_conditions() {
  228. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  229. let proof = Proof::new(
  230. Amount::from(64),
  231. keyset_id,
  232. Secret::new("test_secret"),
  233. PublicKey::from_hex(
  234. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  235. )
  236. .unwrap(),
  237. );
  238. let mint_url = MintUrl::from_str("https://example.com").unwrap();
  239. let proof_info =
  240. ProofInfo::new(proof, mint_url.clone(), State::Unspent, CurrencyUnit::Sat).unwrap();
  241. // Test matching mint_url
  242. assert!(proof_info.matches_conditions(&Some(mint_url.clone()), &None, &None, &None));
  243. assert!(!proof_info.matches_conditions(
  244. &Some(MintUrl::from_str("https://different.com").unwrap()),
  245. &None,
  246. &None,
  247. &None
  248. ));
  249. // Test matching unit
  250. assert!(proof_info.matches_conditions(&None, &Some(CurrencyUnit::Sat), &None, &None));
  251. assert!(!proof_info.matches_conditions(&None, &Some(CurrencyUnit::Msat), &None, &None));
  252. // Test matching state
  253. assert!(proof_info.matches_conditions(&None, &None, &Some(vec![State::Unspent]), &None));
  254. assert!(proof_info.matches_conditions(
  255. &None,
  256. &None,
  257. &Some(vec![State::Unspent, State::Spent]),
  258. &None
  259. ));
  260. assert!(!proof_info.matches_conditions(&None, &None, &Some(vec![State::Spent]), &None));
  261. // Test with no conditions (should match)
  262. assert!(proof_info.matches_conditions(&None, &None, &None, &None));
  263. // Test with multiple conditions
  264. assert!(proof_info.matches_conditions(
  265. &Some(mint_url),
  266. &Some(CurrencyUnit::Sat),
  267. &Some(vec![State::Unspent]),
  268. &None
  269. ));
  270. }
  271. #[test]
  272. fn test_matches_conditions_with_spending_conditions() {
  273. // This test would need to be expanded with actual SpendingConditions
  274. // implementation, but we can test the basic case where no spending
  275. // conditions are present
  276. let keyset_id = Id::from_str("00deadbeef123456").unwrap();
  277. let proof = Proof::new(
  278. Amount::from(64),
  279. keyset_id,
  280. Secret::new("test_secret"),
  281. PublicKey::from_hex(
  282. "02deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
  283. )
  284. .unwrap(),
  285. );
  286. let mint_url = MintUrl::from_str("https://example.com").unwrap();
  287. let proof_info =
  288. ProofInfo::new(proof, mint_url, State::Unspent, CurrencyUnit::Sat).unwrap();
  289. // Test with empty spending conditions (should match when proof has none)
  290. assert!(proof_info.matches_conditions(&None, &None, &None, &Some(vec![])));
  291. // Test with non-empty spending conditions (should not match when proof has none)
  292. let dummy_condition = SpendingConditions::P2PKConditions {
  293. data: SecretKey::generate().public_key(),
  294. conditions: None,
  295. };
  296. assert!(!proof_info.matches_conditions(&None, &None, &None, &Some(vec![dummy_condition])));
  297. }
  298. }
  299. /// Mint Fee Reserve
  300. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
  301. pub struct FeeReserve {
  302. /// Absolute expected min fee
  303. pub min_fee_reserve: Amount,
  304. /// Percentage expected fee
  305. pub percent_fee_reserve: f32,
  306. }