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