4b4572b4df9c85fd8970e9758b727d9b6214a067
[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 a [`Bolt12Invoice`] to be paid.
14 //!
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
16 //!
17 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
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::Bolt12ParseError;
32 //! use lightning::offers::refund::{Refund, RefundBuilder};
33 //! use lightning::util::ser::{Readable, Writeable};
34 //!
35 //! # use lightning::blinded_path::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<(), Bolt12ParseError> {
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, Secp256k1, self};
77 use core::convert::TryFrom;
78 use core::ops::Deref;
79 use core::str::FromStr;
80 use core::time::Duration;
81 use crate::sign::EntropySource;
82 use crate::io;
83 use crate::blinded_path::BlindedPath;
84 use crate::ln::PaymentHash;
85 use crate::ln::channelmanager::PaymentId;
86 use crate::ln::features::InvoiceRequestFeatures;
87 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
88 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
89 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
90 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
91 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
92 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
93 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
94 use crate::offers::signer::{Metadata, MetadataMaterial, self};
95 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
96 use crate::util::string::PrintableString;
97
98 use crate::prelude::*;
99
100 #[cfg(feature = "std")]
101 use std::time::SystemTime;
102
103 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
104
105 /// Builds a [`Refund`] for the "offer for money" flow.
106 ///
107 /// See [module-level documentation] for usage.
108 ///
109 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
110 ///
111 /// [module-level documentation]: self
112 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
113         refund: RefundContents,
114         secp_ctx: Option<&'a Secp256k1<T>>,
115 }
116
117 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
118         /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
119         /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
120         ///
121         /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
122         /// [`Refund::amount_msats`].
123         pub fn new(
124                 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
125         ) -> Result<Self, Bolt12SemanticError> {
126                 if amount_msats > MAX_VALUE_MSAT {
127                         return Err(Bolt12SemanticError::InvalidAmount);
128                 }
129
130                 let metadata = Metadata::Bytes(metadata);
131                 Ok(Self {
132                         refund: RefundContents {
133                                 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
134                                 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
135                                 quantity: None, payer_id, payer_note: None,
136                         },
137                         secp_ctx: None,
138                 })
139         }
140 }
141
142 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
143         /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
144         /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
145         /// different payer id for each refund, assuming a different nonce is used.  Otherwise, the
146         /// provided `node_id` is used for the payer id.
147         ///
148         /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
149         /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
150         ///
151         /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
152         /// one invoice will be paid for the refund and that payments can be uniquely identified.
153         ///
154         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
155         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
156         pub fn deriving_payer_id<ES: Deref>(
157                 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
158                 secp_ctx: &'a Secp256k1<T>, amount_msats: u64, payment_id: PaymentId
159         ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
160                 if amount_msats > MAX_VALUE_MSAT {
161                         return Err(Bolt12SemanticError::InvalidAmount);
162                 }
163
164                 let nonce = Nonce::from_entropy_source(entropy_source);
165                 let payment_id = Some(payment_id);
166                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
167                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
168                 Ok(Self {
169                         refund: RefundContents {
170                                 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
171                                 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
172                                 quantity: None, payer_id: node_id, payer_note: None,
173                         },
174                         secp_ctx: Some(secp_ctx),
175                 })
176         }
177
178         /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
179         /// already passed is valid and can be checked for using [`Refund::is_expired`].
180         ///
181         /// Successive calls to this method will override the previous setting.
182         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
183                 self.refund.absolute_expiry = Some(absolute_expiry);
184                 self
185         }
186
187         /// Sets the [`Refund::issuer`].
188         ///
189         /// Successive calls to this method will override the previous setting.
190         pub fn issuer(mut self, issuer: String) -> Self {
191                 self.refund.issuer = Some(issuer);
192                 self
193         }
194
195         /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
196         /// by private channels or if [`Refund::payer_id`] is not a public node id.
197         ///
198         /// Successive calls to this method will add another blinded path. Caller is responsible for not
199         /// adding duplicate paths.
200         pub fn path(mut self, path: BlindedPath) -> Self {
201                 self.refund.paths.get_or_insert_with(Vec::new).push(path);
202                 self
203         }
204
205         /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
206         /// called, [`Network::Bitcoin`] is assumed.
207         ///
208         /// Successive calls to this method will override the previous setting.
209         pub fn chain(mut self, network: Network) -> Self {
210                 self.refund.chain = Some(ChainHash::using_genesis_block(network));
211                 self
212         }
213
214         /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
215         /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
216         /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
217         ///
218         /// Successive calls to this method will override the previous setting.
219         ///
220         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
221         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
222         /// [`Offer`]: crate::offers::offer::Offer
223         pub fn quantity(mut self, quantity: u64) -> Self {
224                 self.refund.quantity = Some(quantity);
225                 self
226         }
227
228         /// Sets the [`Refund::payer_note`].
229         ///
230         /// Successive calls to this method will override the previous setting.
231         pub fn payer_note(mut self, payer_note: String) -> Self {
232                 self.refund.payer_note = Some(payer_note);
233                 self
234         }
235
236         /// Builds a [`Refund`] after checking for valid semantics.
237         pub fn build(mut self) -> Result<Refund, Bolt12SemanticError> {
238                 if self.refund.chain() == self.refund.implied_chain() {
239                         self.refund.chain = None;
240                 }
241
242                 // Create the metadata for stateless verification of a Bolt12Invoice.
243                 if self.refund.payer.0.has_derivation_material() {
244                         let mut metadata = core::mem::take(&mut self.refund.payer.0);
245
246                         if self.refund.paths.is_none() {
247                                 metadata = metadata.without_keys();
248                         }
249
250                         let mut tlv_stream = self.refund.as_tlv_stream();
251                         tlv_stream.0.metadata = None;
252                         if metadata.derives_payer_keys() {
253                                 tlv_stream.2.payer_id = None;
254                         }
255
256                         let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
257                         metadata = derived_metadata;
258                         if let Some(keys) = keys {
259                                 self.refund.payer_id = keys.public_key();
260                         }
261
262                         self.refund.payer.0 = metadata;
263                 }
264
265                 let mut bytes = Vec::new();
266                 self.refund.write(&mut bytes).unwrap();
267
268                 Ok(Refund { bytes, contents: self.refund })
269         }
270 }
271
272 #[cfg(test)]
273 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
274         fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
275                 self.refund.features = features;
276                 self
277         }
278 }
279
280 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
281 ///
282 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
283 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
284 /// bitcoin ATM.
285 ///
286 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
287 /// [`Offer`]: crate::offers::offer::Offer
288 #[derive(Clone, Debug)]
289 #[cfg_attr(test, derive(PartialEq))]
290 pub struct Refund {
291         pub(super) bytes: Vec<u8>,
292         pub(super) contents: RefundContents,
293 }
294
295 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
296 ///
297 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
298 #[derive(Clone, Debug)]
299 #[cfg_attr(test, derive(PartialEq))]
300 pub(super) struct RefundContents {
301         payer: PayerContents,
302         // offer fields
303         description: String,
304         absolute_expiry: Option<Duration>,
305         issuer: Option<String>,
306         paths: Option<Vec<BlindedPath>>,
307         // invoice_request fields
308         chain: Option<ChainHash>,
309         amount_msats: u64,
310         features: InvoiceRequestFeatures,
311         quantity: Option<u64>,
312         payer_id: PublicKey,
313         payer_note: Option<String>,
314 }
315
316 impl Refund {
317         /// A complete description of the purpose of the refund. Intended to be displayed to the user
318         /// but with the caveat that it has not been verified in any way.
319         pub fn description(&self) -> PrintableString {
320                 self.contents.description()
321         }
322
323         /// Duration since the Unix epoch when an invoice should no longer be sent.
324         ///
325         /// If `None`, the refund does not expire.
326         pub fn absolute_expiry(&self) -> Option<Duration> {
327                 self.contents.absolute_expiry()
328         }
329
330         /// Whether the refund has expired.
331         #[cfg(feature = "std")]
332         pub fn is_expired(&self) -> bool {
333                 self.contents.is_expired()
334         }
335
336         /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
337         /// displayed to the user but with the caveat that it has not been verified in any way.
338         pub fn issuer(&self) -> Option<PrintableString> {
339                 self.contents.issuer()
340         }
341
342         /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
343         /// privacy by obfuscating its node id.
344         pub fn paths(&self) -> &[BlindedPath] {
345                 self.contents.paths()
346         }
347
348         /// An unpredictable series of bytes, typically containing information about the derivation of
349         /// [`payer_id`].
350         ///
351         /// [`payer_id`]: Self::payer_id
352         pub fn payer_metadata(&self) -> &[u8] {
353                 self.contents.metadata()
354         }
355
356         /// A chain that the refund is valid for.
357         pub fn chain(&self) -> ChainHash {
358                 self.contents.chain()
359         }
360
361         /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
362         ///
363         /// [`chain`]: Self::chain
364         pub fn amount_msats(&self) -> u64 {
365                 self.contents.amount_msats()
366         }
367
368         /// Features pertaining to requesting an invoice.
369         pub fn features(&self) -> &InvoiceRequestFeatures {
370                 &self.contents.features()
371         }
372
373         /// The quantity of an item that refund is for.
374         pub fn quantity(&self) -> Option<u64> {
375                 self.contents.quantity()
376         }
377
378         /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
379         /// transient pubkey.
380         ///
381         /// [`paths`]: Self::paths
382         pub fn payer_id(&self) -> PublicKey {
383                 self.contents.payer_id()
384         }
385
386         /// Payer provided note to include in the invoice.
387         pub fn payer_note(&self) -> Option<PrintableString> {
388                 self.contents.payer_note()
389         }
390
391         /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
392         /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
393         ///
394         /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
395         /// time is used for the `created_at` parameter.
396         ///
397         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
398         ///
399         /// [`Duration`]: core::time::Duration
400         #[cfg(feature = "std")]
401         pub fn respond_with(
402                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
403                 signing_pubkey: PublicKey,
404         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
405                 let created_at = std::time::SystemTime::now()
406                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
407                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
408
409                 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
410         }
411
412         /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
413         ///
414         /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
415         /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
416         /// where [`std::time::SystemTime`] is not available.
417         ///
418         /// The caller is expected to remember the preimage of `payment_hash` in order to
419         /// claim a payment for the invoice.
420         ///
421         /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
422         /// offer, which does have a `signing_pubkey`.
423         ///
424         /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
425         /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
426         /// a preference. Note, however, that any privacy is lost if a public node id is used for
427         /// `signing_pubkey`.
428         ///
429         /// Errors if the request contains unknown required features.
430         ///
431         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
432         ///
433         /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
434         pub fn respond_with_no_std(
435                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
436                 signing_pubkey: PublicKey, created_at: Duration
437         ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
438                 if self.features().requires_unknown_bits() {
439                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
440                 }
441
442                 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
443         }
444
445         /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
446         /// derived signing keys to sign the [`Bolt12Invoice`].
447         ///
448         /// See [`Refund::respond_with`] for further details.
449         ///
450         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
451         ///
452         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
453         #[cfg(feature = "std")]
454         pub fn respond_using_derived_keys<ES: Deref>(
455                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
456                 expanded_key: &ExpandedKey, entropy_source: ES
457         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
458         where
459                 ES::Target: EntropySource,
460         {
461                 let created_at = std::time::SystemTime::now()
462                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
463                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
464
465                 self.respond_using_derived_keys_no_std(
466                         payment_paths, payment_hash, created_at, expanded_key, entropy_source
467                 )
468         }
469
470         /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
471         /// derived signing keys to sign the [`Bolt12Invoice`].
472         ///
473         /// See [`Refund::respond_with_no_std`] for further details.
474         ///
475         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
476         ///
477         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
478         pub fn respond_using_derived_keys_no_std<ES: Deref>(
479                 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
480                 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
481         ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
482         where
483                 ES::Target: EntropySource,
484         {
485                 if self.features().requires_unknown_bits() {
486                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
487                 }
488
489                 let nonce = Nonce::from_entropy_source(entropy_source);
490                 let keys = signer::derive_keys(nonce, expanded_key);
491                 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
492         }
493
494         #[cfg(test)]
495         fn as_tlv_stream(&self) -> RefundTlvStreamRef {
496                 self.contents.as_tlv_stream()
497         }
498 }
499
500 impl AsRef<[u8]> for Refund {
501         fn as_ref(&self) -> &[u8] {
502                 &self.bytes
503         }
504 }
505
506 impl RefundContents {
507         pub fn description(&self) -> PrintableString {
508                 PrintableString(&self.description)
509         }
510
511         pub fn absolute_expiry(&self) -> Option<Duration> {
512                 self.absolute_expiry
513         }
514
515         #[cfg(feature = "std")]
516         pub(super) fn is_expired(&self) -> bool {
517                 match self.absolute_expiry {
518                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
519                                 Ok(elapsed) => elapsed > seconds_from_epoch,
520                                 Err(_) => false,
521                         },
522                         None => false,
523                 }
524         }
525
526         pub fn issuer(&self) -> Option<PrintableString> {
527                 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
528         }
529
530         pub fn paths(&self) -> &[BlindedPath] {
531                 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
532         }
533
534         pub(super) fn metadata(&self) -> &[u8] {
535                 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
536         }
537
538         pub(super) fn chain(&self) -> ChainHash {
539                 self.chain.unwrap_or_else(|| self.implied_chain())
540         }
541
542         pub fn implied_chain(&self) -> ChainHash {
543                 ChainHash::using_genesis_block(Network::Bitcoin)
544         }
545
546         pub fn amount_msats(&self) -> u64 {
547                 self.amount_msats
548         }
549
550         /// Features pertaining to requesting an invoice.
551         pub fn features(&self) -> &InvoiceRequestFeatures {
552                 &self.features
553         }
554
555         /// The quantity of an item that refund is for.
556         pub fn quantity(&self) -> Option<u64> {
557                 self.quantity
558         }
559
560         /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
561         /// transient pubkey.
562         ///
563         /// [`paths`]: Self::paths
564         pub fn payer_id(&self) -> PublicKey {
565                 self.payer_id
566         }
567
568         /// Payer provided note to include in the invoice.
569         pub fn payer_note(&self) -> Option<PrintableString> {
570                 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
571         }
572
573         pub(super) fn derives_keys(&self) -> bool {
574                 self.payer.0.derives_payer_keys()
575         }
576
577         pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
578                 let payer = PayerTlvStreamRef {
579                         metadata: self.payer.0.as_bytes(),
580                 };
581
582                 let offer = OfferTlvStreamRef {
583                         chains: None,
584                         metadata: None,
585                         currency: None,
586                         amount: None,
587                         description: Some(&self.description),
588                         features: None,
589                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
590                         paths: self.paths.as_ref(),
591                         issuer: self.issuer.as_ref(),
592                         quantity_max: None,
593                         node_id: None,
594                 };
595
596                 let features = {
597                         if self.features == InvoiceRequestFeatures::empty() { None }
598                         else { Some(&self.features) }
599                 };
600
601                 let invoice_request = InvoiceRequestTlvStreamRef {
602                         chain: self.chain.as_ref(),
603                         amount: Some(self.amount_msats),
604                         features,
605                         quantity: self.quantity,
606                         payer_id: Some(&self.payer_id),
607                         payer_note: self.payer_note.as_ref(),
608                 };
609
610                 (payer, offer, invoice_request)
611         }
612 }
613
614 impl Writeable for Refund {
615         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
616                 WithoutLength(&self.bytes).write(writer)
617         }
618 }
619
620 impl Writeable for RefundContents {
621         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
622                 self.as_tlv_stream().write(writer)
623         }
624 }
625
626 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
627
628 type RefundTlvStreamRef<'a> = (
629         PayerTlvStreamRef<'a>,
630         OfferTlvStreamRef<'a>,
631         InvoiceRequestTlvStreamRef<'a>,
632 );
633
634 impl SeekReadable for RefundTlvStream {
635         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
636                 let payer = SeekReadable::read(r)?;
637                 let offer = SeekReadable::read(r)?;
638                 let invoice_request = SeekReadable::read(r)?;
639
640                 Ok((payer, offer, invoice_request))
641         }
642 }
643
644 impl Bech32Encode for Refund {
645         const BECH32_HRP: &'static str = "lnr";
646 }
647
648 impl FromStr for Refund {
649         type Err = Bolt12ParseError;
650
651         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
652                 Refund::from_bech32_str(s)
653         }
654 }
655
656 impl TryFrom<Vec<u8>> for Refund {
657         type Error = Bolt12ParseError;
658
659         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
660                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
661                 let ParsedMessage { bytes, tlv_stream } = refund;
662                 let contents = RefundContents::try_from(tlv_stream)?;
663
664                 Ok(Refund { bytes, contents })
665         }
666 }
667
668 impl TryFrom<RefundTlvStream> for RefundContents {
669         type Error = Bolt12SemanticError;
670
671         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
672                 let (
673                         PayerTlvStream { metadata: payer_metadata },
674                         OfferTlvStream {
675                                 chains, metadata, currency, amount: offer_amount, description,
676                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
677                         },
678                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
679                 ) = tlv_stream;
680
681                 let payer = match payer_metadata {
682                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
683                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
684                 };
685
686                 if metadata.is_some() {
687                         return Err(Bolt12SemanticError::UnexpectedMetadata);
688                 }
689
690                 if chains.is_some() {
691                         return Err(Bolt12SemanticError::UnexpectedChain);
692                 }
693
694                 if currency.is_some() || offer_amount.is_some() {
695                         return Err(Bolt12SemanticError::UnexpectedAmount);
696                 }
697
698                 let description = match description {
699                         None => return Err(Bolt12SemanticError::MissingDescription),
700                         Some(description) => description,
701                 };
702
703                 if offer_features.is_some() {
704                         return Err(Bolt12SemanticError::UnexpectedFeatures);
705                 }
706
707                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
708
709                 if quantity_max.is_some() {
710                         return Err(Bolt12SemanticError::UnexpectedQuantity);
711                 }
712
713                 if node_id.is_some() {
714                         return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
715                 }
716
717                 let amount_msats = match amount {
718                         None => return Err(Bolt12SemanticError::MissingAmount),
719                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
720                                 return Err(Bolt12SemanticError::InvalidAmount);
721                         },
722                         Some(amount_msats) => amount_msats,
723                 };
724
725                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
726
727                 let payer_id = match payer_id {
728                         None => return Err(Bolt12SemanticError::MissingPayerId),
729                         Some(payer_id) => payer_id,
730                 };
731
732                 Ok(RefundContents {
733                         payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
734                         quantity, payer_id, payer_note,
735                 })
736         }
737 }
738
739 impl core::fmt::Display for Refund {
740         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
741                 self.fmt_bech32_str(f)
742         }
743 }
744
745 #[cfg(test)]
746 mod tests {
747         use super::{Refund, RefundBuilder, RefundTlvStreamRef};
748
749         use bitcoin::blockdata::constants::ChainHash;
750         use bitcoin::network::constants::Network;
751         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
752         use core::convert::TryFrom;
753         use core::time::Duration;
754         use crate::blinded_path::{BlindedHop, BlindedPath};
755         use crate::sign::KeyMaterial;
756         use crate::ln::channelmanager::PaymentId;
757         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
758         use crate::ln::inbound_payment::ExpandedKey;
759         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
760         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
761         use crate::offers::offer::OfferTlvStreamRef;
762         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
763         use crate::offers::payer::PayerTlvStreamRef;
764         use crate::offers::test_utils::*;
765         use crate::util::ser::{BigSize, Writeable};
766         use crate::util::string::PrintableString;
767
768         trait ToBytes {
769                 fn to_bytes(&self) -> Vec<u8>;
770         }
771
772         impl<'a> ToBytes for RefundTlvStreamRef<'a> {
773                 fn to_bytes(&self) -> Vec<u8> {
774                         let mut buffer = Vec::new();
775                         self.write(&mut buffer).unwrap();
776                         buffer
777                 }
778         }
779
780         #[test]
781         fn builds_refund_with_defaults() {
782                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
783                         .build().unwrap();
784
785                 let mut buffer = Vec::new();
786                 refund.write(&mut buffer).unwrap();
787
788                 assert_eq!(refund.bytes, buffer.as_slice());
789                 assert_eq!(refund.payer_metadata(), &[1; 32]);
790                 assert_eq!(refund.description(), PrintableString("foo"));
791                 assert_eq!(refund.absolute_expiry(), None);
792                 #[cfg(feature = "std")]
793                 assert!(!refund.is_expired());
794                 assert_eq!(refund.paths(), &[]);
795                 assert_eq!(refund.issuer(), None);
796                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
797                 assert_eq!(refund.amount_msats(), 1000);
798                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
799                 assert_eq!(refund.payer_id(), payer_pubkey());
800                 assert_eq!(refund.payer_note(), None);
801
802                 assert_eq!(
803                         refund.as_tlv_stream(),
804                         (
805                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
806                                 OfferTlvStreamRef {
807                                         chains: None,
808                                         metadata: None,
809                                         currency: None,
810                                         amount: None,
811                                         description: Some(&String::from("foo")),
812                                         features: None,
813                                         absolute_expiry: None,
814                                         paths: None,
815                                         issuer: None,
816                                         quantity_max: None,
817                                         node_id: None,
818                                 },
819                                 InvoiceRequestTlvStreamRef {
820                                         chain: None,
821                                         amount: Some(1000),
822                                         features: None,
823                                         quantity: None,
824                                         payer_id: Some(&payer_pubkey()),
825                                         payer_note: None,
826                                 },
827                         ),
828                 );
829
830                 if let Err(e) = Refund::try_from(buffer) {
831                         panic!("error parsing refund: {:?}", e);
832                 }
833         }
834
835         #[test]
836         fn fails_building_refund_with_invalid_amount() {
837                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
838                         Ok(_) => panic!("expected error"),
839                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
840                 }
841         }
842
843         #[test]
844         fn builds_refund_with_metadata_derived() {
845                 let desc = "foo".to_string();
846                 let node_id = payer_pubkey();
847                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
848                 let entropy = FixedEntropy {};
849                 let secp_ctx = Secp256k1::new();
850                 let payment_id = PaymentId([1; 32]);
851
852                 let refund = RefundBuilder
853                         ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
854                         .unwrap()
855                         .build().unwrap();
856                 assert_eq!(refund.payer_id(), node_id);
857
858                 // Fails verification with altered fields
859                 let invoice = refund
860                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
861                         .unwrap()
862                         .build().unwrap()
863                         .sign(recipient_sign).unwrap();
864                 match invoice.verify(&expanded_key, &secp_ctx) {
865                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
866                         Err(()) => panic!("verification failed"),
867                 }
868
869                 let mut tlv_stream = refund.as_tlv_stream();
870                 tlv_stream.2.amount = Some(2000);
871
872                 let mut encoded_refund = Vec::new();
873                 tlv_stream.write(&mut encoded_refund).unwrap();
874
875                 let invoice = Refund::try_from(encoded_refund).unwrap()
876                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
877                         .unwrap()
878                         .build().unwrap()
879                         .sign(recipient_sign).unwrap();
880                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
881
882                 // Fails verification with altered metadata
883                 let mut tlv_stream = refund.as_tlv_stream();
884                 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
885                 tlv_stream.0.metadata = Some(&metadata);
886
887                 let mut encoded_refund = Vec::new();
888                 tlv_stream.write(&mut encoded_refund).unwrap();
889
890                 let invoice = Refund::try_from(encoded_refund).unwrap()
891                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
892                         .unwrap()
893                         .build().unwrap()
894                         .sign(recipient_sign).unwrap();
895                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
896         }
897
898         #[test]
899         fn builds_refund_with_derived_payer_id() {
900                 let desc = "foo".to_string();
901                 let node_id = payer_pubkey();
902                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
903                 let entropy = FixedEntropy {};
904                 let secp_ctx = Secp256k1::new();
905                 let payment_id = PaymentId([1; 32]);
906
907                 let blinded_path = BlindedPath {
908                         introduction_node_id: pubkey(40),
909                         blinding_point: pubkey(41),
910                         blinded_hops: vec![
911                                 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
912                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
913                         ],
914                 };
915
916                 let refund = RefundBuilder
917                         ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
918                         .unwrap()
919                         .path(blinded_path)
920                         .build().unwrap();
921                 assert_ne!(refund.payer_id(), node_id);
922
923                 let invoice = refund
924                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
925                         .unwrap()
926                         .build().unwrap()
927                         .sign(recipient_sign).unwrap();
928                 match invoice.verify(&expanded_key, &secp_ctx) {
929                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
930                         Err(()) => panic!("verification failed"),
931                 }
932
933                 // Fails verification with altered fields
934                 let mut tlv_stream = refund.as_tlv_stream();
935                 tlv_stream.2.amount = Some(2000);
936
937                 let mut encoded_refund = Vec::new();
938                 tlv_stream.write(&mut encoded_refund).unwrap();
939
940                 let invoice = Refund::try_from(encoded_refund).unwrap()
941                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
942                         .unwrap()
943                         .build().unwrap()
944                         .sign(recipient_sign).unwrap();
945                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
946
947                 // Fails verification with altered payer_id
948                 let mut tlv_stream = refund.as_tlv_stream();
949                 let payer_id = pubkey(1);
950                 tlv_stream.2.payer_id = Some(&payer_id);
951
952                 let mut encoded_refund = Vec::new();
953                 tlv_stream.write(&mut encoded_refund).unwrap();
954
955                 let invoice = Refund::try_from(encoded_refund).unwrap()
956                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
957                         .unwrap()
958                         .build().unwrap()
959                         .sign(recipient_sign).unwrap();
960                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
961         }
962
963         #[test]
964         fn builds_refund_with_absolute_expiry() {
965                 let future_expiry = Duration::from_secs(u64::max_value());
966                 let past_expiry = Duration::from_secs(0);
967
968                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
969                         .absolute_expiry(future_expiry)
970                         .build()
971                         .unwrap();
972                 let (_, tlv_stream, _) = refund.as_tlv_stream();
973                 #[cfg(feature = "std")]
974                 assert!(!refund.is_expired());
975                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
976                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
977
978                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
979                         .absolute_expiry(future_expiry)
980                         .absolute_expiry(past_expiry)
981                         .build()
982                         .unwrap();
983                 let (_, tlv_stream, _) = refund.as_tlv_stream();
984                 #[cfg(feature = "std")]
985                 assert!(refund.is_expired());
986                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
987                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
988         }
989
990         #[test]
991         fn builds_refund_with_paths() {
992                 let paths = vec![
993                         BlindedPath {
994                                 introduction_node_id: pubkey(40),
995                                 blinding_point: pubkey(41),
996                                 blinded_hops: vec![
997                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
998                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
999                                 ],
1000                         },
1001                         BlindedPath {
1002                                 introduction_node_id: pubkey(40),
1003                                 blinding_point: pubkey(41),
1004                                 blinded_hops: vec![
1005                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1006                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1007                                 ],
1008                         },
1009                 ];
1010
1011                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1012                         .path(paths[0].clone())
1013                         .path(paths[1].clone())
1014                         .build()
1015                         .unwrap();
1016                 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1017                 assert_eq!(refund.paths(), paths.as_slice());
1018                 assert_eq!(refund.payer_id(), pubkey(42));
1019                 assert_ne!(pubkey(42), pubkey(44));
1020                 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1021                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1022         }
1023
1024         #[test]
1025         fn builds_refund_with_issuer() {
1026                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1027                         .issuer("bar".into())
1028                         .build()
1029                         .unwrap();
1030                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1031                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1032                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1033
1034                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1035                         .issuer("bar".into())
1036                         .issuer("baz".into())
1037                         .build()
1038                         .unwrap();
1039                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1040                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1041                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1042         }
1043
1044         #[test]
1045         fn builds_refund_with_chain() {
1046                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1047                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1048
1049                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1050                         .chain(Network::Bitcoin)
1051                         .build().unwrap();
1052                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1053                 assert_eq!(refund.chain(), mainnet);
1054                 assert_eq!(tlv_stream.chain, None);
1055
1056                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1057                         .chain(Network::Testnet)
1058                         .build().unwrap();
1059                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1060                 assert_eq!(refund.chain(), testnet);
1061                 assert_eq!(tlv_stream.chain, Some(&testnet));
1062
1063                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1064                         .chain(Network::Regtest)
1065                         .chain(Network::Testnet)
1066                         .build().unwrap();
1067                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1068                 assert_eq!(refund.chain(), testnet);
1069                 assert_eq!(tlv_stream.chain, Some(&testnet));
1070         }
1071
1072         #[test]
1073         fn builds_refund_with_quantity() {
1074                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1075                         .quantity(10)
1076                         .build().unwrap();
1077                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1078                 assert_eq!(refund.quantity(), Some(10));
1079                 assert_eq!(tlv_stream.quantity, Some(10));
1080
1081                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1082                         .quantity(10)
1083                         .quantity(1)
1084                         .build().unwrap();
1085                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1086                 assert_eq!(refund.quantity(), Some(1));
1087                 assert_eq!(tlv_stream.quantity, Some(1));
1088         }
1089
1090         #[test]
1091         fn builds_refund_with_payer_note() {
1092                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1093                         .payer_note("bar".into())
1094                         .build().unwrap();
1095                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1096                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1097                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1098
1099                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1100                         .payer_note("bar".into())
1101                         .payer_note("baz".into())
1102                         .build().unwrap();
1103                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1104                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1105                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1106         }
1107
1108         #[test]
1109         fn fails_responding_with_unknown_required_features() {
1110                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1111                         .features_unchecked(InvoiceRequestFeatures::unknown())
1112                         .build().unwrap()
1113                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1114                 {
1115                         Ok(_) => panic!("expected error"),
1116                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1117                 }
1118         }
1119
1120         #[test]
1121         fn parses_refund_with_metadata() {
1122                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1123                         .build().unwrap();
1124                 if let Err(e) = refund.to_string().parse::<Refund>() {
1125                         panic!("error parsing refund: {:?}", e);
1126                 }
1127
1128                 let mut tlv_stream = refund.as_tlv_stream();
1129                 tlv_stream.0.metadata = None;
1130
1131                 match Refund::try_from(tlv_stream.to_bytes()) {
1132                         Ok(_) => panic!("expected error"),
1133                         Err(e) => {
1134                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1135                         },
1136                 }
1137         }
1138
1139         #[test]
1140         fn parses_refund_with_description() {
1141                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1142                         .build().unwrap();
1143                 if let Err(e) = refund.to_string().parse::<Refund>() {
1144                         panic!("error parsing refund: {:?}", e);
1145                 }
1146
1147                 let mut tlv_stream = refund.as_tlv_stream();
1148                 tlv_stream.1.description = None;
1149
1150                 match Refund::try_from(tlv_stream.to_bytes()) {
1151                         Ok(_) => panic!("expected error"),
1152                         Err(e) => {
1153                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1154                         },
1155                 }
1156         }
1157
1158         #[test]
1159         fn parses_refund_with_amount() {
1160                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1161                         .build().unwrap();
1162                 if let Err(e) = refund.to_string().parse::<Refund>() {
1163                         panic!("error parsing refund: {:?}", e);
1164                 }
1165
1166                 let mut tlv_stream = refund.as_tlv_stream();
1167                 tlv_stream.2.amount = None;
1168
1169                 match Refund::try_from(tlv_stream.to_bytes()) {
1170                         Ok(_) => panic!("expected error"),
1171                         Err(e) => {
1172                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1173                         },
1174                 }
1175
1176                 let mut tlv_stream = refund.as_tlv_stream();
1177                 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1178
1179                 match Refund::try_from(tlv_stream.to_bytes()) {
1180                         Ok(_) => panic!("expected error"),
1181                         Err(e) => {
1182                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1183                         },
1184                 }
1185         }
1186
1187         #[test]
1188         fn parses_refund_with_payer_id() {
1189                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1190                         .build().unwrap();
1191                 if let Err(e) = refund.to_string().parse::<Refund>() {
1192                         panic!("error parsing refund: {:?}", e);
1193                 }
1194
1195                 let mut tlv_stream = refund.as_tlv_stream();
1196                 tlv_stream.2.payer_id = None;
1197
1198                 match Refund::try_from(tlv_stream.to_bytes()) {
1199                         Ok(_) => panic!("expected error"),
1200                         Err(e) => {
1201                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1202                         },
1203                 }
1204         }
1205
1206         #[test]
1207         fn parses_refund_with_optional_fields() {
1208                 let past_expiry = Duration::from_secs(0);
1209                 let paths = vec![
1210                         BlindedPath {
1211                                 introduction_node_id: pubkey(40),
1212                                 blinding_point: pubkey(41),
1213                                 blinded_hops: vec![
1214                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1215                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1216                                 ],
1217                         },
1218                         BlindedPath {
1219                                 introduction_node_id: pubkey(40),
1220                                 blinding_point: pubkey(41),
1221                                 blinded_hops: vec![
1222                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1223                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1224                                 ],
1225                         },
1226                 ];
1227
1228                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1229                         .absolute_expiry(past_expiry)
1230                         .issuer("bar".into())
1231                         .path(paths[0].clone())
1232                         .path(paths[1].clone())
1233                         .chain(Network::Testnet)
1234                         .features_unchecked(InvoiceRequestFeatures::unknown())
1235                         .quantity(10)
1236                         .payer_note("baz".into())
1237                         .build()
1238                         .unwrap();
1239                 match refund.to_string().parse::<Refund>() {
1240                         Ok(refund) => {
1241                                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1242                                 #[cfg(feature = "std")]
1243                                 assert!(refund.is_expired());
1244                                 assert_eq!(refund.paths(), &paths[..]);
1245                                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1246                                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1247                                 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1248                                 assert_eq!(refund.quantity(), Some(10));
1249                                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1250                         },
1251                         Err(e) => panic!("error parsing refund: {:?}", e),
1252                 }
1253         }
1254
1255         #[test]
1256         fn fails_parsing_refund_with_unexpected_fields() {
1257                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1258                         .build().unwrap();
1259                 if let Err(e) = refund.to_string().parse::<Refund>() {
1260                         panic!("error parsing refund: {:?}", e);
1261                 }
1262
1263                 let metadata = vec![42; 32];
1264                 let mut tlv_stream = refund.as_tlv_stream();
1265                 tlv_stream.1.metadata = Some(&metadata);
1266
1267                 match Refund::try_from(tlv_stream.to_bytes()) {
1268                         Ok(_) => panic!("expected error"),
1269                         Err(e) => {
1270                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1271                         },
1272                 }
1273
1274                 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1275                 let mut tlv_stream = refund.as_tlv_stream();
1276                 tlv_stream.1.chains = Some(&chains);
1277
1278                 match Refund::try_from(tlv_stream.to_bytes()) {
1279                         Ok(_) => panic!("expected error"),
1280                         Err(e) => {
1281                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1282                         },
1283                 }
1284
1285                 let mut tlv_stream = refund.as_tlv_stream();
1286                 tlv_stream.1.currency = Some(&b"USD");
1287                 tlv_stream.1.amount = Some(1000);
1288
1289                 match Refund::try_from(tlv_stream.to_bytes()) {
1290                         Ok(_) => panic!("expected error"),
1291                         Err(e) => {
1292                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1293                         },
1294                 }
1295
1296                 let features = OfferFeatures::unknown();
1297                 let mut tlv_stream = refund.as_tlv_stream();
1298                 tlv_stream.1.features = Some(&features);
1299
1300                 match Refund::try_from(tlv_stream.to_bytes()) {
1301                         Ok(_) => panic!("expected error"),
1302                         Err(e) => {
1303                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1304                         },
1305                 }
1306
1307                 let mut tlv_stream = refund.as_tlv_stream();
1308                 tlv_stream.1.quantity_max = Some(10);
1309
1310                 match Refund::try_from(tlv_stream.to_bytes()) {
1311                         Ok(_) => panic!("expected error"),
1312                         Err(e) => {
1313                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1314                         },
1315                 }
1316
1317                 let node_id = payer_pubkey();
1318                 let mut tlv_stream = refund.as_tlv_stream();
1319                 tlv_stream.1.node_id = Some(&node_id);
1320
1321                 match Refund::try_from(tlv_stream.to_bytes()) {
1322                         Ok(_) => panic!("expected error"),
1323                         Err(e) => {
1324                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1325                         },
1326                 }
1327         }
1328
1329         #[test]
1330         fn fails_parsing_refund_with_extra_tlv_records() {
1331                 let secp_ctx = Secp256k1::new();
1332                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1333                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1334                         .build().unwrap();
1335
1336                 let mut encoded_refund = Vec::new();
1337                 refund.write(&mut encoded_refund).unwrap();
1338                 BigSize(1002).write(&mut encoded_refund).unwrap();
1339                 BigSize(32).write(&mut encoded_refund).unwrap();
1340                 [42u8; 32].write(&mut encoded_refund).unwrap();
1341
1342                 match Refund::try_from(encoded_refund) {
1343                         Ok(_) => panic!("expected error"),
1344                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1345                 }
1346         }
1347 }