Invoice building tests
[rust-lightning] / lightning / src / offers / refund.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Data structures and encoding for refunds.
11 //!
12 //! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
13 //! directly to the customer. The recipient responds with an [`Invoice`] to be paid.
14 //!
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
16 //!
17 //! [`Invoice`]: crate::offers::invoice::Invoice
18 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19 //! [`Offer`]: crate::offers::offer::Offer
20 //!
21 //! ```ignore
22 //! extern crate bitcoin;
23 //! extern crate core;
24 //! extern crate lightning;
25 //!
26 //! use core::convert::TryFrom;
27 //! use core::time::Duration;
28 //!
29 //! use bitcoin::network::constants::Network;
30 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
31 //! use lightning::offers::parse::ParseError;
32 //! use lightning::offers::refund::{Refund, RefundBuilder};
33 //! use lightning::util::ser::{Readable, Writeable};
34 //!
35 //! # use lightning::onion_message::BlindedPath;
36 //! # #[cfg(feature = "std")]
37 //! # use std::time::SystemTime;
38 //! #
39 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
40 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
41 //! #
42 //! # #[cfg(feature = "std")]
43 //! # fn build() -> Result<(), ParseError> {
44 //! let secp_ctx = Secp256k1::new();
45 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
46 //! let pubkey = PublicKey::from(keys);
47 //!
48 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
49 //! let refund = RefundBuilder::new("coffee, large".to_string(), vec![1; 32], pubkey, 20_000)?
50 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
51 //!     .issuer("Foo Bar".to_string())
52 //!     .path(create_blinded_path())
53 //!     .path(create_another_blinded_path())
54 //!     .chain(Network::Bitcoin)
55 //!     .payer_note("refund for order #12345".to_string())
56 //!     .build()?;
57 //!
58 //! // Encode as a bech32 string for use in a QR code.
59 //! let encoded_refund = refund.to_string();
60 //!
61 //! // Parse from a bech32 string after scanning from a QR code.
62 //! let refund = encoded_refund.parse::<Refund>()?;
63 //!
64 //! // Encode refund as raw bytes.
65 //! let mut bytes = Vec::new();
66 //! refund.write(&mut bytes).unwrap();
67 //!
68 //! // Decode raw bytes into an refund.
69 //! let refund = Refund::try_from(bytes)?;
70 //! # Ok(())
71 //! # }
72 //! ```
73
74 use bitcoin::blockdata::constants::ChainHash;
75 use bitcoin::network::constants::Network;
76 use bitcoin::secp256k1::PublicKey;
77 use core::convert::TryFrom;
78 use core::str::FromStr;
79 use core::time::Duration;
80 use crate::io;
81 use crate::ln::PaymentHash;
82 use crate::ln::features::InvoiceRequestFeatures;
83 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
84 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
85 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
86 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
87 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
88 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
89 use crate::onion_message::BlindedPath;
90 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
91 use crate::util::string::PrintableString;
92
93 use crate::prelude::*;
94
95 #[cfg(feature = "std")]
96 use std::time::SystemTime;
97
98 /// Builds a [`Refund`] for the "offer for money" flow.
99 ///
100 /// See [module-level documentation] for usage.
101 ///
102 /// [module-level documentation]: self
103 pub struct RefundBuilder {
104         refund: RefundContents,
105 }
106
107 impl RefundBuilder {
108         /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
109         /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
110         ///
111         /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
112         /// [`Refund::amount_msats`].
113         pub fn new(
114                 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
115         ) -> Result<Self, SemanticError> {
116                 if amount_msats > MAX_VALUE_MSAT {
117                         return Err(SemanticError::InvalidAmount);
118                 }
119
120                 let refund = RefundContents {
121                         payer: PayerContents(metadata), metadata: None, description, absolute_expiry: None,
122                         issuer: None, paths: None, chain: None, amount_msats,
123                         features: InvoiceRequestFeatures::empty(), payer_id, payer_note: None,
124                 };
125
126                 Ok(RefundBuilder { refund })
127         }
128
129         /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
130         /// already passed is valid and can be checked for using [`Refund::is_expired`].
131         ///
132         /// Successive calls to this method will override the previous setting.
133         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
134                 self.refund.absolute_expiry = Some(absolute_expiry);
135                 self
136         }
137
138         /// Sets the [`Refund::issuer`].
139         ///
140         /// Successive calls to this method will override the previous setting.
141         pub fn issuer(mut self, issuer: String) -> Self {
142                 self.refund.issuer = Some(issuer);
143                 self
144         }
145
146         /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
147         /// by private channels or if [`Refund::payer_id`] is not a public node id.
148         ///
149         /// Successive calls to this method will add another blinded path. Caller is responsible for not
150         /// adding duplicate paths.
151         pub fn path(mut self, path: BlindedPath) -> Self {
152                 self.refund.paths.get_or_insert_with(Vec::new).push(path);
153                 self
154         }
155
156         /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
157         /// called, [`Network::Bitcoin`] is assumed.
158         ///
159         /// Successive calls to this method will override the previous setting.
160         pub fn chain(mut self, network: Network) -> Self {
161                 self.refund.chain = Some(ChainHash::using_genesis_block(network));
162                 self
163         }
164
165         /// Sets the [`Refund::payer_note`].
166         ///
167         /// Successive calls to this method will override the previous setting.
168         pub fn payer_note(mut self, payer_note: String) -> Self {
169                 self.refund.payer_note = Some(payer_note);
170                 self
171         }
172
173         /// Builds a [`Refund`] after checking for valid semantics.
174         pub fn build(mut self) -> Result<Refund, SemanticError> {
175                 if self.refund.chain() == self.refund.implied_chain() {
176                         self.refund.chain = None;
177                 }
178
179                 let mut bytes = Vec::new();
180                 self.refund.write(&mut bytes).unwrap();
181
182                 Ok(Refund {
183                         bytes,
184                         contents: self.refund,
185                 })
186         }
187 }
188
189 #[cfg(test)]
190 impl RefundBuilder {
191         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
192                 self.refund.features = features;
193                 self
194         }
195 }
196
197 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
198 ///
199 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
200 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
201 /// bitcoin ATM.
202 ///
203 /// [`Invoice`]: crate::offers::invoice::Invoice
204 /// [`Offer`]: crate::offers::offer::Offer
205 #[derive(Clone, Debug)]
206 pub struct Refund {
207         pub(super) bytes: Vec<u8>,
208         pub(super) contents: RefundContents,
209 }
210
211 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
212 ///
213 /// [`Invoice`]: crate::offers::invoice::Invoice
214 #[derive(Clone, Debug)]
215 pub(super) struct RefundContents {
216         payer: PayerContents,
217         // offer fields
218         metadata: Option<Vec<u8>>,
219         description: String,
220         absolute_expiry: Option<Duration>,
221         issuer: Option<String>,
222         paths: Option<Vec<BlindedPath>>,
223         // invoice_request fields
224         chain: Option<ChainHash>,
225         amount_msats: u64,
226         features: InvoiceRequestFeatures,
227         payer_id: PublicKey,
228         payer_note: Option<String>,
229 }
230
231 impl Refund {
232         /// A complete description of the purpose of the refund. Intended to be displayed to the user
233         /// but with the caveat that it has not been verified in any way.
234         pub fn description(&self) -> PrintableString {
235                 PrintableString(&self.contents.description)
236         }
237
238         /// Duration since the Unix epoch when an invoice should no longer be sent.
239         ///
240         /// If `None`, the refund does not expire.
241         pub fn absolute_expiry(&self) -> Option<Duration> {
242                 self.contents.absolute_expiry
243         }
244
245         /// Whether the refund has expired.
246         #[cfg(feature = "std")]
247         pub fn is_expired(&self) -> bool {
248                 self.contents.is_expired()
249         }
250
251         /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
252         /// displayed to the user but with the caveat that it has not been verified in any way.
253         pub fn issuer(&self) -> Option<PrintableString> {
254                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
255         }
256
257         /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
258         /// privacy by obfuscating its node id.
259         pub fn paths(&self) -> &[BlindedPath] {
260                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
261         }
262
263         /// An unpredictable series of bytes, typically containing information about the derivation of
264         /// [`payer_id`].
265         ///
266         /// [`payer_id`]: Self::payer_id
267         pub fn metadata(&self) -> &[u8] {
268                 &self.contents.payer.0
269         }
270
271         /// A chain that the refund is valid for.
272         pub fn chain(&self) -> ChainHash {
273                 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
274         }
275
276         /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
277         ///
278         /// [`chain`]: Self::chain
279         pub fn amount_msats(&self) -> u64 {
280                 self.contents.amount_msats
281         }
282
283         /// Features pertaining to requesting an invoice.
284         pub fn features(&self) -> &InvoiceRequestFeatures {
285                 &self.contents.features
286         }
287
288         /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
289         /// transient pubkey.
290         ///
291         /// [`paths`]: Self::paths
292         pub fn payer_id(&self) -> PublicKey {
293                 self.contents.payer_id
294         }
295
296         /// Payer provided note to include in the invoice.
297         pub fn payer_note(&self) -> Option<PrintableString> {
298                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
299         }
300
301         /// Creates an [`Invoice`] for the refund with the given required fields.
302         ///
303         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
304         /// calling this method in `std` builds. For `no-std` builds, a final [`Duration`] parameter
305         /// must be given, which is used to set [`Invoice::created_at`] since [`std::time::SystemTime`]
306         /// is not available.
307         ///
308         /// The caller is expected to remember the preimage of `payment_hash` in order to
309         /// claim a payment for the invoice.
310         ///
311         /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
312         /// offer, which does have a `signing_pubkey`.
313         ///
314         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
315         /// must contain one or more elements.
316         ///
317         /// Errors if the request contains unknown required features.
318         ///
319         /// [`Invoice`]: crate::offers::invoice::Invoice
320         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
321         pub fn respond_with(
322                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
323                 signing_pubkey: PublicKey,
324                 #[cfg(any(test, not(feature = "std")))]
325                 created_at: Duration
326         ) -> Result<InvoiceBuilder, SemanticError> {
327                 if self.features().requires_unknown_bits() {
328                         return Err(SemanticError::UnknownRequiredFeatures);
329                 }
330
331                 #[cfg(all(not(test), feature = "std"))]
332                 let created_at = std::time::SystemTime::now()
333                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
334                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
335
336                 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
337         }
338
339         #[cfg(test)]
340         fn as_tlv_stream(&self) -> RefundTlvStreamRef {
341                 self.contents.as_tlv_stream()
342         }
343 }
344
345 impl AsRef<[u8]> for Refund {
346         fn as_ref(&self) -> &[u8] {
347                 &self.bytes
348         }
349 }
350
351 impl RefundContents {
352         #[cfg(feature = "std")]
353         pub(super) fn is_expired(&self) -> bool {
354                 match self.absolute_expiry {
355                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
356                                 Ok(elapsed) => elapsed > seconds_from_epoch,
357                                 Err(_) => false,
358                         },
359                         None => false,
360                 }
361         }
362
363         pub(super) fn chain(&self) -> ChainHash {
364                 self.chain.unwrap_or_else(|| self.implied_chain())
365         }
366
367         pub fn implied_chain(&self) -> ChainHash {
368                 ChainHash::using_genesis_block(Network::Bitcoin)
369         }
370
371         pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
372                 let payer = PayerTlvStreamRef {
373                         metadata: Some(&self.payer.0),
374                 };
375
376                 let offer = OfferTlvStreamRef {
377                         chains: None,
378                         metadata: self.metadata.as_ref(),
379                         currency: None,
380                         amount: None,
381                         description: Some(&self.description),
382                         features: None,
383                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
384                         paths: self.paths.as_ref(),
385                         issuer: self.issuer.as_ref(),
386                         quantity_max: None,
387                         node_id: None,
388                 };
389
390                 let features = {
391                         if self.features == InvoiceRequestFeatures::empty() { None }
392                         else { Some(&self.features) }
393                 };
394
395                 let invoice_request = InvoiceRequestTlvStreamRef {
396                         chain: self.chain.as_ref(),
397                         amount: Some(self.amount_msats),
398                         features,
399                         quantity: None,
400                         payer_id: Some(&self.payer_id),
401                         payer_note: self.payer_note.as_ref(),
402                 };
403
404                 (payer, offer, invoice_request)
405         }
406 }
407
408 impl Writeable for Refund {
409         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
410                 WithoutLength(&self.bytes).write(writer)
411         }
412 }
413
414 impl Writeable for RefundContents {
415         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
416                 self.as_tlv_stream().write(writer)
417         }
418 }
419
420 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
421
422 type RefundTlvStreamRef<'a> = (
423         PayerTlvStreamRef<'a>,
424         OfferTlvStreamRef<'a>,
425         InvoiceRequestTlvStreamRef<'a>,
426 );
427
428 impl SeekReadable for RefundTlvStream {
429         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
430                 let payer = SeekReadable::read(r)?;
431                 let offer = SeekReadable::read(r)?;
432                 let invoice_request = SeekReadable::read(r)?;
433
434                 Ok((payer, offer, invoice_request))
435         }
436 }
437
438 impl Bech32Encode for Refund {
439         const BECH32_HRP: &'static str = "lnr";
440 }
441
442 impl FromStr for Refund {
443         type Err = ParseError;
444
445         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
446                 Refund::from_bech32_str(s)
447         }
448 }
449
450 impl TryFrom<Vec<u8>> for Refund {
451         type Error = ParseError;
452
453         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
454                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
455                 let ParsedMessage { bytes, tlv_stream } = refund;
456                 let contents = RefundContents::try_from(tlv_stream)?;
457
458                 Ok(Refund { bytes, contents })
459         }
460 }
461
462 impl TryFrom<RefundTlvStream> for RefundContents {
463         type Error = SemanticError;
464
465         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
466                 let (
467                         PayerTlvStream { metadata: payer_metadata },
468                         OfferTlvStream {
469                                 chains, metadata, currency, amount: offer_amount, description,
470                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
471                         },
472                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
473                 ) = tlv_stream;
474
475                 let payer = match payer_metadata {
476                         None => return Err(SemanticError::MissingPayerMetadata),
477                         Some(metadata) => PayerContents(metadata),
478                 };
479
480                 if chains.is_some() {
481                         return Err(SemanticError::UnexpectedChain);
482                 }
483
484                 if currency.is_some() || offer_amount.is_some() {
485                         return Err(SemanticError::UnexpectedAmount);
486                 }
487
488                 let description = match description {
489                         None => return Err(SemanticError::MissingDescription),
490                         Some(description) => description,
491                 };
492
493                 if offer_features.is_some() {
494                         return Err(SemanticError::UnexpectedFeatures);
495                 }
496
497                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
498
499                 if quantity_max.is_some() {
500                         return Err(SemanticError::UnexpectedQuantity);
501                 }
502
503                 if node_id.is_some() {
504                         return Err(SemanticError::UnexpectedSigningPubkey);
505                 }
506
507                 let amount_msats = match amount {
508                         None => return Err(SemanticError::MissingAmount),
509                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
510                                 return Err(SemanticError::InvalidAmount);
511                         },
512                         Some(amount_msats) => amount_msats,
513                 };
514
515                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
516
517                 // TODO: Check why this isn't in the spec.
518                 if quantity.is_some() {
519                         return Err(SemanticError::UnexpectedQuantity);
520                 }
521
522                 let payer_id = match payer_id {
523                         None => return Err(SemanticError::MissingPayerId),
524                         Some(payer_id) => payer_id,
525                 };
526
527                 // TODO: Should metadata be included?
528                 Ok(RefundContents {
529                         payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
530                         features, payer_id, payer_note,
531                 })
532         }
533 }
534
535 impl core::fmt::Display for Refund {
536         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
537                 self.fmt_bech32_str(f)
538         }
539 }
540
541 #[cfg(test)]
542 mod tests {
543         use super::{Refund, RefundBuilder, RefundTlvStreamRef};
544
545         use bitcoin::blockdata::constants::ChainHash;
546         use bitcoin::network::constants::Network;
547         use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
548         use core::convert::TryFrom;
549         use core::time::Duration;
550         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
551         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
552         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
553         use crate::offers::offer::OfferTlvStreamRef;
554         use crate::offers::parse::{ParseError, SemanticError};
555         use crate::offers::payer::PayerTlvStreamRef;
556         use crate::onion_message::{BlindedHop, BlindedPath};
557         use crate::util::ser::{BigSize, Writeable};
558         use crate::util::string::PrintableString;
559
560         fn payer_pubkey() -> PublicKey {
561                 let secp_ctx = Secp256k1::new();
562                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()).public_key()
563         }
564
565         fn pubkey(byte: u8) -> PublicKey {
566                 let secp_ctx = Secp256k1::new();
567                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
568         }
569
570         fn privkey(byte: u8) -> SecretKey {
571                 SecretKey::from_slice(&[byte; 32]).unwrap()
572         }
573
574         trait ToBytes {
575                 fn to_bytes(&self) -> Vec<u8>;
576         }
577
578         impl<'a> ToBytes for RefundTlvStreamRef<'a> {
579                 fn to_bytes(&self) -> Vec<u8> {
580                         let mut buffer = Vec::new();
581                         self.write(&mut buffer).unwrap();
582                         buffer
583                 }
584         }
585
586         #[test]
587         fn builds_refund_with_defaults() {
588                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
589                         .build().unwrap();
590
591                 let mut buffer = Vec::new();
592                 refund.write(&mut buffer).unwrap();
593
594                 assert_eq!(refund.bytes, buffer.as_slice());
595                 assert_eq!(refund.metadata(), &[1; 32]);
596                 assert_eq!(refund.description(), PrintableString("foo"));
597                 assert_eq!(refund.absolute_expiry(), None);
598                 #[cfg(feature = "std")]
599                 assert!(!refund.is_expired());
600                 assert_eq!(refund.paths(), &[]);
601                 assert_eq!(refund.issuer(), None);
602                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
603                 assert_eq!(refund.amount_msats(), 1000);
604                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
605                 assert_eq!(refund.payer_id(), payer_pubkey());
606                 assert_eq!(refund.payer_note(), None);
607
608                 assert_eq!(
609                         refund.as_tlv_stream(),
610                         (
611                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
612                                 OfferTlvStreamRef {
613                                         chains: None,
614                                         metadata: None,
615                                         currency: None,
616                                         amount: None,
617                                         description: Some(&String::from("foo")),
618                                         features: None,
619                                         absolute_expiry: None,
620                                         paths: None,
621                                         issuer: None,
622                                         quantity_max: None,
623                                         node_id: None,
624                                 },
625                                 InvoiceRequestTlvStreamRef {
626                                         chain: None,
627                                         amount: Some(1000),
628                                         features: None,
629                                         quantity: None,
630                                         payer_id: Some(&payer_pubkey()),
631                                         payer_note: None,
632                                 },
633                         ),
634                 );
635
636                 if let Err(e) = Refund::try_from(buffer) {
637                         panic!("error parsing refund: {:?}", e);
638                 }
639         }
640
641         #[test]
642         fn fails_building_refund_with_invalid_amount() {
643                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
644                         Ok(_) => panic!("expected error"),
645                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
646                 }
647         }
648
649         #[test]
650         fn builds_refund_with_absolute_expiry() {
651                 let future_expiry = Duration::from_secs(u64::max_value());
652                 let past_expiry = Duration::from_secs(0);
653
654                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
655                         .absolute_expiry(future_expiry)
656                         .build()
657                         .unwrap();
658                 let (_, tlv_stream, _) = refund.as_tlv_stream();
659                 #[cfg(feature = "std")]
660                 assert!(!refund.is_expired());
661                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
662                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
663
664                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
665                         .absolute_expiry(future_expiry)
666                         .absolute_expiry(past_expiry)
667                         .build()
668                         .unwrap();
669                 let (_, tlv_stream, _) = refund.as_tlv_stream();
670                 #[cfg(feature = "std")]
671                 assert!(refund.is_expired());
672                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
673                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
674         }
675
676         #[test]
677         fn builds_refund_with_paths() {
678                 let paths = vec![
679                         BlindedPath {
680                                 introduction_node_id: pubkey(40),
681                                 blinding_point: pubkey(41),
682                                 blinded_hops: vec![
683                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
684                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
685                                 ],
686                         },
687                         BlindedPath {
688                                 introduction_node_id: pubkey(40),
689                                 blinding_point: pubkey(41),
690                                 blinded_hops: vec![
691                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
692                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
693                                 ],
694                         },
695                 ];
696
697                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
698                         .path(paths[0].clone())
699                         .path(paths[1].clone())
700                         .build()
701                         .unwrap();
702                 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
703                 assert_eq!(refund.paths(), paths.as_slice());
704                 assert_eq!(refund.payer_id(), pubkey(42));
705                 assert_ne!(pubkey(42), pubkey(44));
706                 assert_eq!(offer_tlv_stream.paths, Some(&paths));
707                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
708         }
709
710         #[test]
711         fn builds_refund_with_issuer() {
712                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
713                         .issuer("bar".into())
714                         .build()
715                         .unwrap();
716                 let (_, tlv_stream, _) = refund.as_tlv_stream();
717                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
718                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
719
720                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
721                         .issuer("bar".into())
722                         .issuer("baz".into())
723                         .build()
724                         .unwrap();
725                 let (_, tlv_stream, _) = refund.as_tlv_stream();
726                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
727                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
728         }
729
730         #[test]
731         fn builds_refund_with_chain() {
732                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
733                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
734
735                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
736                         .chain(Network::Bitcoin)
737                         .build().unwrap();
738                 let (_, _, tlv_stream) = refund.as_tlv_stream();
739                 assert_eq!(refund.chain(), mainnet);
740                 assert_eq!(tlv_stream.chain, None);
741
742                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
743                         .chain(Network::Testnet)
744                         .build().unwrap();
745                 let (_, _, tlv_stream) = refund.as_tlv_stream();
746                 assert_eq!(refund.chain(), testnet);
747                 assert_eq!(tlv_stream.chain, Some(&testnet));
748
749                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
750                         .chain(Network::Regtest)
751                         .chain(Network::Testnet)
752                         .build().unwrap();
753                 let (_, _, tlv_stream) = refund.as_tlv_stream();
754                 assert_eq!(refund.chain(), testnet);
755                 assert_eq!(tlv_stream.chain, Some(&testnet));
756         }
757
758         #[test]
759         fn builds_refund_with_payer_note() {
760                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
761                         .payer_note("bar".into())
762                         .build().unwrap();
763                 let (_, _, tlv_stream) = refund.as_tlv_stream();
764                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
765                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
766
767                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
768                         .payer_note("bar".into())
769                         .payer_note("baz".into())
770                         .build().unwrap();
771                 let (_, _, tlv_stream) = refund.as_tlv_stream();
772                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
773                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
774         }
775
776         #[test]
777         fn parses_refund_with_metadata() {
778                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
779                         .build().unwrap();
780                 if let Err(e) = refund.to_string().parse::<Refund>() {
781                         panic!("error parsing refund: {:?}", e);
782                 }
783
784                 let mut tlv_stream = refund.as_tlv_stream();
785                 tlv_stream.0.metadata = None;
786
787                 match Refund::try_from(tlv_stream.to_bytes()) {
788                         Ok(_) => panic!("expected error"),
789                         Err(e) => {
790                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
791                         },
792                 }
793         }
794
795         #[test]
796         fn parses_refund_with_description() {
797                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
798                         .build().unwrap();
799                 if let Err(e) = refund.to_string().parse::<Refund>() {
800                         panic!("error parsing refund: {:?}", e);
801                 }
802
803                 let mut tlv_stream = refund.as_tlv_stream();
804                 tlv_stream.1.description = None;
805
806                 match Refund::try_from(tlv_stream.to_bytes()) {
807                         Ok(_) => panic!("expected error"),
808                         Err(e) => {
809                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
810                         },
811                 }
812         }
813
814         #[test]
815         fn parses_refund_with_amount() {
816                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
817                         .build().unwrap();
818                 if let Err(e) = refund.to_string().parse::<Refund>() {
819                         panic!("error parsing refund: {:?}", e);
820                 }
821
822                 let mut tlv_stream = refund.as_tlv_stream();
823                 tlv_stream.2.amount = None;
824
825                 match Refund::try_from(tlv_stream.to_bytes()) {
826                         Ok(_) => panic!("expected error"),
827                         Err(e) => {
828                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
829                         },
830                 }
831
832                 let mut tlv_stream = refund.as_tlv_stream();
833                 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
834
835                 match Refund::try_from(tlv_stream.to_bytes()) {
836                         Ok(_) => panic!("expected error"),
837                         Err(e) => {
838                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
839                         },
840                 }
841         }
842
843         #[test]
844         fn parses_refund_with_payer_id() {
845                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
846                         .build().unwrap();
847                 if let Err(e) = refund.to_string().parse::<Refund>() {
848                         panic!("error parsing refund: {:?}", e);
849                 }
850
851                 let mut tlv_stream = refund.as_tlv_stream();
852                 tlv_stream.2.payer_id = None;
853
854                 match Refund::try_from(tlv_stream.to_bytes()) {
855                         Ok(_) => panic!("expected error"),
856                         Err(e) => {
857                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
858                         },
859                 }
860         }
861
862         #[test]
863         fn parses_refund_with_optional_fields() {
864                 let past_expiry = Duration::from_secs(0);
865                 let paths = vec![
866                         BlindedPath {
867                                 introduction_node_id: pubkey(40),
868                                 blinding_point: pubkey(41),
869                                 blinded_hops: vec![
870                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
871                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
872                                 ],
873                         },
874                         BlindedPath {
875                                 introduction_node_id: pubkey(40),
876                                 blinding_point: pubkey(41),
877                                 blinded_hops: vec![
878                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
879                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
880                                 ],
881                         },
882                 ];
883
884                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
885                         .absolute_expiry(past_expiry)
886                         .issuer("bar".into())
887                         .path(paths[0].clone())
888                         .path(paths[1].clone())
889                         .chain(Network::Testnet)
890                         .features_unchecked(InvoiceRequestFeatures::unknown())
891                         .payer_note("baz".into())
892                         .build()
893                         .unwrap();
894                 match refund.to_string().parse::<Refund>() {
895                         Ok(refund) => {
896                                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
897                                 #[cfg(feature = "std")]
898                                 assert!(refund.is_expired());
899                                 assert_eq!(refund.paths(), &paths[..]);
900                                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
901                                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
902                                 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
903                                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
904                         },
905                         Err(e) => panic!("error parsing refund: {:?}", e),
906                 }
907         }
908
909         #[test]
910         fn fails_parsing_refund_with_unexpected_fields() {
911                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
912                         .build().unwrap();
913                 if let Err(e) = refund.to_string().parse::<Refund>() {
914                         panic!("error parsing refund: {:?}", e);
915                 }
916
917                 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
918                 let mut tlv_stream = refund.as_tlv_stream();
919                 tlv_stream.1.chains = Some(&chains);
920
921                 match Refund::try_from(tlv_stream.to_bytes()) {
922                         Ok(_) => panic!("expected error"),
923                         Err(e) => {
924                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
925                         },
926                 }
927
928                 let mut tlv_stream = refund.as_tlv_stream();
929                 tlv_stream.1.currency = Some(&b"USD");
930                 tlv_stream.1.amount = Some(1000);
931
932                 match Refund::try_from(tlv_stream.to_bytes()) {
933                         Ok(_) => panic!("expected error"),
934                         Err(e) => {
935                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
936                         },
937                 }
938
939                 let features = OfferFeatures::unknown();
940                 let mut tlv_stream = refund.as_tlv_stream();
941                 tlv_stream.1.features = Some(&features);
942
943                 match Refund::try_from(tlv_stream.to_bytes()) {
944                         Ok(_) => panic!("expected error"),
945                         Err(e) => {
946                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
947                         },
948                 }
949
950                 let mut tlv_stream = refund.as_tlv_stream();
951                 tlv_stream.1.quantity_max = Some(10);
952
953                 match Refund::try_from(tlv_stream.to_bytes()) {
954                         Ok(_) => panic!("expected error"),
955                         Err(e) => {
956                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
957                         },
958                 }
959
960                 let node_id = payer_pubkey();
961                 let mut tlv_stream = refund.as_tlv_stream();
962                 tlv_stream.1.node_id = Some(&node_id);
963
964                 match Refund::try_from(tlv_stream.to_bytes()) {
965                         Ok(_) => panic!("expected error"),
966                         Err(e) => {
967                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
968                         },
969                 }
970
971                 let mut tlv_stream = refund.as_tlv_stream();
972                 tlv_stream.2.quantity = Some(10);
973
974                 match Refund::try_from(tlv_stream.to_bytes()) {
975                         Ok(_) => panic!("expected error"),
976                         Err(e) => {
977                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
978                         },
979                 }
980         }
981
982         #[test]
983         fn fails_parsing_refund_with_extra_tlv_records() {
984                 let secp_ctx = Secp256k1::new();
985                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
986                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
987                         .build().unwrap();
988
989                 let mut encoded_refund = Vec::new();
990                 refund.write(&mut encoded_refund).unwrap();
991                 BigSize(1002).write(&mut encoded_refund).unwrap();
992                 BigSize(32).write(&mut encoded_refund).unwrap();
993                 [42u8; 32].write(&mut encoded_refund).unwrap();
994
995                 match Refund::try_from(encoded_refund) {
996                         Ok(_) => panic!("expected error"),
997                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
998                 }
999         }
1000 }