Update docs regarding payment path privacy
[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), 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)]
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)]
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.
321         ///
322         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
323         /// calling this method in `std` builds. For `no-std` builds, a final [`Duration`] parameter
324         /// must be given, which is used to set [`Invoice::created_at`] since [`std::time::SystemTime`]
325         /// is not available.
326         ///
327         /// The caller is expected to remember the preimage of `payment_hash` in order to
328         /// claim a payment for the invoice.
329         ///
330         /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
331         /// offer, which does have a `signing_pubkey`.
332         ///
333         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
334         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
335         /// a preference. Note, however, that any privacy is lost if a public node id is used for
336         /// `signing_pubkey`.
337         ///
338         /// Errors if the request contains unknown required features.
339         ///
340         /// [`Invoice`]: crate::offers::invoice::Invoice
341         /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
342         pub fn respond_with(
343                 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
344                 signing_pubkey: PublicKey,
345                 #[cfg(any(test, not(feature = "std")))]
346                 created_at: Duration
347         ) -> Result<InvoiceBuilder, SemanticError> {
348                 if self.features().requires_unknown_bits() {
349                         return Err(SemanticError::UnknownRequiredFeatures);
350                 }
351
352                 #[cfg(all(not(test), feature = "std"))]
353                 let created_at = std::time::SystemTime::now()
354                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
355                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
356
357                 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
358         }
359
360         #[cfg(test)]
361         fn as_tlv_stream(&self) -> RefundTlvStreamRef {
362                 self.contents.as_tlv_stream()
363         }
364 }
365
366 impl AsRef<[u8]> for Refund {
367         fn as_ref(&self) -> &[u8] {
368                 &self.bytes
369         }
370 }
371
372 impl RefundContents {
373         #[cfg(feature = "std")]
374         pub(super) fn is_expired(&self) -> bool {
375                 match self.absolute_expiry {
376                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
377                                 Ok(elapsed) => elapsed > seconds_from_epoch,
378                                 Err(_) => false,
379                         },
380                         None => false,
381                 }
382         }
383
384         pub(super) fn chain(&self) -> ChainHash {
385                 self.chain.unwrap_or_else(|| self.implied_chain())
386         }
387
388         pub fn implied_chain(&self) -> ChainHash {
389                 ChainHash::using_genesis_block(Network::Bitcoin)
390         }
391
392         pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
393                 let payer = PayerTlvStreamRef {
394                         metadata: Some(&self.payer.0),
395                 };
396
397                 let offer = OfferTlvStreamRef {
398                         chains: None,
399                         metadata: None,
400                         currency: None,
401                         amount: None,
402                         description: Some(&self.description),
403                         features: None,
404                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
405                         paths: self.paths.as_ref(),
406                         issuer: self.issuer.as_ref(),
407                         quantity_max: None,
408                         node_id: None,
409                 };
410
411                 let features = {
412                         if self.features == InvoiceRequestFeatures::empty() { None }
413                         else { Some(&self.features) }
414                 };
415
416                 let invoice_request = InvoiceRequestTlvStreamRef {
417                         chain: self.chain.as_ref(),
418                         amount: Some(self.amount_msats),
419                         features,
420                         quantity: self.quantity,
421                         payer_id: Some(&self.payer_id),
422                         payer_note: self.payer_note.as_ref(),
423                 };
424
425                 (payer, offer, invoice_request)
426         }
427 }
428
429 impl Writeable for Refund {
430         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
431                 WithoutLength(&self.bytes).write(writer)
432         }
433 }
434
435 impl Writeable for RefundContents {
436         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
437                 self.as_tlv_stream().write(writer)
438         }
439 }
440
441 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
442
443 type RefundTlvStreamRef<'a> = (
444         PayerTlvStreamRef<'a>,
445         OfferTlvStreamRef<'a>,
446         InvoiceRequestTlvStreamRef<'a>,
447 );
448
449 impl SeekReadable for RefundTlvStream {
450         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
451                 let payer = SeekReadable::read(r)?;
452                 let offer = SeekReadable::read(r)?;
453                 let invoice_request = SeekReadable::read(r)?;
454
455                 Ok((payer, offer, invoice_request))
456         }
457 }
458
459 impl Bech32Encode for Refund {
460         const BECH32_HRP: &'static str = "lnr";
461 }
462
463 impl FromStr for Refund {
464         type Err = ParseError;
465
466         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
467                 Refund::from_bech32_str(s)
468         }
469 }
470
471 impl TryFrom<Vec<u8>> for Refund {
472         type Error = ParseError;
473
474         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
475                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
476                 let ParsedMessage { bytes, tlv_stream } = refund;
477                 let contents = RefundContents::try_from(tlv_stream)?;
478
479                 Ok(Refund { bytes, contents })
480         }
481 }
482
483 impl TryFrom<RefundTlvStream> for RefundContents {
484         type Error = SemanticError;
485
486         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
487                 let (
488                         PayerTlvStream { metadata: payer_metadata },
489                         OfferTlvStream {
490                                 chains, metadata, currency, amount: offer_amount, description,
491                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
492                         },
493                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
494                 ) = tlv_stream;
495
496                 let payer = match payer_metadata {
497                         None => return Err(SemanticError::MissingPayerMetadata),
498                         Some(metadata) => PayerContents(metadata),
499                 };
500
501                 if metadata.is_some() {
502                         return Err(SemanticError::UnexpectedMetadata);
503                 }
504
505                 if chains.is_some() {
506                         return Err(SemanticError::UnexpectedChain);
507                 }
508
509                 if currency.is_some() || offer_amount.is_some() {
510                         return Err(SemanticError::UnexpectedAmount);
511                 }
512
513                 let description = match description {
514                         None => return Err(SemanticError::MissingDescription),
515                         Some(description) => description,
516                 };
517
518                 if offer_features.is_some() {
519                         return Err(SemanticError::UnexpectedFeatures);
520                 }
521
522                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
523
524                 if quantity_max.is_some() {
525                         return Err(SemanticError::UnexpectedQuantity);
526                 }
527
528                 if node_id.is_some() {
529                         return Err(SemanticError::UnexpectedSigningPubkey);
530                 }
531
532                 let amount_msats = match amount {
533                         None => return Err(SemanticError::MissingAmount),
534                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
535                                 return Err(SemanticError::InvalidAmount);
536                         },
537                         Some(amount_msats) => amount_msats,
538                 };
539
540                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
541
542                 let payer_id = match payer_id {
543                         None => return Err(SemanticError::MissingPayerId),
544                         Some(payer_id) => payer_id,
545                 };
546
547                 Ok(RefundContents {
548                         payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
549                         quantity, payer_id, payer_note,
550                 })
551         }
552 }
553
554 impl core::fmt::Display for Refund {
555         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
556                 self.fmt_bech32_str(f)
557         }
558 }
559
560 #[cfg(test)]
561 mod tests {
562         use super::{Refund, RefundBuilder, RefundTlvStreamRef};
563
564         use bitcoin::blockdata::constants::ChainHash;
565         use bitcoin::network::constants::Network;
566         use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
567         use core::convert::TryFrom;
568         use core::time::Duration;
569         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
570         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
571         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
572         use crate::offers::offer::OfferTlvStreamRef;
573         use crate::offers::parse::{ParseError, SemanticError};
574         use crate::offers::payer::PayerTlvStreamRef;
575         use crate::onion_message::{BlindedHop, BlindedPath};
576         use crate::util::ser::{BigSize, Writeable};
577         use crate::util::string::PrintableString;
578
579         fn payer_pubkey() -> PublicKey {
580                 let secp_ctx = Secp256k1::new();
581                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()).public_key()
582         }
583
584         fn pubkey(byte: u8) -> PublicKey {
585                 let secp_ctx = Secp256k1::new();
586                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
587         }
588
589         fn privkey(byte: u8) -> SecretKey {
590                 SecretKey::from_slice(&[byte; 32]).unwrap()
591         }
592
593         trait ToBytes {
594                 fn to_bytes(&self) -> Vec<u8>;
595         }
596
597         impl<'a> ToBytes for RefundTlvStreamRef<'a> {
598                 fn to_bytes(&self) -> Vec<u8> {
599                         let mut buffer = Vec::new();
600                         self.write(&mut buffer).unwrap();
601                         buffer
602                 }
603         }
604
605         #[test]
606         fn builds_refund_with_defaults() {
607                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
608                         .build().unwrap();
609
610                 let mut buffer = Vec::new();
611                 refund.write(&mut buffer).unwrap();
612
613                 assert_eq!(refund.bytes, buffer.as_slice());
614                 assert_eq!(refund.metadata(), &[1; 32]);
615                 assert_eq!(refund.description(), PrintableString("foo"));
616                 assert_eq!(refund.absolute_expiry(), None);
617                 #[cfg(feature = "std")]
618                 assert!(!refund.is_expired());
619                 assert_eq!(refund.paths(), &[]);
620                 assert_eq!(refund.issuer(), None);
621                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
622                 assert_eq!(refund.amount_msats(), 1000);
623                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
624                 assert_eq!(refund.payer_id(), payer_pubkey());
625                 assert_eq!(refund.payer_note(), None);
626
627                 assert_eq!(
628                         refund.as_tlv_stream(),
629                         (
630                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
631                                 OfferTlvStreamRef {
632                                         chains: None,
633                                         metadata: None,
634                                         currency: None,
635                                         amount: None,
636                                         description: Some(&String::from("foo")),
637                                         features: None,
638                                         absolute_expiry: None,
639                                         paths: None,
640                                         issuer: None,
641                                         quantity_max: None,
642                                         node_id: None,
643                                 },
644                                 InvoiceRequestTlvStreamRef {
645                                         chain: None,
646                                         amount: Some(1000),
647                                         features: None,
648                                         quantity: None,
649                                         payer_id: Some(&payer_pubkey()),
650                                         payer_note: None,
651                                 },
652                         ),
653                 );
654
655                 if let Err(e) = Refund::try_from(buffer) {
656                         panic!("error parsing refund: {:?}", e);
657                 }
658         }
659
660         #[test]
661         fn fails_building_refund_with_invalid_amount() {
662                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
663                         Ok(_) => panic!("expected error"),
664                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
665                 }
666         }
667
668         #[test]
669         fn builds_refund_with_absolute_expiry() {
670                 let future_expiry = Duration::from_secs(u64::max_value());
671                 let past_expiry = Duration::from_secs(0);
672
673                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
674                         .absolute_expiry(future_expiry)
675                         .build()
676                         .unwrap();
677                 let (_, tlv_stream, _) = refund.as_tlv_stream();
678                 #[cfg(feature = "std")]
679                 assert!(!refund.is_expired());
680                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
681                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
682
683                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
684                         .absolute_expiry(future_expiry)
685                         .absolute_expiry(past_expiry)
686                         .build()
687                         .unwrap();
688                 let (_, tlv_stream, _) = refund.as_tlv_stream();
689                 #[cfg(feature = "std")]
690                 assert!(refund.is_expired());
691                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
692                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
693         }
694
695         #[test]
696         fn builds_refund_with_paths() {
697                 let paths = vec![
698                         BlindedPath {
699                                 introduction_node_id: pubkey(40),
700                                 blinding_point: pubkey(41),
701                                 blinded_hops: vec![
702                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
703                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
704                                 ],
705                         },
706                         BlindedPath {
707                                 introduction_node_id: pubkey(40),
708                                 blinding_point: pubkey(41),
709                                 blinded_hops: vec![
710                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
711                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
712                                 ],
713                         },
714                 ];
715
716                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
717                         .path(paths[0].clone())
718                         .path(paths[1].clone())
719                         .build()
720                         .unwrap();
721                 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
722                 assert_eq!(refund.paths(), paths.as_slice());
723                 assert_eq!(refund.payer_id(), pubkey(42));
724                 assert_ne!(pubkey(42), pubkey(44));
725                 assert_eq!(offer_tlv_stream.paths, Some(&paths));
726                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
727         }
728
729         #[test]
730         fn builds_refund_with_issuer() {
731                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
732                         .issuer("bar".into())
733                         .build()
734                         .unwrap();
735                 let (_, tlv_stream, _) = refund.as_tlv_stream();
736                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
737                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
738
739                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
740                         .issuer("bar".into())
741                         .issuer("baz".into())
742                         .build()
743                         .unwrap();
744                 let (_, tlv_stream, _) = refund.as_tlv_stream();
745                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
746                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
747         }
748
749         #[test]
750         fn builds_refund_with_chain() {
751                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
752                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
753
754                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
755                         .chain(Network::Bitcoin)
756                         .build().unwrap();
757                 let (_, _, tlv_stream) = refund.as_tlv_stream();
758                 assert_eq!(refund.chain(), mainnet);
759                 assert_eq!(tlv_stream.chain, None);
760
761                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
762                         .chain(Network::Testnet)
763                         .build().unwrap();
764                 let (_, _, tlv_stream) = refund.as_tlv_stream();
765                 assert_eq!(refund.chain(), testnet);
766                 assert_eq!(tlv_stream.chain, Some(&testnet));
767
768                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
769                         .chain(Network::Regtest)
770                         .chain(Network::Testnet)
771                         .build().unwrap();
772                 let (_, _, tlv_stream) = refund.as_tlv_stream();
773                 assert_eq!(refund.chain(), testnet);
774                 assert_eq!(tlv_stream.chain, Some(&testnet));
775         }
776
777         #[test]
778         fn builds_refund_with_quantity() {
779                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
780                         .quantity(10)
781                         .build().unwrap();
782                 let (_, _, tlv_stream) = refund.as_tlv_stream();
783                 assert_eq!(refund.quantity(), Some(10));
784                 assert_eq!(tlv_stream.quantity, Some(10));
785
786                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
787                         .quantity(10)
788                         .quantity(1)
789                         .build().unwrap();
790                 let (_, _, tlv_stream) = refund.as_tlv_stream();
791                 assert_eq!(refund.quantity(), Some(1));
792                 assert_eq!(tlv_stream.quantity, Some(1));
793         }
794
795         #[test]
796         fn builds_refund_with_payer_note() {
797                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
798                         .payer_note("bar".into())
799                         .build().unwrap();
800                 let (_, _, tlv_stream) = refund.as_tlv_stream();
801                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
802                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
803
804                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
805                         .payer_note("bar".into())
806                         .payer_note("baz".into())
807                         .build().unwrap();
808                 let (_, _, tlv_stream) = refund.as_tlv_stream();
809                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
810                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
811         }
812
813         #[test]
814         fn parses_refund_with_metadata() {
815                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
816                         .build().unwrap();
817                 if let Err(e) = refund.to_string().parse::<Refund>() {
818                         panic!("error parsing refund: {:?}", e);
819                 }
820
821                 let mut tlv_stream = refund.as_tlv_stream();
822                 tlv_stream.0.metadata = None;
823
824                 match Refund::try_from(tlv_stream.to_bytes()) {
825                         Ok(_) => panic!("expected error"),
826                         Err(e) => {
827                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
828                         },
829                 }
830         }
831
832         #[test]
833         fn parses_refund_with_description() {
834                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
835                         .build().unwrap();
836                 if let Err(e) = refund.to_string().parse::<Refund>() {
837                         panic!("error parsing refund: {:?}", e);
838                 }
839
840                 let mut tlv_stream = refund.as_tlv_stream();
841                 tlv_stream.1.description = None;
842
843                 match Refund::try_from(tlv_stream.to_bytes()) {
844                         Ok(_) => panic!("expected error"),
845                         Err(e) => {
846                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
847                         },
848                 }
849         }
850
851         #[test]
852         fn parses_refund_with_amount() {
853                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
854                         .build().unwrap();
855                 if let Err(e) = refund.to_string().parse::<Refund>() {
856                         panic!("error parsing refund: {:?}", e);
857                 }
858
859                 let mut tlv_stream = refund.as_tlv_stream();
860                 tlv_stream.2.amount = None;
861
862                 match Refund::try_from(tlv_stream.to_bytes()) {
863                         Ok(_) => panic!("expected error"),
864                         Err(e) => {
865                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
866                         },
867                 }
868
869                 let mut tlv_stream = refund.as_tlv_stream();
870                 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
871
872                 match Refund::try_from(tlv_stream.to_bytes()) {
873                         Ok(_) => panic!("expected error"),
874                         Err(e) => {
875                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
876                         },
877                 }
878         }
879
880         #[test]
881         fn parses_refund_with_payer_id() {
882                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
883                         .build().unwrap();
884                 if let Err(e) = refund.to_string().parse::<Refund>() {
885                         panic!("error parsing refund: {:?}", e);
886                 }
887
888                 let mut tlv_stream = refund.as_tlv_stream();
889                 tlv_stream.2.payer_id = None;
890
891                 match Refund::try_from(tlv_stream.to_bytes()) {
892                         Ok(_) => panic!("expected error"),
893                         Err(e) => {
894                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
895                         },
896                 }
897         }
898
899         #[test]
900         fn parses_refund_with_optional_fields() {
901                 let past_expiry = Duration::from_secs(0);
902                 let paths = vec![
903                         BlindedPath {
904                                 introduction_node_id: pubkey(40),
905                                 blinding_point: pubkey(41),
906                                 blinded_hops: vec![
907                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
908                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
909                                 ],
910                         },
911                         BlindedPath {
912                                 introduction_node_id: pubkey(40),
913                                 blinding_point: pubkey(41),
914                                 blinded_hops: vec![
915                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
916                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
917                                 ],
918                         },
919                 ];
920
921                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
922                         .absolute_expiry(past_expiry)
923                         .issuer("bar".into())
924                         .path(paths[0].clone())
925                         .path(paths[1].clone())
926                         .chain(Network::Testnet)
927                         .features_unchecked(InvoiceRequestFeatures::unknown())
928                         .quantity(10)
929                         .payer_note("baz".into())
930                         .build()
931                         .unwrap();
932                 match refund.to_string().parse::<Refund>() {
933                         Ok(refund) => {
934                                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
935                                 #[cfg(feature = "std")]
936                                 assert!(refund.is_expired());
937                                 assert_eq!(refund.paths(), &paths[..]);
938                                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
939                                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
940                                 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
941                                 assert_eq!(refund.quantity(), Some(10));
942                                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
943                         },
944                         Err(e) => panic!("error parsing refund: {:?}", e),
945                 }
946         }
947
948         #[test]
949         fn fails_parsing_refund_with_unexpected_fields() {
950                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
951                         .build().unwrap();
952                 if let Err(e) = refund.to_string().parse::<Refund>() {
953                         panic!("error parsing refund: {:?}", e);
954                 }
955
956                 let metadata = vec![42; 32];
957                 let mut tlv_stream = refund.as_tlv_stream();
958                 tlv_stream.1.metadata = Some(&metadata);
959
960                 match Refund::try_from(tlv_stream.to_bytes()) {
961                         Ok(_) => panic!("expected error"),
962                         Err(e) => {
963                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
964                         },
965                 }
966
967                 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
968                 let mut tlv_stream = refund.as_tlv_stream();
969                 tlv_stream.1.chains = Some(&chains);
970
971                 match Refund::try_from(tlv_stream.to_bytes()) {
972                         Ok(_) => panic!("expected error"),
973                         Err(e) => {
974                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
975                         },
976                 }
977
978                 let mut tlv_stream = refund.as_tlv_stream();
979                 tlv_stream.1.currency = Some(&b"USD");
980                 tlv_stream.1.amount = Some(1000);
981
982                 match Refund::try_from(tlv_stream.to_bytes()) {
983                         Ok(_) => panic!("expected error"),
984                         Err(e) => {
985                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
986                         },
987                 }
988
989                 let features = OfferFeatures::unknown();
990                 let mut tlv_stream = refund.as_tlv_stream();
991                 tlv_stream.1.features = Some(&features);
992
993                 match Refund::try_from(tlv_stream.to_bytes()) {
994                         Ok(_) => panic!("expected error"),
995                         Err(e) => {
996                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
997                         },
998                 }
999
1000                 let mut tlv_stream = refund.as_tlv_stream();
1001                 tlv_stream.1.quantity_max = Some(10);
1002
1003                 match Refund::try_from(tlv_stream.to_bytes()) {
1004                         Ok(_) => panic!("expected error"),
1005                         Err(e) => {
1006                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1007                         },
1008                 }
1009
1010                 let node_id = payer_pubkey();
1011                 let mut tlv_stream = refund.as_tlv_stream();
1012                 tlv_stream.1.node_id = Some(&node_id);
1013
1014                 match Refund::try_from(tlv_stream.to_bytes()) {
1015                         Ok(_) => panic!("expected error"),
1016                         Err(e) => {
1017                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1018                         },
1019                 }
1020         }
1021
1022         #[test]
1023         fn fails_parsing_refund_with_extra_tlv_records() {
1024                 let secp_ctx = Secp256k1::new();
1025                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1026                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1027                         .build().unwrap();
1028
1029                 let mut encoded_refund = Vec::new();
1030                 refund.write(&mut encoded_refund).unwrap();
1031                 BigSize(1002).write(&mut encoded_refund).unwrap();
1032                 BigSize(32).write(&mut encoded_refund).unwrap();
1033                 [42u8; 32].write(&mut encoded_refund).unwrap();
1034
1035                 match Refund::try_from(encoded_refund) {
1036                         Ok(_) => panic!("expected error"),
1037                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1038                 }
1039         }
1040 }