1988a92aaa7450262f0a04d1c2ba00d8545beec3
[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(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::constants::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, 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 Writeable for Refund {
773         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
774                 WithoutLength(&self.bytes).write(writer)
775         }
776 }
777
778 impl Writeable for RefundContents {
779         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
780                 self.as_tlv_stream().write(writer)
781         }
782 }
783
784 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
785
786 type RefundTlvStreamRef<'a> = (
787         PayerTlvStreamRef<'a>,
788         OfferTlvStreamRef<'a>,
789         InvoiceRequestTlvStreamRef<'a>,
790 );
791
792 impl SeekReadable for RefundTlvStream {
793         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
794                 let payer = SeekReadable::read(r)?;
795                 let offer = SeekReadable::read(r)?;
796                 let invoice_request = SeekReadable::read(r)?;
797
798                 Ok((payer, offer, invoice_request))
799         }
800 }
801
802 impl Bech32Encode for Refund {
803         const BECH32_HRP: &'static str = "lnr";
804 }
805
806 impl FromStr for Refund {
807         type Err = Bolt12ParseError;
808
809         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
810                 Refund::from_bech32_str(s)
811         }
812 }
813
814 impl TryFrom<Vec<u8>> for Refund {
815         type Error = Bolt12ParseError;
816
817         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
818                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
819                 let ParsedMessage { bytes, tlv_stream } = refund;
820                 let contents = RefundContents::try_from(tlv_stream)?;
821
822                 Ok(Refund { bytes, contents })
823         }
824 }
825
826 impl TryFrom<RefundTlvStream> for RefundContents {
827         type Error = Bolt12SemanticError;
828
829         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
830                 let (
831                         PayerTlvStream { metadata: payer_metadata },
832                         OfferTlvStream {
833                                 chains, metadata, currency, amount: offer_amount, description,
834                                 features: offer_features, absolute_expiry, paths: offer_paths, issuer, quantity_max,
835                                 node_id,
836                         },
837                         InvoiceRequestTlvStream {
838                                 chain, amount, features, quantity, payer_id, payer_note, paths
839                         },
840                 ) = tlv_stream;
841
842                 let payer = match payer_metadata {
843                         None => return Err(Bolt12SemanticError::MissingPayerMetadata),
844                         Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
845                 };
846
847                 if metadata.is_some() {
848                         return Err(Bolt12SemanticError::UnexpectedMetadata);
849                 }
850
851                 if chains.is_some() {
852                         return Err(Bolt12SemanticError::UnexpectedChain);
853                 }
854
855                 if currency.is_some() || offer_amount.is_some() {
856                         return Err(Bolt12SemanticError::UnexpectedAmount);
857                 }
858
859                 let description = match description {
860                         None => return Err(Bolt12SemanticError::MissingDescription),
861                         Some(description) => description,
862                 };
863
864                 if offer_features.is_some() {
865                         return Err(Bolt12SemanticError::UnexpectedFeatures);
866                 }
867
868                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
869
870                 if offer_paths.is_some() {
871                         return Err(Bolt12SemanticError::UnexpectedPaths);
872                 }
873
874                 if quantity_max.is_some() {
875                         return Err(Bolt12SemanticError::UnexpectedQuantity);
876                 }
877
878                 if node_id.is_some() {
879                         return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
880                 }
881
882                 let amount_msats = match amount {
883                         None => return Err(Bolt12SemanticError::MissingAmount),
884                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
885                                 return Err(Bolt12SemanticError::InvalidAmount);
886                         },
887                         Some(amount_msats) => amount_msats,
888                 };
889
890                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
891
892                 let payer_id = match payer_id {
893                         None => return Err(Bolt12SemanticError::MissingPayerId),
894                         Some(payer_id) => payer_id,
895                 };
896
897                 Ok(RefundContents {
898                         payer, description, absolute_expiry, issuer, chain, amount_msats, features, quantity,
899                         payer_id, payer_note, paths,
900                 })
901         }
902 }
903
904 impl core::fmt::Display for Refund {
905         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
906                 self.fmt_bech32_str(f)
907         }
908 }
909
910 #[cfg(test)]
911 mod tests {
912         use super::{Refund, RefundTlvStreamRef};
913         #[cfg(not(c_bindings))]
914         use {
915                 super::RefundBuilder,
916         };
917         #[cfg(c_bindings)]
918         use {
919                 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
920         };
921
922         use bitcoin::blockdata::constants::ChainHash;
923         use bitcoin::network::constants::Network;
924         use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
925
926         use core::time::Duration;
927
928         use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
929         use crate::sign::KeyMaterial;
930         use crate::ln::channelmanager::PaymentId;
931         use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
932         use crate::ln::inbound_payment::ExpandedKey;
933         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
934         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
935         use crate::offers::offer::OfferTlvStreamRef;
936         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
937         use crate::offers::payer::PayerTlvStreamRef;
938         use crate::offers::test_utils::*;
939         use crate::util::ser::{BigSize, Writeable};
940         use crate::util::string::PrintableString;
941         use crate::prelude::*;
942
943         trait ToBytes {
944                 fn to_bytes(&self) -> Vec<u8>;
945         }
946
947         impl<'a> ToBytes for RefundTlvStreamRef<'a> {
948                 fn to_bytes(&self) -> Vec<u8> {
949                         let mut buffer = Vec::new();
950                         self.write(&mut buffer).unwrap();
951                         buffer
952                 }
953         }
954
955         #[test]
956         fn builds_refund_with_defaults() {
957                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
958                         .build().unwrap();
959
960                 let mut buffer = Vec::new();
961                 refund.write(&mut buffer).unwrap();
962
963                 assert_eq!(refund.bytes, buffer.as_slice());
964                 assert_eq!(refund.payer_metadata(), &[1; 32]);
965                 assert_eq!(refund.description(), PrintableString(""));
966                 assert_eq!(refund.absolute_expiry(), None);
967                 #[cfg(feature = "std")]
968                 assert!(!refund.is_expired());
969                 assert_eq!(refund.paths(), &[]);
970                 assert_eq!(refund.issuer(), None);
971                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
972                 assert_eq!(refund.amount_msats(), 1000);
973                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
974                 assert_eq!(refund.payer_id(), payer_pubkey());
975                 assert_eq!(refund.payer_note(), None);
976
977                 assert_eq!(
978                         refund.as_tlv_stream(),
979                         (
980                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
981                                 OfferTlvStreamRef {
982                                         chains: None,
983                                         metadata: None,
984                                         currency: None,
985                                         amount: None,
986                                         description: Some(&String::from("")),
987                                         features: None,
988                                         absolute_expiry: None,
989                                         paths: None,
990                                         issuer: None,
991                                         quantity_max: None,
992                                         node_id: None,
993                                 },
994                                 InvoiceRequestTlvStreamRef {
995                                         chain: None,
996                                         amount: Some(1000),
997                                         features: None,
998                                         quantity: None,
999                                         payer_id: Some(&payer_pubkey()),
1000                                         payer_note: None,
1001                                         paths: None,
1002                                 },
1003                         ),
1004                 );
1005
1006                 if let Err(e) = Refund::try_from(buffer) {
1007                         panic!("error parsing refund: {:?}", e);
1008                 }
1009         }
1010
1011         #[test]
1012         fn fails_building_refund_with_invalid_amount() {
1013                 match RefundBuilder::new(vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
1014                         Ok(_) => panic!("expected error"),
1015                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1016                 }
1017         }
1018
1019         #[test]
1020         fn builds_refund_with_metadata_derived() {
1021                 let node_id = payer_pubkey();
1022                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1023                 let entropy = FixedEntropy {};
1024                 let secp_ctx = Secp256k1::new();
1025                 let payment_id = PaymentId([1; 32]);
1026
1027                 let refund = RefundBuilder
1028                         ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1029                         .unwrap()
1030                         .build().unwrap();
1031                 assert_eq!(refund.payer_id(), node_id);
1032
1033                 // Fails verification with altered fields
1034                 let invoice = refund
1035                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1036                         .unwrap()
1037                         .build().unwrap()
1038                         .sign(recipient_sign).unwrap();
1039                 match invoice.verify(&expanded_key, &secp_ctx) {
1040                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1041                         Err(()) => panic!("verification failed"),
1042                 }
1043
1044                 let mut tlv_stream = refund.as_tlv_stream();
1045                 tlv_stream.2.amount = Some(2000);
1046
1047                 let mut encoded_refund = Vec::new();
1048                 tlv_stream.write(&mut encoded_refund).unwrap();
1049
1050                 let invoice = Refund::try_from(encoded_refund).unwrap()
1051                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1052                         .unwrap()
1053                         .build().unwrap()
1054                         .sign(recipient_sign).unwrap();
1055                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1056
1057                 // Fails verification with altered metadata
1058                 let mut tlv_stream = refund.as_tlv_stream();
1059                 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1060                 tlv_stream.0.metadata = Some(&metadata);
1061
1062                 let mut encoded_refund = Vec::new();
1063                 tlv_stream.write(&mut encoded_refund).unwrap();
1064
1065                 let invoice = Refund::try_from(encoded_refund).unwrap()
1066                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1067                         .unwrap()
1068                         .build().unwrap()
1069                         .sign(recipient_sign).unwrap();
1070                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1071         }
1072
1073         #[test]
1074         fn builds_refund_with_derived_payer_id() {
1075                 let node_id = payer_pubkey();
1076                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1077                 let entropy = FixedEntropy {};
1078                 let secp_ctx = Secp256k1::new();
1079                 let payment_id = PaymentId([1; 32]);
1080
1081                 let blinded_path = BlindedPath {
1082                         introduction_node: IntroductionNode::NodeId(pubkey(40)),
1083                         blinding_point: pubkey(41),
1084                         blinded_hops: vec![
1085                                 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1086                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1087                         ],
1088                 };
1089
1090                 let refund = RefundBuilder
1091                         ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1092                         .unwrap()
1093                         .path(blinded_path)
1094                         .build().unwrap();
1095                 assert_ne!(refund.payer_id(), node_id);
1096
1097                 let invoice = refund
1098                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1099                         .unwrap()
1100                         .build().unwrap()
1101                         .sign(recipient_sign).unwrap();
1102                 match invoice.verify(&expanded_key, &secp_ctx) {
1103                         Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1104                         Err(()) => panic!("verification failed"),
1105                 }
1106
1107                 // Fails verification with altered fields
1108                 let mut tlv_stream = refund.as_tlv_stream();
1109                 tlv_stream.2.amount = Some(2000);
1110
1111                 let mut encoded_refund = Vec::new();
1112                 tlv_stream.write(&mut encoded_refund).unwrap();
1113
1114                 let invoice = Refund::try_from(encoded_refund).unwrap()
1115                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1116                         .unwrap()
1117                         .build().unwrap()
1118                         .sign(recipient_sign).unwrap();
1119                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1120
1121                 // Fails verification with altered payer_id
1122                 let mut tlv_stream = refund.as_tlv_stream();
1123                 let payer_id = pubkey(1);
1124                 tlv_stream.2.payer_id = Some(&payer_id);
1125
1126                 let mut encoded_refund = Vec::new();
1127                 tlv_stream.write(&mut encoded_refund).unwrap();
1128
1129                 let invoice = Refund::try_from(encoded_refund).unwrap()
1130                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1131                         .unwrap()
1132                         .build().unwrap()
1133                         .sign(recipient_sign).unwrap();
1134                 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1135         }
1136
1137         #[test]
1138         fn builds_refund_with_absolute_expiry() {
1139                 let future_expiry = Duration::from_secs(u64::max_value());
1140                 let past_expiry = Duration::from_secs(0);
1141                 let now = future_expiry - Duration::from_secs(1_000);
1142
1143                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1144                         .absolute_expiry(future_expiry)
1145                         .build()
1146                         .unwrap();
1147                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1148                 #[cfg(feature = "std")]
1149                 assert!(!refund.is_expired());
1150                 assert!(!refund.is_expired_no_std(now));
1151                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1152                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1153
1154                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1155                         .absolute_expiry(future_expiry)
1156                         .absolute_expiry(past_expiry)
1157                         .build()
1158                         .unwrap();
1159                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1160                 #[cfg(feature = "std")]
1161                 assert!(refund.is_expired());
1162                 assert!(refund.is_expired_no_std(now));
1163                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1164                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1165         }
1166
1167         #[test]
1168         fn builds_refund_with_paths() {
1169                 let paths = vec![
1170                         BlindedPath {
1171                                 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1172                                 blinding_point: pubkey(41),
1173                                 blinded_hops: vec![
1174                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1175                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1176                                 ],
1177                         },
1178                         BlindedPath {
1179                                 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1180                                 blinding_point: pubkey(41),
1181                                 blinded_hops: vec![
1182                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1183                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1184                                 ],
1185                         },
1186                 ];
1187
1188                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1189                         .path(paths[0].clone())
1190                         .path(paths[1].clone())
1191                         .build()
1192                         .unwrap();
1193                 let (_, _, invoice_request_tlv_stream) = refund.as_tlv_stream();
1194                 assert_eq!(refund.payer_id(), pubkey(42));
1195                 assert_eq!(refund.paths(), paths.as_slice());
1196                 assert_ne!(pubkey(42), pubkey(44));
1197                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1198                 assert_eq!(invoice_request_tlv_stream.paths, Some(&paths));
1199         }
1200
1201         #[test]
1202         fn builds_refund_with_issuer() {
1203                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1204                         .issuer("bar".into())
1205                         .build()
1206                         .unwrap();
1207                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1208                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1209                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1210
1211                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1212                         .issuer("bar".into())
1213                         .issuer("baz".into())
1214                         .build()
1215                         .unwrap();
1216                 let (_, tlv_stream, _) = refund.as_tlv_stream();
1217                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1218                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1219         }
1220
1221         #[test]
1222         fn builds_refund_with_chain() {
1223                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1224                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1225
1226                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1227                         .chain(Network::Bitcoin)
1228                         .build().unwrap();
1229                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1230                 assert_eq!(refund.chain(), mainnet);
1231                 assert_eq!(tlv_stream.chain, None);
1232
1233                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1234                         .chain(Network::Testnet)
1235                         .build().unwrap();
1236                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1237                 assert_eq!(refund.chain(), testnet);
1238                 assert_eq!(tlv_stream.chain, Some(&testnet));
1239
1240                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1241                         .chain(Network::Regtest)
1242                         .chain(Network::Testnet)
1243                         .build().unwrap();
1244                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1245                 assert_eq!(refund.chain(), testnet);
1246                 assert_eq!(tlv_stream.chain, Some(&testnet));
1247         }
1248
1249         #[test]
1250         fn builds_refund_with_quantity() {
1251                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1252                         .quantity(10)
1253                         .build().unwrap();
1254                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1255                 assert_eq!(refund.quantity(), Some(10));
1256                 assert_eq!(tlv_stream.quantity, Some(10));
1257
1258                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1259                         .quantity(10)
1260                         .quantity(1)
1261                         .build().unwrap();
1262                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1263                 assert_eq!(refund.quantity(), Some(1));
1264                 assert_eq!(tlv_stream.quantity, Some(1));
1265         }
1266
1267         #[test]
1268         fn builds_refund_with_payer_note() {
1269                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1270                         .payer_note("bar".into())
1271                         .build().unwrap();
1272                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1273                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1274                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1275
1276                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1277                         .payer_note("bar".into())
1278                         .payer_note("baz".into())
1279                         .build().unwrap();
1280                 let (_, _, tlv_stream) = refund.as_tlv_stream();
1281                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1282                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1283         }
1284
1285         #[test]
1286         fn fails_responding_with_unknown_required_features() {
1287                 match RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1288                         .features_unchecked(InvoiceRequestFeatures::unknown())
1289                         .build().unwrap()
1290                         .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1291                 {
1292                         Ok(_) => panic!("expected error"),
1293                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1294                 }
1295         }
1296
1297         #[test]
1298         fn parses_refund_with_metadata() {
1299                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1300                         .build().unwrap();
1301                 if let Err(e) = refund.to_string().parse::<Refund>() {
1302                         panic!("error parsing refund: {:?}", e);
1303                 }
1304
1305                 let mut tlv_stream = refund.as_tlv_stream();
1306                 tlv_stream.0.metadata = None;
1307
1308                 match Refund::try_from(tlv_stream.to_bytes()) {
1309                         Ok(_) => panic!("expected error"),
1310                         Err(e) => {
1311                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1312                         },
1313                 }
1314         }
1315
1316         #[test]
1317         fn parses_refund_with_description() {
1318                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1319                         .build().unwrap();
1320                 if let Err(e) = refund.to_string().parse::<Refund>() {
1321                         panic!("error parsing refund: {:?}", e);
1322                 }
1323
1324                 let mut tlv_stream = refund.as_tlv_stream();
1325                 tlv_stream.1.description = None;
1326
1327                 match Refund::try_from(tlv_stream.to_bytes()) {
1328                         Ok(_) => panic!("expected error"),
1329                         Err(e) => {
1330                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1331                         },
1332                 }
1333         }
1334
1335         #[test]
1336         fn parses_refund_with_amount() {
1337                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1338                         .build().unwrap();
1339                 if let Err(e) = refund.to_string().parse::<Refund>() {
1340                         panic!("error parsing refund: {:?}", e);
1341                 }
1342
1343                 let mut tlv_stream = refund.as_tlv_stream();
1344                 tlv_stream.2.amount = None;
1345
1346                 match Refund::try_from(tlv_stream.to_bytes()) {
1347                         Ok(_) => panic!("expected error"),
1348                         Err(e) => {
1349                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1350                         },
1351                 }
1352
1353                 let mut tlv_stream = refund.as_tlv_stream();
1354                 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1355
1356                 match Refund::try_from(tlv_stream.to_bytes()) {
1357                         Ok(_) => panic!("expected error"),
1358                         Err(e) => {
1359                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1360                         },
1361                 }
1362         }
1363
1364         #[test]
1365         fn parses_refund_with_payer_id() {
1366                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1367                         .build().unwrap();
1368                 if let Err(e) = refund.to_string().parse::<Refund>() {
1369                         panic!("error parsing refund: {:?}", e);
1370                 }
1371
1372                 let mut tlv_stream = refund.as_tlv_stream();
1373                 tlv_stream.2.payer_id = None;
1374
1375                 match Refund::try_from(tlv_stream.to_bytes()) {
1376                         Ok(_) => panic!("expected error"),
1377                         Err(e) => {
1378                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1379                         },
1380                 }
1381         }
1382
1383         #[test]
1384         fn parses_refund_with_optional_fields() {
1385                 let past_expiry = Duration::from_secs(0);
1386                 let paths = vec![
1387                         BlindedPath {
1388                                 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1389                                 blinding_point: pubkey(41),
1390                                 blinded_hops: vec![
1391                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1392                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1393                                 ],
1394                         },
1395                         BlindedPath {
1396                                 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1397                                 blinding_point: pubkey(41),
1398                                 blinded_hops: vec![
1399                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1400                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1401                                 ],
1402                         },
1403                 ];
1404
1405                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1406                         .absolute_expiry(past_expiry)
1407                         .issuer("bar".into())
1408                         .path(paths[0].clone())
1409                         .path(paths[1].clone())
1410                         .chain(Network::Testnet)
1411                         .features_unchecked(InvoiceRequestFeatures::unknown())
1412                         .quantity(10)
1413                         .payer_note("baz".into())
1414                         .build()
1415                         .unwrap();
1416                 match refund.to_string().parse::<Refund>() {
1417                         Ok(refund) => {
1418                                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1419                                 #[cfg(feature = "std")]
1420                                 assert!(refund.is_expired());
1421                                 assert_eq!(refund.paths(), &paths[..]);
1422                                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1423                                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1424                                 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1425                                 assert_eq!(refund.quantity(), Some(10));
1426                                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1427                         },
1428                         Err(e) => panic!("error parsing refund: {:?}", e),
1429                 }
1430         }
1431
1432         #[test]
1433         fn fails_parsing_refund_with_unexpected_fields() {
1434                 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1435                         .build().unwrap();
1436                 if let Err(e) = refund.to_string().parse::<Refund>() {
1437                         panic!("error parsing refund: {:?}", e);
1438                 }
1439
1440                 let metadata = vec![42; 32];
1441                 let mut tlv_stream = refund.as_tlv_stream();
1442                 tlv_stream.1.metadata = Some(&metadata);
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::UnexpectedMetadata));
1448                         },
1449                 }
1450
1451                 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1452                 let mut tlv_stream = refund.as_tlv_stream();
1453                 tlv_stream.1.chains = Some(&chains);
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::UnexpectedChain));
1459                         },
1460                 }
1461
1462                 let mut tlv_stream = refund.as_tlv_stream();
1463                 tlv_stream.1.currency = Some(&b"USD");
1464                 tlv_stream.1.amount = Some(1000);
1465
1466                 match Refund::try_from(tlv_stream.to_bytes()) {
1467                         Ok(_) => panic!("expected error"),
1468                         Err(e) => {
1469                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1470                         },
1471                 }
1472
1473                 let features = OfferFeatures::unknown();
1474                 let mut tlv_stream = refund.as_tlv_stream();
1475                 tlv_stream.1.features = Some(&features);
1476
1477                 match Refund::try_from(tlv_stream.to_bytes()) {
1478                         Ok(_) => panic!("expected error"),
1479                         Err(e) => {
1480                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1481                         },
1482                 }
1483
1484                 let mut tlv_stream = refund.as_tlv_stream();
1485                 tlv_stream.1.quantity_max = Some(10);
1486
1487                 match Refund::try_from(tlv_stream.to_bytes()) {
1488                         Ok(_) => panic!("expected error"),
1489                         Err(e) => {
1490                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1491                         },
1492                 }
1493
1494                 let node_id = payer_pubkey();
1495                 let mut tlv_stream = refund.as_tlv_stream();
1496                 tlv_stream.1.node_id = Some(&node_id);
1497
1498                 match Refund::try_from(tlv_stream.to_bytes()) {
1499                         Ok(_) => panic!("expected error"),
1500                         Err(e) => {
1501                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1502                         },
1503                 }
1504         }
1505
1506         #[test]
1507         fn fails_parsing_refund_with_extra_tlv_records() {
1508                 let secp_ctx = Secp256k1::new();
1509                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1510                 let refund = RefundBuilder::new(vec![1; 32], keys.public_key(), 1000).unwrap()
1511                         .build().unwrap();
1512
1513                 let mut encoded_refund = Vec::new();
1514                 refund.write(&mut encoded_refund).unwrap();
1515                 BigSize(1002).write(&mut encoded_refund).unwrap();
1516                 BigSize(32).write(&mut encoded_refund).unwrap();
1517                 [42u8; 32].write(&mut encoded_refund).unwrap();
1518
1519                 match Refund::try_from(encoded_refund) {
1520                         Ok(_) => panic!("expected error"),
1521                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1522                 }
1523         }
1524 }