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