wallet.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //! Wallet Types
  2. use std::collections::HashMap;
  3. use std::fmt;
  4. use std::str::FromStr;
  5. use bitcoin::hashes::{sha256, Hash, HashEngine};
  6. use cashu::util::hex;
  7. use cashu::{nut00, Proofs, PublicKey};
  8. use serde::{Deserialize, Serialize};
  9. use crate::mint_url::MintUrl;
  10. use crate::nuts::{CurrencyUnit, MeltQuoteState, MintQuoteState, SecretKey};
  11. use crate::{Amount, Error};
  12. /// Wallet Key
  13. #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
  14. pub struct WalletKey {
  15. /// Mint Url
  16. pub mint_url: MintUrl,
  17. /// Currency Unit
  18. pub unit: CurrencyUnit,
  19. }
  20. impl fmt::Display for WalletKey {
  21. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  22. write!(f, "mint_url: {}, unit: {}", self.mint_url, self.unit,)
  23. }
  24. }
  25. impl WalletKey {
  26. /// Create new [`WalletKey`]
  27. pub fn new(mint_url: MintUrl, unit: CurrencyUnit) -> Self {
  28. Self { mint_url, unit }
  29. }
  30. }
  31. /// Mint Quote Info
  32. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  33. pub struct MintQuote {
  34. /// Quote id
  35. pub id: String,
  36. /// Mint Url
  37. pub mint_url: MintUrl,
  38. /// Amount of quote
  39. pub amount: Amount,
  40. /// Unit of quote
  41. pub unit: CurrencyUnit,
  42. /// Quote payment request e.g. bolt11
  43. pub request: String,
  44. /// Quote state
  45. pub state: MintQuoteState,
  46. /// Expiration time of quote
  47. pub expiry: u64,
  48. /// Secretkey for signing mint quotes [NUT-20]
  49. pub secret_key: Option<SecretKey>,
  50. }
  51. /// Melt Quote Info
  52. #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
  53. pub struct MeltQuote {
  54. /// Quote id
  55. pub id: String,
  56. /// Quote unit
  57. pub unit: CurrencyUnit,
  58. /// Quote amount
  59. pub amount: Amount,
  60. /// Quote Payment request e.g. bolt11
  61. pub request: String,
  62. /// Quote fee reserve
  63. pub fee_reserve: Amount,
  64. /// Quote state
  65. pub state: MeltQuoteState,
  66. /// Expiration time of quote
  67. pub expiry: u64,
  68. /// Payment preimage
  69. pub payment_preimage: Option<String>,
  70. }
  71. /// Send Kind
  72. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default, Serialize, Deserialize)]
  73. pub enum SendKind {
  74. #[default]
  75. /// Allow online swap before send if wallet does not have exact amount
  76. OnlineExact,
  77. /// Prefer offline send if difference is less then tolerance
  78. OnlineTolerance(Amount),
  79. /// Wallet cannot do an online swap and selected proof must be exactly send amount
  80. OfflineExact,
  81. /// Wallet must remain offline but can over pay if below tolerance
  82. OfflineTolerance(Amount),
  83. }
  84. impl SendKind {
  85. /// Check if send kind is online
  86. pub fn is_online(&self) -> bool {
  87. matches!(self, Self::OnlineExact | Self::OnlineTolerance(_))
  88. }
  89. /// Check if send kind is offline
  90. pub fn is_offline(&self) -> bool {
  91. matches!(self, Self::OfflineExact | Self::OfflineTolerance(_))
  92. }
  93. /// Check if send kind is exact
  94. pub fn is_exact(&self) -> bool {
  95. matches!(self, Self::OnlineExact | Self::OfflineExact)
  96. }
  97. /// Check if send kind has tolerance
  98. pub fn has_tolerance(&self) -> bool {
  99. matches!(self, Self::OnlineTolerance(_) | Self::OfflineTolerance(_))
  100. }
  101. }
  102. /// Wallet Transaction
  103. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
  104. pub struct Transaction {
  105. /// Mint Url
  106. pub mint_url: MintUrl,
  107. /// Transaction direction
  108. pub direction: TransactionDirection,
  109. /// Amount
  110. pub amount: Amount,
  111. /// Fee
  112. pub fee: Amount,
  113. /// Currency Unit
  114. pub unit: CurrencyUnit,
  115. /// Proof Ys
  116. pub ys: Vec<PublicKey>,
  117. /// Unix timestamp
  118. pub timestamp: u64,
  119. /// Memo
  120. pub memo: Option<String>,
  121. /// User-defined metadata
  122. pub metadata: HashMap<String, String>,
  123. }
  124. impl Transaction {
  125. /// Transaction ID
  126. pub fn id(&self) -> TransactionId {
  127. TransactionId::new(self.ys.clone())
  128. }
  129. /// Check if transaction matches conditions
  130. pub fn matches_conditions(
  131. &self,
  132. mint_url: &Option<MintUrl>,
  133. direction: &Option<TransactionDirection>,
  134. unit: &Option<CurrencyUnit>,
  135. ) -> bool {
  136. if let Some(mint_url) = mint_url {
  137. if &self.mint_url != mint_url {
  138. return false;
  139. }
  140. }
  141. if let Some(direction) = direction {
  142. if &self.direction != direction {
  143. return false;
  144. }
  145. }
  146. if let Some(unit) = unit {
  147. if &self.unit != unit {
  148. return false;
  149. }
  150. }
  151. true
  152. }
  153. }
  154. impl PartialOrd for Transaction {
  155. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  156. Some(self.cmp(other))
  157. }
  158. }
  159. impl Ord for Transaction {
  160. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  161. self.timestamp.cmp(&other.timestamp).reverse()
  162. }
  163. }
  164. /// Transaction Direction
  165. #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
  166. pub enum TransactionDirection {
  167. /// Incoming transaction (i.e., receive or mint)
  168. Incoming,
  169. /// Outgoing transaction (i.e., send or melt)
  170. Outgoing,
  171. }
  172. impl std::fmt::Display for TransactionDirection {
  173. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  174. match self {
  175. TransactionDirection::Incoming => write!(f, "Incoming"),
  176. TransactionDirection::Outgoing => write!(f, "Outgoing"),
  177. }
  178. }
  179. }
  180. impl FromStr for TransactionDirection {
  181. type Err = Error;
  182. fn from_str(value: &str) -> Result<Self, Self::Err> {
  183. match value {
  184. "Incoming" => Ok(Self::Incoming),
  185. "Outgoing" => Ok(Self::Outgoing),
  186. _ => Err(Error::InvalidTransactionDirection),
  187. }
  188. }
  189. }
  190. /// Transaction ID
  191. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
  192. #[serde(transparent)]
  193. pub struct TransactionId([u8; 32]);
  194. impl TransactionId {
  195. /// Create new [`TransactionId`]
  196. pub fn new(ys: Vec<PublicKey>) -> Self {
  197. let mut ys = ys;
  198. ys.sort();
  199. let mut hasher = sha256::Hash::engine();
  200. for y in ys {
  201. hasher.input(&y.to_bytes());
  202. }
  203. let hash = sha256::Hash::from_engine(hasher);
  204. Self(hash.to_byte_array())
  205. }
  206. /// From proofs
  207. pub fn from_proofs(proofs: Proofs) -> Result<Self, nut00::Error> {
  208. let ys = proofs
  209. .iter()
  210. .map(|proof| proof.y())
  211. .collect::<Result<Vec<PublicKey>, nut00::Error>>()?;
  212. Ok(Self::new(ys))
  213. }
  214. /// From bytes
  215. pub fn from_bytes(bytes: [u8; 32]) -> Self {
  216. Self(bytes)
  217. }
  218. /// From hex string
  219. pub fn from_hex(value: &str) -> Result<Self, Error> {
  220. let bytes = hex::decode(value)?;
  221. let mut array = [0u8; 32];
  222. array.copy_from_slice(&bytes);
  223. Ok(Self(array))
  224. }
  225. /// From slice
  226. pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
  227. if slice.len() != 32 {
  228. return Err(Error::InvalidTransactionId);
  229. }
  230. let mut array = [0u8; 32];
  231. array.copy_from_slice(slice);
  232. Ok(Self(array))
  233. }
  234. /// Get inner value
  235. pub fn as_bytes(&self) -> &[u8; 32] {
  236. &self.0
  237. }
  238. /// Get inner value as slice
  239. pub fn as_slice(&self) -> &[u8] {
  240. &self.0
  241. }
  242. }
  243. impl std::fmt::Display for TransactionId {
  244. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  245. write!(f, "{}", hex::encode(self.0))
  246. }
  247. }
  248. impl FromStr for TransactionId {
  249. type Err = Error;
  250. fn from_str(value: &str) -> Result<Self, Self::Err> {
  251. Self::from_hex(value)
  252. }
  253. }
  254. impl TryFrom<Proofs> for TransactionId {
  255. type Error = nut00::Error;
  256. fn try_from(proofs: Proofs) -> Result<Self, Self::Error> {
  257. Self::from_proofs(proofs)
  258. }
  259. }