acceptxmr 0.14.0

Accept monero in your application.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use std::{
    cmp::{self, max, Ordering},
    collections::HashMap,
    fmt,
    fmt::Display,
};

#[cfg(feature = "bincode")]
use bincode::{Decode, Encode};
use monero::cryptonote::subaddress;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

const PICONEROS_PER_XMR: u64 = 1_000_000_000_000;

/// Representation of an invoice. `Invoice`s are created by the
/// [`PaymentGateway`](crate::PaymentGateway).
///
/// `Invoice`s have an expiration block, after which they are considered
/// expired. However, note that the payment gateway by default will continue
/// updating invoices even after expiration.
///
/// To receive updates for a given `Invoice`, use a
/// [`Subscriber`](crate::pubsub::Subscriber).
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
pub struct Invoice {
    address: String,
    index: SubIndex,
    creation_height: u64,
    amount_requested: u64,
    pub(crate) amount_paid: u64,
    /// The height at which the `Invoice` was fully paid. Will be `None`
    /// if not yet fully paid, or if the required XMR is still in the
    /// txpool (which has no height).
    pub(crate) paid_height: Option<u64>,
    confirmations_required: u64,
    pub(crate) current_height: u64,
    expiration_height: u64,
    pub(crate) transfers: Vec<Transfer>,
    pub(crate) description: String,
}

impl Invoice {
    pub(crate) fn new(
        address: String,
        index: SubIndex,
        creation_height: u64,
        amount_requested: u64,
        confirmations_required: u64,
        expiration_in: u64,
        description: String,
    ) -> Invoice {
        let expiration_height = creation_height + expiration_in;
        Invoice {
            address,
            index,
            creation_height,
            amount_requested,
            amount_paid: 0,
            paid_height: None,
            confirmations_required,
            current_height: 0,
            expiration_height,
            transfers: Vec::new(),
            description,
        }
    }

    /// Returns a URI containing the address and amount due as a `String`. For
    /// example:
    ///
    /// ```no run
    /// "monero:4A1WSBQdCbUCqt3DaGfmqVFchXScF43M6c5r4B6JXT3dUwuALncU9XTEnRPmUMcB3c16kVP9Y7thFLCJ5BaMW3UmSy93w3w?tx_amount=0.001"
    /// ```
    ///
    /// Monero URIs can be thought of as fancy addresses that pre-fill the
    /// amount field for the user (and sometimes the description field as
    /// well). They are supported by all major wallets.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn uri(&self) -> String {
        let piconeros_due = self.amount_requested.saturating_sub(self.amount_paid);
        let whole_xmr_due = piconeros_due / PICONEROS_PER_XMR;
        let fractional_xmr_due =
            (piconeros_due % PICONEROS_PER_XMR) as f64 / PICONEROS_PER_XMR as f64;
        format!(
            "monero:{}?tx_amount={}.{}",
            &self.address,
            whole_xmr_due,
            fractional_xmr_due.to_string().trim_start_matches("0.")
        )
    }

    /// Returns `true` if the `Invoice` has received the required number of
    /// confirmations.
    #[must_use]
    pub fn is_confirmed(&self) -> bool {
        self.confirmations().map_or(false, |confirmations| {
            confirmations >= self.confirmations_required
        })
    }

    /// Returns `true` if the `Invoice` has been paid in full (regadless of
    /// whether all required confirmations have been received).
    #[must_use]
    pub fn is_paid(&self) -> bool {
        self.amount_paid >= self.amount_requested
    }

    /// Returns `true` if the `Invoice`'s current block is greater than or equal
    /// to its expiration block.
    #[must_use]
    pub fn is_expired(&self) -> bool {
        // At or passed the expiration block.
        self.current_height >= self.expiration_height
    }

    /// Returns the base 58 encoded subaddress of this `Invoice`.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }

    /// Returns the ID of this invoice.
    #[must_use]
    pub fn id(&self) -> InvoiceId {
        InvoiceId {
            sub_index: self.index,
            creation_height: self.creation_height,
        }
    }

    /// Returns the [subaddress index](SubIndex) of this `Invoice`.
    #[must_use]
    pub fn index(&self) -> SubIndex {
        self.index
    }

    /// Returns the blockchain height at which the `Invoice` was created.
    #[must_use]
    pub fn creation_height(&self) -> u64 {
        self.creation_height
    }

    /// Returns the amount of monero requested in piconeros.
    #[must_use]
    pub fn amount_requested(&self) -> u64 {
        self.amount_requested
    }

    /// Returns the amount of monero paid in piconeros.
    #[must_use]
    pub fn amount_paid(&self) -> u64 {
        self.amount_paid
    }

    /// Returns the amount of monero requested in XMR.
    ///
    /// Note that rounding may occur because the precision of `f64` is
    /// insufficient for representing large amounts of XMR out to many decimal
    /// places. If accuracy is desired,
    /// [`amount_requested()`](#method.amount_requested) should be preferred.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// # use std::time::Duration;
    /// #
    /// # use acceptxmr::{PaymentGatewayBuilder, storage::stores::InMemory};
    /// #
    /// # let store = InMemory::new();
    /// #
    /// # let private_view_key = "ad2093a5705b9f33e6f0f0c1bc1f5f639c756cdfc168c8f2ac6127ccbdab3a03";
    /// # let primary_address = "4613YiHLM6JMH4zejMB2zJY5TwQCxL8p65ufw8kBP5yxX9itmuGLqp1dS4tkVoTxjyH3aYhYNrtGHbQzJQP5bFus3KHVdmf";
    /// #
    /// # let payment_gateway = PaymentGatewayBuilder::new(private_view_key.to_string(), primary_address.to_string(), store)
    /// #   .build()
    /// #   .await?;
    /// #
    /// // Create a new `Invoice` for 1 millinero.
    /// let invoice_id = payment_gateway.new_invoice(1_000_000_000, 3, 5, "for pizza".to_string()).await?;
    /// let small_invoice = payment_gateway.get_invoice(invoice_id).await?.expect("invoice ID not found");
    ///
    /// // One millinero, as expected.
    /// assert_eq!(small_invoice.xmr_requested(), 0.001);
    ///
    /// // Create a new `Invoice` for 18446744.073709551615 XMR.
    /// let invoice_id = payment_gateway.new_invoice(18_446_744_073_709_551_615, 3, 5, "for lambo".to_string()).await?;
    /// let large_invoice = payment_gateway.get_invoice(invoice_id).await?.expect("invoice ID not found");
    ///
    /// // The large value has been rounded slightly due to f64 precision limitations.
    /// assert_eq!(large_invoice.xmr_requested(), 18446744.07370955);
    /// #   Ok(())
    /// # }
    /// ```
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn xmr_requested(&self) -> f64 {
        let whole_xmr = self.amount_requested / PICONEROS_PER_XMR;
        let fractional_xmr =
            (self.amount_requested % PICONEROS_PER_XMR) as f64 / PICONEROS_PER_XMR as f64;
        whole_xmr as f64 + fractional_xmr
    }

    /// Returns the amount of monero paid in XMR.
    ///
    /// Note that rounding may occur because the precision of `f64` is
    /// insufficient for representing large amounts of XMR out to many decimal
    /// places. If accuracy is desired, [`amount_paid()`](#method.amount_paid)
    /// should be preferred.
    ///
    /// For an example of possible rounding error, see
    /// [`xmr_requested()`](#method.xmr_requested)
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn xmr_paid(&self) -> f64 {
        let whole_xmr = self.amount_paid / PICONEROS_PER_XMR;
        let fractional_xmr =
            (self.amount_paid % PICONEROS_PER_XMR) as f64 / PICONEROS_PER_XMR as f64;
        whole_xmr as f64 + fractional_xmr
    }

    /// Returns the number of confirmations this `Invoice` requires before it is
    /// considered fully confirmed.
    #[must_use]
    pub fn confirmations_required(&self) -> u64 {
        self.confirmations_required
    }

    /// Returns the number of confirmations this `Invoice` has received since it
    /// was paid in full. Returns `None` if the `Invoice` has not yet been paid
    /// in full.
    #[must_use]
    pub fn confirmations(&self) -> Option<u64> {
        if self.amount_paid >= self.amount_requested {
            self.paid_height.map_or(Some(0), |paid_at| {
                Some(self.current_height.saturating_sub(paid_at))
            })
        } else {
            None
        }
    }

    /// Returns the last daemon height at which this `Invoice` was updated.
    ///
    /// Returns `0` if the `Invoice` has not yet been updated.
    #[must_use]
    pub fn current_height(&self) -> u64 {
        self.current_height
    }

    /// Returns the daemon height at which this `Invoice` will expire.
    #[must_use]
    pub fn expiration_height(&self) -> u64 {
        self.expiration_height
    }

    /// Returns the number of blocks before expiration.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// # use acceptxmr::{PaymentGatewayBuilder, storage::stores::InMemory};
    /// #
    /// # let private_view_key = "ad2093a5705b9f33e6f0f0c1bc1f5f639c756cdfc168c8f2ac6127ccbdab3a03";
    /// # let primary_address = "4613YiHLM6JMH4zejMB2zJY5TwQCxL8p65ufw8kBP5yxX9itmuGLqp1dS4tkVoTxjyH3aYhYNrtGHbQzJQP5bFus3KHVdmf";
    /// #
    /// # let store = InMemory::new();
    /// #
    /// # let payment_gateway = PaymentGatewayBuilder::new(private_view_key.to_string(), primary_address.to_string(), store)
    /// #    .build()
    /// #    .await?;
    /// #
    /// # payment_gateway.run().await?;
    /// #
    /// // Create a new `Invoice` requiring 3 confirmations, and expiring in 5 blocks.
    /// let invoice_id = payment_gateway.new_invoice(10000, 3, 5, "for pizza".to_string()).await?;
    /// let mut subscriber = payment_gateway.subscribe(invoice_id).expect("invoice ID not found");
    /// let invoice = subscriber.recv().await.expect("invoice update not received");
    ///
    /// assert_eq!(invoice.expiration_in(), 5);
    /// #   Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn expiration_in(&self) -> u64 {
        let height = max(self.creation_height, self.current_height);
        self.expiration_height.saturating_sub(height)
    }

    /// Returns the description of this invoice.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }
}

impl fmt::Display for Invoice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let confirmations = match self.confirmations() {
            Some(height) => height.to_string(),
            None => "N/A".to_string(),
        };
        let mut str = format!(
            "Index {}: \
            \nPaid: {}/{} \
            \nConfirmations: {} \
            \nStarted at: {} \
            \nCurrent height: {} \
            \nExpiration at: {} \
            \nDescription: \"{}\" \
            \ntransfers: \
            \n[",
            self.index,
            monero::Amount::from_pico(self.amount_paid).as_xmr(),
            monero::Amount::from_pico(self.amount_requested).as_xmr(),
            confirmations,
            self.creation_height,
            self.current_height,
            self.expiration_height,
            self.description,
        );
        for transfer in &self.transfers {
            let height = match transfer.height {
                Some(h) => h.to_string(),
                None => "N/A".to_string(),
            };
            str.push_str(&format!(
                "\n   {{Amount: {}, Height: {:?}}}",
                transfer.amount, height
            ));
        }
        if self.transfers.is_empty() {
            str.push(']');
        } else {
            str.push_str("\n]");
        }
        write!(f, "{str}")
    }
}

/// This custom `PartialEq` implementation is necessary so that the order of
/// `Transfer`s can be ignored while comparing `Invoice`s.
impl PartialEq for Invoice {
    fn eq(&self, other: &Self) -> bool {
        let mut lhs_transfers = HashMap::new();
        let mut rhs_transfers = HashMap::new();
        for i in &self.transfers {
            *lhs_transfers.entry(i).or_insert(0) += 1;
        }
        for i in &other.transfers {
            *rhs_transfers.entry(i).or_insert(0) += 1;
        }

        lhs_transfers == rhs_transfers
            && self.address == other.address
            && self.index == other.index
            && self.creation_height == other.creation_height
            && self.amount_requested == other.amount_requested
            && self.amount_paid == other.amount_paid
            && self.paid_height == other.paid_height
            && self.confirmations_required == other.confirmations_required
            && self.current_height == other.current_height
            && self.expiration_height == other.expiration_height
            && self.description == other.description
    }
}

/// An invoice ID uniquely identifies a given invoice by the combination of its
/// subaddress index and creation height.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
pub struct InvoiceId {
    /// The [subaddress index](SubIndex) of the invoice.
    pub sub_index: SubIndex,
    /// The creation height of the invoice.
    pub creation_height: u64,
}

impl InvoiceId {
    /// Create a new `InvoiceId` from subaddress index and creation height.
    #[must_use]
    pub fn new(sub_index: SubIndex, creation_height: u64) -> InvoiceId {
        InvoiceId {
            sub_index,
            creation_height,
        }
    }
}

impl Ord for InvoiceId {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.sub_index.cmp(&other.sub_index) {
            Ordering::Equal => self.creation_height.cmp(&other.creation_height),
            Ordering::Greater => Ordering::Greater,
            Ordering::Less => Ordering::Less,
        }
    }
}

impl PartialOrd for InvoiceId {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Display for InvoiceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({},{})", self.sub_index, self.creation_height)
    }
}

/// A subaddress index.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
pub struct SubIndex {
    /// Subaddress major index.
    pub major: u32,
    /// Subaddress minor index.
    pub minor: u32,
}

impl SubIndex {
    /// Create a new subaddress index from major and minor indexes.
    #[must_use]
    pub fn new(major: u32, minor: u32) -> SubIndex {
        SubIndex { major, minor }
    }
}

impl Ord for SubIndex {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.major.cmp(&other.major) {
            Ordering::Equal => self.minor.cmp(&other.minor),
            Ordering::Greater => Ordering::Greater,
            Ordering::Less => Ordering::Less,
        }
    }
}

impl PartialOrd for SubIndex {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for SubIndex {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}/{}", self.major, self.minor)
    }
}

impl From<subaddress::Index> for SubIndex {
    fn from(index: subaddress::Index) -> SubIndex {
        SubIndex {
            major: index.major,
            minor: index.minor,
        }
    }
}

impl From<SubIndex> for subaddress::Index {
    fn from(index: SubIndex) -> subaddress::Index {
        subaddress::Index {
            major: index.major,
            minor: index.minor,
        }
    }
}

/// A `Transfer` represents a sum of owned outputs at a given height. When part
/// of an `Invoice`, it specifically represents the sum of owned outputs for
/// that invoice's subaddress, at a given height.
#[derive(Debug, Clone, PartialEq, Copy, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
pub(crate) struct Transfer {
    /// Amount transferred in piconeros.
    pub(crate) amount: u64,
    /// Block height of the transfer, or None if the outputs are in the txpool.
    pub(crate) height: Option<u64>,
}

impl Transfer {
    pub(crate) fn new(amount: u64, height: Option<u64>) -> Transfer {
        Transfer { amount, height }
    }

    /// Compare two transfers by height. Newer is greater.
    pub(crate) fn cmp_by_height(&self, other: &Self) -> cmp::Ordering {
        match self.height {
            Some(height) => match other.height {
                Some(other_height) => height.cmp(&other_height),
                None => cmp::Ordering::Less,
            },
            None => match other.height {
                Some(_) => cmp::Ordering::Greater,
                None => cmp::Ordering::Equal,
            },
        }
    }
}

impl From<InvoiceId> for u128 {
    fn from(value: InvoiceId) -> Self {
        let SubIndex { major, minor } = value.sub_index;
        let height = value.creation_height;
        let mut bytes = [0u8; 16];
        bytes[..4].copy_from_slice(&major.to_be_bytes());
        bytes[4..8].copy_from_slice(&minor.to_be_bytes());
        bytes[8..16].copy_from_slice(&height.to_be_bytes());
        u128::from_be_bytes(bytes)
    }
}

impl From<u128> for InvoiceId {
    fn from(value: u128) -> Self {
        let bytes = value.to_be_bytes();
        let mut major_index_bytes = [0u8; 4];
        let mut minor_index_bytes = [0u8; 4];
        let mut height_bytes = [0u8; 8];
        major_index_bytes.copy_from_slice(&bytes[..4]);
        minor_index_bytes.copy_from_slice(&bytes[4..8]);
        height_bytes.copy_from_slice(&bytes[8..16]);
        let sub_index = SubIndex {
            major: u32::from_be_bytes(major_index_bytes),
            minor: u32::from_be_bytes(minor_index_bytes),
        };
        InvoiceId {
            sub_index,
            creation_height: u64::from_be_bytes(height_bytes),
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
#[allow(clippy::panic)]
mod tests {
    use test_case::test_case;
    use testing_utils::init_logger;

    use crate::{Invoice, InvoiceId, SubIndex};

    #[test_case(1, 0 => "0.000000000001".to_string(); "small")]
    #[test_case(u64::MAX, 0 => "18446744.073709551615".to_string(); "big")]
    #[test_case(1, 1 => "0.0"; "zero")]
    #[test_case(2_460_000_000_000, 1_230_000_000_000 => "1.23"; "partially paid")]
    fn payment_request(requested: u64, paid: u64) -> String {
        // Setup.
        init_logger();

        let mut invoice = Invoice::new(
            "testAddress".to_string(),
            SubIndex::new(0, 1),
            0,
            requested,
            5,
            10,
            "test_description".to_string(),
        );
        invoice.amount_paid = paid;

        let uri = invoice.uri();
        let amount = uri
            .strip_prefix("monero:testAddress?tx_amount=")
            .expect("unexpected URI format");

        amount.to_string()
    }

    #[test_case(1 => "0.000000000001".to_string(); "small")]
    #[test_case(u64::MAX => "18446744.07370955".to_string(); "big")]
    #[test_case(0 => "0".to_string(); "zero")]
    fn xmr_requested(requested: u64) -> String {
        // Setup.
        init_logger();

        let invoice = Invoice::new(
            "testAddress".to_string(),
            SubIndex::new(0, 1),
            0,
            requested,
            5,
            10,
            "test_description".to_string(),
        );
        invoice.xmr_requested().to_string()
    }

    #[test]
    fn expires_in() {
        init_logger();

        let invoice = Invoice::new(
            "testAddress".to_string(),
            SubIndex::new(0, 1),
            12345,
            1,
            5,
            10,
            "test_description".to_string(),
        );

        assert_eq!(invoice.expiration_in(), 10);
    }

    #[test_case(InvoiceId::new(SubIndex::new(0, 0), 0), 0)]
    fn invoice_id_integer_roundtrip(invoice_id: InvoiceId, expected_int: u128) {
        let actual_int: u128 = invoice_id.into();
        assert_eq!(actual_int, expected_int);

        let rebuilt_invoice_id: InvoiceId = actual_int.into();
        assert_eq!(rebuilt_invoice_id, invoice_id);
    }
}