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