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