cdk_common/
wallet.rs

1//! Wallet Types
2
3use std::collections::HashMap;
4use std::fmt;
5use std::str::FromStr;
6
7use bitcoin::hashes::{sha256, Hash, HashEngine};
8use cashu::util::hex;
9use cashu::{nut00, PaymentMethod, Proofs, PublicKey};
10use serde::{Deserialize, Serialize};
11
12use crate::mint_url::MintUrl;
13use crate::nuts::{CurrencyUnit, MeltQuoteState, MintQuoteState, SecretKey};
14use crate::{Amount, Error};
15
16/// Wallet Key
17#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
18pub struct WalletKey {
19    /// Mint Url
20    pub mint_url: MintUrl,
21    /// Currency Unit
22    pub unit: CurrencyUnit,
23}
24
25impl fmt::Display for WalletKey {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "mint_url: {}, unit: {}", self.mint_url, self.unit,)
28    }
29}
30
31impl WalletKey {
32    /// Create new [`WalletKey`]
33    pub fn new(mint_url: MintUrl, unit: CurrencyUnit) -> Self {
34        Self { mint_url, unit }
35    }
36}
37
38/// Mint Quote Info
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct MintQuote {
41    /// Quote id
42    pub id: String,
43    /// Mint Url
44    pub mint_url: MintUrl,
45    /// Payment method
46    #[serde(default)]
47    pub payment_method: PaymentMethod,
48    /// Amount of quote
49    pub amount: Option<Amount>,
50    /// Unit of quote
51    pub unit: CurrencyUnit,
52    /// Quote payment request e.g. bolt11
53    pub request: String,
54    /// Quote state
55    pub state: MintQuoteState,
56    /// Expiration time of quote
57    pub expiry: u64,
58    /// Secretkey for signing mint quotes [NUT-20]
59    pub secret_key: Option<SecretKey>,
60    /// Amount minted
61    #[serde(default)]
62    pub amount_issued: Amount,
63    /// Amount paid to the mint for the quote
64    #[serde(default)]
65    pub amount_paid: Amount,
66}
67
68/// Melt Quote Info
69#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
70pub struct MeltQuote {
71    /// Quote id
72    pub id: String,
73    /// Quote unit
74    pub unit: CurrencyUnit,
75    /// Quote amount
76    pub amount: Amount,
77    /// Quote Payment request e.g. bolt11
78    pub request: String,
79    /// Quote fee reserve
80    pub fee_reserve: Amount,
81    /// Quote state
82    pub state: MeltQuoteState,
83    /// Expiration time of quote
84    pub expiry: u64,
85    /// Payment preimage
86    pub payment_preimage: Option<String>,
87    /// Payment method
88    #[serde(default)]
89    pub payment_method: PaymentMethod,
90}
91
92impl MintQuote {
93    /// Create a new MintQuote
94    #[allow(clippy::too_many_arguments)]
95    pub fn new(
96        id: String,
97        mint_url: MintUrl,
98        payment_method: PaymentMethod,
99        amount: Option<Amount>,
100        unit: CurrencyUnit,
101        request: String,
102        expiry: u64,
103        secret_key: Option<SecretKey>,
104    ) -> Self {
105        Self {
106            id,
107            mint_url,
108            payment_method,
109            amount,
110            unit,
111            request,
112            state: MintQuoteState::Unpaid,
113            expiry,
114            secret_key,
115            amount_issued: Amount::ZERO,
116            amount_paid: Amount::ZERO,
117        }
118    }
119
120    /// Calculate the total amount including any fees
121    pub fn total_amount(&self) -> Amount {
122        self.amount_paid
123    }
124
125    /// Check if the quote has expired
126    pub fn is_expired(&self, current_time: u64) -> bool {
127        current_time > self.expiry
128    }
129
130    /// Amount that can be minted
131    pub fn amount_mintable(&self) -> Amount {
132        if self.amount_issued > self.amount_paid {
133            return Amount::ZERO;
134        }
135
136        let difference = self.amount_paid - self.amount_issued;
137
138        if difference == Amount::ZERO && self.state != MintQuoteState::Issued {
139            if let Some(amount) = self.amount {
140                return amount;
141            }
142        }
143
144        difference
145    }
146}
147
148/// Send Kind
149#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default, Serialize, Deserialize)]
150pub enum SendKind {
151    #[default]
152    /// Allow online swap before send if wallet does not have exact amount
153    OnlineExact,
154    /// Prefer offline send if difference is less then tolerance
155    OnlineTolerance(Amount),
156    /// Wallet cannot do an online swap and selected proof must be exactly send amount
157    OfflineExact,
158    /// Wallet must remain offline but can over pay if below tolerance
159    OfflineTolerance(Amount),
160}
161
162impl SendKind {
163    /// Check if send kind is online
164    pub fn is_online(&self) -> bool {
165        matches!(self, Self::OnlineExact | Self::OnlineTolerance(_))
166    }
167
168    /// Check if send kind is offline
169    pub fn is_offline(&self) -> bool {
170        matches!(self, Self::OfflineExact | Self::OfflineTolerance(_))
171    }
172
173    /// Check if send kind is exact
174    pub fn is_exact(&self) -> bool {
175        matches!(self, Self::OnlineExact | Self::OfflineExact)
176    }
177
178    /// Check if send kind has tolerance
179    pub fn has_tolerance(&self) -> bool {
180        matches!(self, Self::OnlineTolerance(_) | Self::OfflineTolerance(_))
181    }
182}
183
184/// Wallet Transaction
185#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
186pub struct Transaction {
187    /// Mint Url
188    pub mint_url: MintUrl,
189    /// Transaction direction
190    pub direction: TransactionDirection,
191    /// Amount
192    pub amount: Amount,
193    /// Fee
194    pub fee: Amount,
195    /// Currency Unit
196    pub unit: CurrencyUnit,
197    /// Proof Ys
198    pub ys: Vec<PublicKey>,
199    /// Unix timestamp
200    pub timestamp: u64,
201    /// Memo
202    pub memo: Option<String>,
203    /// User-defined metadata
204    pub metadata: HashMap<String, String>,
205    /// Quote ID if this is a mint or melt transaction
206    pub quote_id: Option<String>,
207}
208
209impl Transaction {
210    /// Transaction ID
211    pub fn id(&self) -> TransactionId {
212        TransactionId::new(self.ys.clone())
213    }
214
215    /// Check if transaction matches conditions
216    pub fn matches_conditions(
217        &self,
218        mint_url: &Option<MintUrl>,
219        direction: &Option<TransactionDirection>,
220        unit: &Option<CurrencyUnit>,
221    ) -> bool {
222        if let Some(mint_url) = mint_url {
223            if &self.mint_url != mint_url {
224                return false;
225            }
226        }
227        if let Some(direction) = direction {
228            if &self.direction != direction {
229                return false;
230            }
231        }
232        if let Some(unit) = unit {
233            if &self.unit != unit {
234                return false;
235            }
236        }
237        true
238    }
239}
240
241impl PartialOrd for Transaction {
242    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
243        Some(self.cmp(other))
244    }
245}
246
247impl Ord for Transaction {
248    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
249        self.timestamp.cmp(&other.timestamp).reverse()
250    }
251}
252
253/// Transaction Direction
254#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub enum TransactionDirection {
256    /// Incoming transaction (i.e., receive or mint)
257    Incoming,
258    /// Outgoing transaction (i.e., send or melt)
259    Outgoing,
260}
261
262impl std::fmt::Display for TransactionDirection {
263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264        match self {
265            TransactionDirection::Incoming => write!(f, "Incoming"),
266            TransactionDirection::Outgoing => write!(f, "Outgoing"),
267        }
268    }
269}
270
271impl FromStr for TransactionDirection {
272    type Err = Error;
273
274    fn from_str(value: &str) -> Result<Self, Self::Err> {
275        match value {
276            "Incoming" => Ok(Self::Incoming),
277            "Outgoing" => Ok(Self::Outgoing),
278            _ => Err(Error::InvalidTransactionDirection),
279        }
280    }
281}
282
283/// Transaction ID
284#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
285#[serde(transparent)]
286pub struct TransactionId([u8; 32]);
287
288impl TransactionId {
289    /// Create new [`TransactionId`]
290    pub fn new(ys: Vec<PublicKey>) -> Self {
291        let mut ys = ys;
292        ys.sort();
293        let mut hasher = sha256::Hash::engine();
294        for y in ys {
295            hasher.input(&y.to_bytes());
296        }
297        let hash = sha256::Hash::from_engine(hasher);
298        Self(hash.to_byte_array())
299    }
300
301    /// From proofs
302    pub fn from_proofs(proofs: Proofs) -> Result<Self, nut00::Error> {
303        let ys = proofs
304            .iter()
305            .map(|proof| proof.y())
306            .collect::<Result<Vec<PublicKey>, nut00::Error>>()?;
307        Ok(Self::new(ys))
308    }
309
310    /// From bytes
311    pub fn from_bytes(bytes: [u8; 32]) -> Self {
312        Self(bytes)
313    }
314
315    /// From hex string
316    pub fn from_hex(value: &str) -> Result<Self, Error> {
317        let bytes = hex::decode(value)?;
318        if bytes.len() != 32 {
319            return Err(Error::InvalidTransactionId);
320        }
321        let mut array = [0u8; 32];
322        array.copy_from_slice(&bytes);
323        Ok(Self(array))
324    }
325
326    /// From slice
327    pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
328        if slice.len() != 32 {
329            return Err(Error::InvalidTransactionId);
330        }
331        let mut array = [0u8; 32];
332        array.copy_from_slice(slice);
333        Ok(Self(array))
334    }
335
336    /// Get inner value
337    pub fn as_bytes(&self) -> &[u8; 32] {
338        &self.0
339    }
340
341    /// Get inner value as slice
342    pub fn as_slice(&self) -> &[u8] {
343        &self.0
344    }
345}
346
347impl std::fmt::Display for TransactionId {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        write!(f, "{}", hex::encode(self.0))
350    }
351}
352
353impl FromStr for TransactionId {
354    type Err = Error;
355
356    fn from_str(value: &str) -> Result<Self, Self::Err> {
357        Self::from_hex(value)
358    }
359}
360
361impl TryFrom<Proofs> for TransactionId {
362    type Error = nut00::Error;
363
364    fn try_from(proofs: Proofs) -> Result<Self, Self::Error> {
365        Self::from_proofs(proofs)
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_transaction_id_from_hex() {
375        let hex_str = "a1b2c3d4e5f60718293a0b1c2d3e4f506172839a0b1c2d3e4f506172839a0b1c";
376        let transaction_id = TransactionId::from_hex(hex_str).unwrap();
377        assert_eq!(transaction_id.to_string(), hex_str);
378    }
379
380    #[test]
381    fn test_transaction_id_from_hex_empty_string() {
382        let hex_str = "";
383        let res = TransactionId::from_hex(hex_str);
384        assert!(matches!(res, Err(Error::InvalidTransactionId)));
385    }
386
387    #[test]
388    fn test_transaction_id_from_hex_longer_string() {
389        let hex_str = "a1b2c3d4e5f60718293a0b1c2d3e4f506172839a0b1c2d3e4f506172839a0b1ca1b2";
390        let res = TransactionId::from_hex(hex_str);
391        assert!(matches!(res, Err(Error::InvalidTransactionId)));
392    }
393}