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