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