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