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