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