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