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