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