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