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