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