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