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