common.rs 9.9 KB

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