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