Common offers test_utils module
[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 //! ```
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), description, absolute_expiry: None, issuer: None,
122                         paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
123                         quantity: None, 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 [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
166         /// when the refund pertains to an [`Invoice`] that paid for more than one item from an
167         /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
168         ///
169         /// Successive calls to this method will override the previous setting.
170         ///
171         /// [`Invoice`]: crate::offers::invoice::Invoice
172         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
173         /// [`Offer`]: crate::offers::offer::Offer
174         pub fn quantity(mut self, quantity: u64) -> Self {
175                 self.refund.quantity = Some(quantity);
176                 self
177         }
178
179         /// Sets the [`Refund::payer_note`].
180         ///
181         /// Successive calls to this method will override the previous setting.
182         pub fn payer_note(mut self, payer_note: String) -> Self {
183                 self.refund.payer_note = Some(payer_note);
184                 self
185         }
186
187         /// Builds a [`Refund`] after checking for valid semantics.
188         pub fn build(mut self) -> Result<Refund, SemanticError> {
189                 if self.refund.chain() == self.refund.implied_chain() {
190                         self.refund.chain = None;
191                 }
192
193                 let mut bytes = Vec::new();
194                 self.refund.write(&mut bytes).unwrap();
195
196                 Ok(Refund {
197                         bytes,
198                         contents: self.refund,
199                 })
200         }
201 }
202
203 #[cfg(test)]
204 impl RefundBuilder {
205         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
206                 self.refund.features = features;
207                 self
208         }
209 }
210
211 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
212 ///
213 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
214 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
215 /// bitcoin ATM.
216 ///
217 /// [`Invoice`]: crate::offers::invoice::Invoice
218 /// [`Offer`]: crate::offers::offer::Offer
219 #[derive(Clone, Debug, PartialEq)]
220 pub struct Refund {
221         pub(super) bytes: Vec<u8>,
222         pub(super) contents: RefundContents,
223 }
224
225 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
226 ///
227 /// [`Invoice`]: crate::offers::invoice::Invoice
228 #[derive(Clone, Debug, PartialEq)]
229 pub(super) struct RefundContents {
230         payer: PayerContents,
231         // offer fields
232         description: String,
233         absolute_expiry: Option<Duration>,
234         issuer: Option<String>,
235         paths: Option<Vec<BlindedPath>>,
236         // invoice_request fields
237         chain: Option<ChainHash>,
238         amount_msats: u64,
239         features: InvoiceRequestFeatures,
240         quantity: Option<u64>,
241         payer_id: PublicKey,
242         payer_note: Option<String>,
243 }
244
245 impl Refund {
246         /// A complete description of the purpose of the refund. Intended to be displayed to the user
247         /// but with the caveat that it has not been verified in any way.
248         pub fn description(&self) -> PrintableString {
249                 PrintableString(&self.contents.description)
250         }
251
252         /// Duration since the Unix epoch when an invoice should no longer be sent.
253         ///
254         /// If `None`, the refund does not expire.
255         pub fn absolute_expiry(&self) -> Option<Duration> {
256                 self.contents.absolute_expiry
257         }
258
259         /// Whether the refund has expired.
260         #[cfg(feature = "std")]
261         pub fn is_expired(&self) -> bool {
262                 self.contents.is_expired()
263         }
264
265         /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
266         /// displayed to the user but with the caveat that it has not been verified in any way.
267         pub fn issuer(&self) -> Option<PrintableString> {
268                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
269         }
270
271         /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
272         /// privacy by obfuscating its node id.
273         pub fn paths(&self) -> &[BlindedPath] {
274                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
275         }
276
277         /// An unpredictable series of bytes, typically containing information about the derivation of
278         /// [`payer_id`].
279         ///
280         /// [`payer_id`]: Self::payer_id
281         pub fn metadata(&self) -> &[u8] {
282                 &self.contents.payer.0
283         }
284
285         /// A chain that the refund is valid for.
286         pub fn chain(&self) -> ChainHash {
287                 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
288         }
289
290         /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
291         ///
292         /// [`chain`]: Self::chain
293         pub fn amount_msats(&self) -> u64 {
294                 self.contents.amount_msats
295         }
296
297         /// Features pertaining to requesting an invoice.
298         pub fn features(&self) -> &InvoiceRequestFeatures {
299                 &self.contents.features
300         }
301
302         /// The quantity of an item that refund is for.
303         pub fn quantity(&self) -> Option<u64> {
304                 self.contents.quantity
305         }
306
307         /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
308         /// transient pubkey.
309         ///
310         /// [`paths`]: Self::paths
311         pub fn payer_id(&self) -> PublicKey {
312                 self.contents.payer_id
313         }
314
315         /// Payer provided note to include in the invoice.
316         pub fn payer_note(&self) -> Option<PrintableString> {
317                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
318         }
319
320         /// Creates an [`Invoice`] for the refund with the given required fields and using the
321         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
322         ///
323         /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
324         /// time is used for the `created_at` parameter.
325         ///
326         /// [`Invoice`]: crate::offers::invoice::Invoice
327         /// [`Duration`]: core::time::Duration
328         #[cfg(feature = "std")]
329         pub fn respond_with(
330                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
331                 signing_pubkey: PublicKey,
332         ) -> Result<InvoiceBuilder, SemanticError> {
333                 let created_at = std::time::SystemTime::now()
334                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
335                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
336
337                 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
338         }
339
340         /// Creates an [`Invoice`] for the refund with the given required fields.
341         ///
342         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
343         /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
344         /// [`std::time::SystemTime`] is not available.
345         ///
346         /// The caller is expected to remember the preimage of `payment_hash` in order to
347         /// claim a payment for the invoice.
348         ///
349         /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
350         /// offer, which does have a `signing_pubkey`.
351         ///
352         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
353         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
354         /// a preference. Note, however, that any privacy is lost if a public node id is used for
355         /// `signing_pubkey`.
356         ///
357         /// Errors if the request contains unknown required features.
358         ///
359         /// [`Invoice`]: crate::offers::invoice::Invoice
360         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
361         pub fn respond_with_no_std(
362                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
363                 signing_pubkey: PublicKey, created_at: Duration
364         ) -> Result<InvoiceBuilder, SemanticError> {
365                 if self.features().requires_unknown_bits() {
366                         return Err(SemanticError::UnknownRequiredFeatures);
367                 }
368
369                 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
370         }
371
372         #[cfg(test)]
373         fn as_tlv_stream(&self) -> RefundTlvStreamRef {
374                 self.contents.as_tlv_stream()
375         }
376 }
377
378 impl AsRef<[u8]> for Refund {
379         fn as_ref(&self) -> &[u8] {
380                 &self.bytes
381         }
382 }
383
384 impl RefundContents {
385         #[cfg(feature = "std")]
386         pub(super) fn is_expired(&self) -> bool {
387                 match self.absolute_expiry {
388                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
389                                 Ok(elapsed) => elapsed > seconds_from_epoch,
390                                 Err(_) => false,
391                         },
392                         None => false,
393                 }
394         }
395
396         pub(super) fn chain(&self) -> ChainHash {
397                 self.chain.unwrap_or_else(|| self.implied_chain())
398         }
399
400         pub fn implied_chain(&self) -> ChainHash {
401                 ChainHash::using_genesis_block(Network::Bitcoin)
402         }
403
404         pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
405                 let payer = PayerTlvStreamRef {
406                         metadata: Some(&self.payer.0),
407                 };
408
409                 let offer = OfferTlvStreamRef {
410                         chains: None,
411                         metadata: None,
412                         currency: None,
413                         amount: None,
414                         description: Some(&self.description),
415                         features: None,
416                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
417                         paths: self.paths.as_ref(),
418                         issuer: self.issuer.as_ref(),
419                         quantity_max: None,
420                         node_id: None,
421                 };
422
423                 let features = {
424                         if self.features == InvoiceRequestFeatures::empty() { None }
425                         else { Some(&self.features) }
426                 };
427
428                 let invoice_request = InvoiceRequestTlvStreamRef {
429                         chain: self.chain.as_ref(),
430                         amount: Some(self.amount_msats),
431                         features,
432                         quantity: self.quantity,
433                         payer_id: Some(&self.payer_id),
434                         payer_note: self.payer_note.as_ref(),
435                 };
436
437                 (payer, offer, invoice_request)
438         }
439 }
440
441 impl Writeable for Refund {
442         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
443                 WithoutLength(&self.bytes).write(writer)
444         }
445 }
446
447 impl Writeable for RefundContents {
448         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
449                 self.as_tlv_stream().write(writer)
450         }
451 }
452
453 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
454
455 type RefundTlvStreamRef<'a> = (
456         PayerTlvStreamRef<'a>,
457         OfferTlvStreamRef<'a>,
458         InvoiceRequestTlvStreamRef<'a>,
459 );
460
461 impl SeekReadable for RefundTlvStream {
462         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
463                 let payer = SeekReadable::read(r)?;
464                 let offer = SeekReadable::read(r)?;
465                 let invoice_request = SeekReadable::read(r)?;
466
467                 Ok((payer, offer, invoice_request))
468         }
469 }
470
471 impl Bech32Encode for Refund {
472         const BECH32_HRP: &'static str = "lnr";
473 }
474
475 impl FromStr for Refund {
476         type Err = ParseError;
477
478         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
479                 Refund::from_bech32_str(s)
480         }
481 }
482
483 impl TryFrom<Vec<u8>> for Refund {
484         type Error = ParseError;
485
486         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
487                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
488                 let ParsedMessage { bytes, tlv_stream } = refund;
489                 let contents = RefundContents::try_from(tlv_stream)?;
490
491                 Ok(Refund { bytes, contents })
492         }
493 }
494
495 impl TryFrom<RefundTlvStream> for RefundContents {
496         type Error = SemanticError;
497
498         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
499                 let (
500                         PayerTlvStream { metadata: payer_metadata },
501                         OfferTlvStream {
502                                 chains, metadata, currency, amount: offer_amount, description,
503                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
504                         },
505                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
506                 ) = tlv_stream;
507
508                 let payer = match payer_metadata {
509                         None => return Err(SemanticError::MissingPayerMetadata),
510                         Some(metadata) => PayerContents(metadata),
511                 };
512
513                 if metadata.is_some() {
514                         return Err(SemanticError::UnexpectedMetadata);
515                 }
516
517                 if chains.is_some() {
518                         return Err(SemanticError::UnexpectedChain);
519                 }
520
521                 if currency.is_some() || offer_amount.is_some() {
522                         return Err(SemanticError::UnexpectedAmount);
523                 }
524
525                 let description = match description {
526                         None => return Err(SemanticError::MissingDescription),
527                         Some(description) => description,
528                 };
529
530                 if offer_features.is_some() {
531                         return Err(SemanticError::UnexpectedFeatures);
532                 }
533
534                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
535
536                 if quantity_max.is_some() {
537                         return Err(SemanticError::UnexpectedQuantity);
538                 }
539
540                 if node_id.is_some() {
541                         return Err(SemanticError::UnexpectedSigningPubkey);
542                 }
543
544                 let amount_msats = match amount {
545                         None => return Err(SemanticError::MissingAmount),
546                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
547                                 return Err(SemanticError::InvalidAmount);
548                         },
549                         Some(amount_msats) => amount_msats,
550                 };
551
552                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
553
554                 let payer_id = match payer_id {
555                         None => return Err(SemanticError::MissingPayerId),
556                         Some(payer_id) => payer_id,
557                 };
558
559                 Ok(RefundContents {
560                         payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
561                         quantity, payer_id, payer_note,
562                 })
563         }
564 }
565
566 impl core::fmt::Display for Refund {
567         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
568                 self.fmt_bech32_str(f)
569         }
570 }
571
572 #[cfg(test)]
573 mod tests {
574         use super::{Refund, RefundBuilder, RefundTlvStreamRef};
575
576         use bitcoin::blockdata::constants::ChainHash;
577         use bitcoin::network::constants::Network;
578         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
579         use core::convert::TryFrom;
580         use core::time::Duration;
581         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
582         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
583         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
584         use crate::offers::offer::OfferTlvStreamRef;
585         use crate::offers::parse::{ParseError, SemanticError};
586         use crate::offers::payer::PayerTlvStreamRef;
587         use crate::offers::test_utils::*;
588         use crate::onion_message::{BlindedHop, BlindedPath};
589         use crate::util::ser::{BigSize, Writeable};
590         use crate::util::string::PrintableString;
591
592         trait ToBytes {
593                 fn to_bytes(&self) -> Vec<u8>;
594         }
595
596         impl<'a> ToBytes for RefundTlvStreamRef<'a> {
597                 fn to_bytes(&self) -> Vec<u8> {
598                         let mut buffer = Vec::new();
599                         self.write(&mut buffer).unwrap();
600                         buffer
601                 }
602         }
603
604         #[test]
605         fn builds_refund_with_defaults() {
606                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
607                         .build().unwrap();
608
609                 let mut buffer = Vec::new();
610                 refund.write(&mut buffer).unwrap();
611
612                 assert_eq!(refund.bytes, buffer.as_slice());
613                 assert_eq!(refund.metadata(), &[1; 32]);
614                 assert_eq!(refund.description(), PrintableString("foo"));
615                 assert_eq!(refund.absolute_expiry(), None);
616                 #[cfg(feature = "std")]
617                 assert!(!refund.is_expired());
618                 assert_eq!(refund.paths(), &[]);
619                 assert_eq!(refund.issuer(), None);
620                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
621                 assert_eq!(refund.amount_msats(), 1000);
622                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
623                 assert_eq!(refund.payer_id(), payer_pubkey());
624                 assert_eq!(refund.payer_note(), None);
625
626                 assert_eq!(
627                         refund.as_tlv_stream(),
628                         (
629                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
630                                 OfferTlvStreamRef {
631                                         chains: None,
632                                         metadata: None,
633                                         currency: None,
634                                         amount: None,
635                                         description: Some(&String::from("foo")),
636                                         features: None,
637                                         absolute_expiry: None,
638                                         paths: None,
639                                         issuer: None,
640                                         quantity_max: None,
641                                         node_id: None,
642                                 },
643                                 InvoiceRequestTlvStreamRef {
644                                         chain: None,
645                                         amount: Some(1000),
646                                         features: None,
647                                         quantity: None,
648                                         payer_id: Some(&payer_pubkey()),
649                                         payer_note: None,
650                                 },
651                         ),
652                 );
653
654                 if let Err(e) = Refund::try_from(buffer) {
655                         panic!("error parsing refund: {:?}", e);
656                 }
657         }
658
659         #[test]
660         fn fails_building_refund_with_invalid_amount() {
661                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
662                         Ok(_) => panic!("expected error"),
663                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
664                 }
665         }
666
667         #[test]
668         fn builds_refund_with_absolute_expiry() {
669                 let future_expiry = Duration::from_secs(u64::max_value());
670                 let past_expiry = Duration::from_secs(0);
671
672                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
673                         .absolute_expiry(future_expiry)
674                         .build()
675                         .unwrap();
676                 let (_, tlv_stream, _) = refund.as_tlv_stream();
677                 #[cfg(feature = "std")]
678                 assert!(!refund.is_expired());
679                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
680                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
681
682                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
683                         .absolute_expiry(future_expiry)
684                         .absolute_expiry(past_expiry)
685                         .build()
686                         .unwrap();
687                 let (_, tlv_stream, _) = refund.as_tlv_stream();
688                 #[cfg(feature = "std")]
689                 assert!(refund.is_expired());
690                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
691                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
692         }
693
694         #[test]
695         fn builds_refund_with_paths() {
696                 let paths = vec![
697                         BlindedPath {
698                                 introduction_node_id: pubkey(40),
699                                 blinding_point: pubkey(41),
700                                 blinded_hops: vec![
701                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
702                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
703                                 ],
704                         },
705                         BlindedPath {
706                                 introduction_node_id: pubkey(40),
707                                 blinding_point: pubkey(41),
708                                 blinded_hops: vec![
709                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
710                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
711                                 ],
712                         },
713                 ];
714
715                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
716                         .path(paths[0].clone())
717                         .path(paths[1].clone())
718                         .build()
719                         .unwrap();
720                 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
721                 assert_eq!(refund.paths(), paths.as_slice());
722                 assert_eq!(refund.payer_id(), pubkey(42));
723                 assert_ne!(pubkey(42), pubkey(44));
724                 assert_eq!(offer_tlv_stream.paths, Some(&paths));
725                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
726         }
727
728         #[test]
729         fn builds_refund_with_issuer() {
730                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
731                         .issuer("bar".into())
732                         .build()
733                         .unwrap();
734                 let (_, tlv_stream, _) = refund.as_tlv_stream();
735                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
736                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
737
738                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
739                         .issuer("bar".into())
740                         .issuer("baz".into())
741                         .build()
742                         .unwrap();
743                 let (_, tlv_stream, _) = refund.as_tlv_stream();
744                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
745                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
746         }
747
748         #[test]
749         fn builds_refund_with_chain() {
750                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
751                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
752
753                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
754                         .chain(Network::Bitcoin)
755                         .build().unwrap();
756                 let (_, _, tlv_stream) = refund.as_tlv_stream();
757                 assert_eq!(refund.chain(), mainnet);
758                 assert_eq!(tlv_stream.chain, None);
759
760                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
761                         .chain(Network::Testnet)
762                         .build().unwrap();
763                 let (_, _, tlv_stream) = refund.as_tlv_stream();
764                 assert_eq!(refund.chain(), testnet);
765                 assert_eq!(tlv_stream.chain, Some(&testnet));
766
767                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
768                         .chain(Network::Regtest)
769                         .chain(Network::Testnet)
770                         .build().unwrap();
771                 let (_, _, tlv_stream) = refund.as_tlv_stream();
772                 assert_eq!(refund.chain(), testnet);
773                 assert_eq!(tlv_stream.chain, Some(&testnet));
774         }
775
776         #[test]
777         fn builds_refund_with_quantity() {
778                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
779                         .quantity(10)
780                         .build().unwrap();
781                 let (_, _, tlv_stream) = refund.as_tlv_stream();
782                 assert_eq!(refund.quantity(), Some(10));
783                 assert_eq!(tlv_stream.quantity, Some(10));
784
785                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
786                         .quantity(10)
787                         .quantity(1)
788                         .build().unwrap();
789                 let (_, _, tlv_stream) = refund.as_tlv_stream();
790                 assert_eq!(refund.quantity(), Some(1));
791                 assert_eq!(tlv_stream.quantity, Some(1));
792         }
793
794         #[test]
795         fn builds_refund_with_payer_note() {
796                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
797                         .payer_note("bar".into())
798                         .build().unwrap();
799                 let (_, _, tlv_stream) = refund.as_tlv_stream();
800                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
801                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
802
803                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
804                         .payer_note("bar".into())
805                         .payer_note("baz".into())
806                         .build().unwrap();
807                 let (_, _, tlv_stream) = refund.as_tlv_stream();
808                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
809                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
810         }
811
812         #[test]
813         fn parses_refund_with_metadata() {
814                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
815                         .build().unwrap();
816                 if let Err(e) = refund.to_string().parse::<Refund>() {
817                         panic!("error parsing refund: {:?}", e);
818                 }
819
820                 let mut tlv_stream = refund.as_tlv_stream();
821                 tlv_stream.0.metadata = None;
822
823                 match Refund::try_from(tlv_stream.to_bytes()) {
824                         Ok(_) => panic!("expected error"),
825                         Err(e) => {
826                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
827                         },
828                 }
829         }
830
831         #[test]
832         fn parses_refund_with_description() {
833                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
834                         .build().unwrap();
835                 if let Err(e) = refund.to_string().parse::<Refund>() {
836                         panic!("error parsing refund: {:?}", e);
837                 }
838
839                 let mut tlv_stream = refund.as_tlv_stream();
840                 tlv_stream.1.description = None;
841
842                 match Refund::try_from(tlv_stream.to_bytes()) {
843                         Ok(_) => panic!("expected error"),
844                         Err(e) => {
845                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
846                         },
847                 }
848         }
849
850         #[test]
851         fn parses_refund_with_amount() {
852                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
853                         .build().unwrap();
854                 if let Err(e) = refund.to_string().parse::<Refund>() {
855                         panic!("error parsing refund: {:?}", e);
856                 }
857
858                 let mut tlv_stream = refund.as_tlv_stream();
859                 tlv_stream.2.amount = None;
860
861                 match Refund::try_from(tlv_stream.to_bytes()) {
862                         Ok(_) => panic!("expected error"),
863                         Err(e) => {
864                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
865                         },
866                 }
867
868                 let mut tlv_stream = refund.as_tlv_stream();
869                 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
870
871                 match Refund::try_from(tlv_stream.to_bytes()) {
872                         Ok(_) => panic!("expected error"),
873                         Err(e) => {
874                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
875                         },
876                 }
877         }
878
879         #[test]
880         fn parses_refund_with_payer_id() {
881                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
882                         .build().unwrap();
883                 if let Err(e) = refund.to_string().parse::<Refund>() {
884                         panic!("error parsing refund: {:?}", e);
885                 }
886
887                 let mut tlv_stream = refund.as_tlv_stream();
888                 tlv_stream.2.payer_id = None;
889
890                 match Refund::try_from(tlv_stream.to_bytes()) {
891                         Ok(_) => panic!("expected error"),
892                         Err(e) => {
893                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
894                         },
895                 }
896         }
897
898         #[test]
899         fn parses_refund_with_optional_fields() {
900                 let past_expiry = Duration::from_secs(0);
901                 let paths = vec![
902                         BlindedPath {
903                                 introduction_node_id: pubkey(40),
904                                 blinding_point: pubkey(41),
905                                 blinded_hops: vec![
906                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
907                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
908                                 ],
909                         },
910                         BlindedPath {
911                                 introduction_node_id: pubkey(40),
912                                 blinding_point: pubkey(41),
913                                 blinded_hops: vec![
914                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
915                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
916                                 ],
917                         },
918                 ];
919
920                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
921                         .absolute_expiry(past_expiry)
922                         .issuer("bar".into())
923                         .path(paths[0].clone())
924                         .path(paths[1].clone())
925                         .chain(Network::Testnet)
926                         .features_unchecked(InvoiceRequestFeatures::unknown())
927                         .quantity(10)
928                         .payer_note("baz".into())
929                         .build()
930                         .unwrap();
931                 match refund.to_string().parse::<Refund>() {
932                         Ok(refund) => {
933                                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
934                                 #[cfg(feature = "std")]
935                                 assert!(refund.is_expired());
936                                 assert_eq!(refund.paths(), &paths[..]);
937                                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
938                                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
939                                 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
940                                 assert_eq!(refund.quantity(), Some(10));
941                                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
942                         },
943                         Err(e) => panic!("error parsing refund: {:?}", e),
944                 }
945         }
946
947         #[test]
948         fn fails_parsing_refund_with_unexpected_fields() {
949                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
950                         .build().unwrap();
951                 if let Err(e) = refund.to_string().parse::<Refund>() {
952                         panic!("error parsing refund: {:?}", e);
953                 }
954
955                 let metadata = vec![42; 32];
956                 let mut tlv_stream = refund.as_tlv_stream();
957                 tlv_stream.1.metadata = Some(&metadata);
958
959                 match Refund::try_from(tlv_stream.to_bytes()) {
960                         Ok(_) => panic!("expected error"),
961                         Err(e) => {
962                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
963                         },
964                 }
965
966                 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
967                 let mut tlv_stream = refund.as_tlv_stream();
968                 tlv_stream.1.chains = Some(&chains);
969
970                 match Refund::try_from(tlv_stream.to_bytes()) {
971                         Ok(_) => panic!("expected error"),
972                         Err(e) => {
973                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
974                         },
975                 }
976
977                 let mut tlv_stream = refund.as_tlv_stream();
978                 tlv_stream.1.currency = Some(&b"USD");
979                 tlv_stream.1.amount = Some(1000);
980
981                 match Refund::try_from(tlv_stream.to_bytes()) {
982                         Ok(_) => panic!("expected error"),
983                         Err(e) => {
984                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
985                         },
986                 }
987
988                 let features = OfferFeatures::unknown();
989                 let mut tlv_stream = refund.as_tlv_stream();
990                 tlv_stream.1.features = Some(&features);
991
992                 match Refund::try_from(tlv_stream.to_bytes()) {
993                         Ok(_) => panic!("expected error"),
994                         Err(e) => {
995                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
996                         },
997                 }
998
999                 let mut tlv_stream = refund.as_tlv_stream();
1000                 tlv_stream.1.quantity_max = Some(10);
1001
1002                 match Refund::try_from(tlv_stream.to_bytes()) {
1003                         Ok(_) => panic!("expected error"),
1004                         Err(e) => {
1005                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1006                         },
1007                 }
1008
1009                 let node_id = payer_pubkey();
1010                 let mut tlv_stream = refund.as_tlv_stream();
1011                 tlv_stream.1.node_id = Some(&node_id);
1012
1013                 match Refund::try_from(tlv_stream.to_bytes()) {
1014                         Ok(_) => panic!("expected error"),
1015                         Err(e) => {
1016                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1017                         },
1018                 }
1019         }
1020
1021         #[test]
1022         fn fails_parsing_refund_with_extra_tlv_records() {
1023                 let secp_ctx = Secp256k1::new();
1024                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1025                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1026                         .build().unwrap();
1027
1028                 let mut encoded_refund = Vec::new();
1029                 refund.write(&mut encoded_refund).unwrap();
1030                 BigSize(1002).write(&mut encoded_refund).unwrap();
1031                 BigSize(32).write(&mut encoded_refund).unwrap();
1032                 [42u8; 32].write(&mut encoded_refund).unwrap();
1033
1034                 match Refund::try_from(encoded_refund) {
1035                         Ok(_) => panic!("expected error"),
1036                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1037                 }
1038         }
1039 }