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