Refund building tests
[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 signing invoices. Use
106         /// a different pubkey per refund to avoid correlating refunds.
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 /// A `Refund` is a request to send an `Invoice` without a preceding [`Offer`].
187 ///
188 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
189 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
190 /// bitcoin ATM.
191 ///
192 /// [`Offer`]: crate::offers::offer::Offer
193 #[derive(Clone, Debug)]
194 pub struct Refund {
195         bytes: Vec<u8>,
196         contents: RefundContents,
197 }
198
199 /// The contents of a [`Refund`], which may be shared with an `Invoice`.
200 #[derive(Clone, Debug)]
201 struct RefundContents {
202         payer: PayerContents,
203         // offer fields
204         metadata: Option<Vec<u8>>,
205         description: String,
206         absolute_expiry: Option<Duration>,
207         issuer: Option<String>,
208         paths: Option<Vec<BlindedPath>>,
209         // invoice_request fields
210         chain: Option<ChainHash>,
211         amount_msats: u64,
212         features: InvoiceRequestFeatures,
213         payer_id: PublicKey,
214         payer_note: Option<String>,
215 }
216
217 impl Refund {
218         /// A complete description of the purpose of the refund. Intended to be displayed to the user
219         /// but with the caveat that it has not been verified in any way.
220         pub fn description(&self) -> PrintableString {
221                 PrintableString(&self.contents.description)
222         }
223
224         /// Duration since the Unix epoch when an invoice should no longer be sent.
225         ///
226         /// If `None`, the refund does not expire.
227         pub fn absolute_expiry(&self) -> Option<Duration> {
228                 self.contents.absolute_expiry
229         }
230
231         /// Whether the refund has expired.
232         #[cfg(feature = "std")]
233         pub fn is_expired(&self) -> bool {
234                 match self.absolute_expiry() {
235                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
236                                 Ok(elapsed) => elapsed > seconds_from_epoch,
237                                 Err(_) => false,
238                         },
239                         None => false,
240                 }
241         }
242
243         /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
244         /// displayed to the user but with the caveat that it has not been verified in any way.
245         pub fn issuer(&self) -> Option<PrintableString> {
246                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
247         }
248
249         /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
250         /// privacy by obfuscating its node id.
251         pub fn paths(&self) -> &[BlindedPath] {
252                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
253         }
254
255         /// An unpredictable series of bytes, typically containing information about the derivation of
256         /// [`payer_id`].
257         ///
258         /// [`payer_id`]: Self::payer_id
259         pub fn metadata(&self) -> &[u8] {
260                 &self.contents.payer.0
261         }
262
263         /// A chain that the refund is valid for.
264         pub fn chain(&self) -> ChainHash {
265                 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
266         }
267
268         /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
269         ///
270         /// [`chain`]: Self::chain
271         pub fn amount_msats(&self) -> u64 {
272                 self.contents.amount_msats
273         }
274
275         /// Features pertaining to requesting an invoice.
276         pub fn features(&self) -> &InvoiceRequestFeatures {
277                 &self.contents.features
278         }
279
280         /// A possibly transient pubkey used to sign the refund.
281         pub fn payer_id(&self) -> PublicKey {
282                 self.contents.payer_id
283         }
284
285         /// Payer provided note to include in the invoice.
286         pub fn payer_note(&self) -> Option<PrintableString> {
287                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
288         }
289
290         #[cfg(test)]
291         fn as_tlv_stream(&self) -> RefundTlvStreamRef {
292                 self.contents.as_tlv_stream()
293         }
294 }
295
296 impl AsRef<[u8]> for Refund {
297         fn as_ref(&self) -> &[u8] {
298                 &self.bytes
299         }
300 }
301
302 impl RefundContents {
303         fn chain(&self) -> ChainHash {
304                 self.chain.unwrap_or_else(|| self.implied_chain())
305         }
306
307         pub fn implied_chain(&self) -> ChainHash {
308                 ChainHash::using_genesis_block(Network::Bitcoin)
309         }
310
311         pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
312                 let payer = PayerTlvStreamRef {
313                         metadata: Some(&self.payer.0),
314                 };
315
316                 let offer = OfferTlvStreamRef {
317                         chains: None,
318                         metadata: self.metadata.as_ref(),
319                         currency: None,
320                         amount: None,
321                         description: Some(&self.description),
322                         features: None,
323                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
324                         paths: self.paths.as_ref(),
325                         issuer: self.issuer.as_ref(),
326                         quantity_max: None,
327                         node_id: None,
328                 };
329
330                 let features = {
331                         if self.features == InvoiceRequestFeatures::empty() { None }
332                         else { Some(&self.features) }
333                 };
334
335                 let invoice_request = InvoiceRequestTlvStreamRef {
336                         chain: self.chain.as_ref(),
337                         amount: Some(self.amount_msats),
338                         features,
339                         quantity: None,
340                         payer_id: Some(&self.payer_id),
341                         payer_note: self.payer_note.as_ref(),
342                 };
343
344                 (payer, offer, invoice_request)
345         }
346 }
347
348 impl Writeable for Refund {
349         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
350                 WithoutLength(&self.bytes).write(writer)
351         }
352 }
353
354 impl Writeable for RefundContents {
355         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
356                 self.as_tlv_stream().write(writer)
357         }
358 }
359
360 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
361
362 type RefundTlvStreamRef<'a> = (
363         PayerTlvStreamRef<'a>,
364         OfferTlvStreamRef<'a>,
365         InvoiceRequestTlvStreamRef<'a>,
366 );
367
368 impl SeekReadable for RefundTlvStream {
369         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
370                 let payer = SeekReadable::read(r)?;
371                 let offer = SeekReadable::read(r)?;
372                 let invoice_request = SeekReadable::read(r)?;
373
374                 Ok((payer, offer, invoice_request))
375         }
376 }
377
378 impl Bech32Encode for Refund {
379         const BECH32_HRP: &'static str = "lnr";
380 }
381
382 impl FromStr for Refund {
383         type Err = ParseError;
384
385         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
386                 Refund::from_bech32_str(s)
387         }
388 }
389
390 impl TryFrom<Vec<u8>> for Refund {
391         type Error = ParseError;
392
393         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
394                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
395                 let ParsedMessage { bytes, tlv_stream } = refund;
396                 let contents = RefundContents::try_from(tlv_stream)?;
397
398                 Ok(Refund { bytes, contents })
399         }
400 }
401
402 impl TryFrom<RefundTlvStream> for RefundContents {
403         type Error = SemanticError;
404
405         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
406                 let (
407                         PayerTlvStream { metadata: payer_metadata },
408                         OfferTlvStream {
409                                 chains, metadata, currency, amount: offer_amount, description,
410                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
411                         },
412                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
413                 ) = tlv_stream;
414
415                 let payer = match payer_metadata {
416                         None => return Err(SemanticError::MissingPayerMetadata),
417                         Some(metadata) => PayerContents(metadata),
418                 };
419
420                 if chains.is_some() {
421                         return Err(SemanticError::UnexpectedChain);
422                 }
423
424                 if currency.is_some() || offer_amount.is_some() {
425                         return Err(SemanticError::UnexpectedAmount);
426                 }
427
428                 let description = match description {
429                         None => return Err(SemanticError::MissingDescription),
430                         Some(description) => description,
431                 };
432
433                 if offer_features.is_some() {
434                         return Err(SemanticError::UnexpectedFeatures);
435                 }
436
437                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
438
439                 if quantity_max.is_some() {
440                         return Err(SemanticError::UnexpectedQuantity);
441                 }
442
443                 if node_id.is_some() {
444                         return Err(SemanticError::UnexpectedSigningPubkey);
445                 }
446
447                 let amount_msats = match amount {
448                         None => return Err(SemanticError::MissingAmount),
449                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
450                                 return Err(SemanticError::InvalidAmount);
451                         },
452                         Some(amount_msats) => amount_msats,
453                 };
454
455                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
456
457                 // TODO: Check why this isn't in the spec.
458                 if quantity.is_some() {
459                         return Err(SemanticError::UnexpectedQuantity);
460                 }
461
462                 let payer_id = match payer_id {
463                         None => return Err(SemanticError::MissingPayerId),
464                         Some(payer_id) => payer_id,
465                 };
466
467                 // TODO: Should metadata be included?
468                 Ok(RefundContents {
469                         payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
470                         features, payer_id, payer_note,
471                 })
472         }
473 }
474
475 impl core::fmt::Display for Refund {
476         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
477                 self.fmt_bech32_str(f)
478         }
479 }
480
481 #[cfg(test)]
482 mod tests {
483         use super::{Refund, RefundBuilder};
484
485         use bitcoin::blockdata::constants::ChainHash;
486         use bitcoin::network::constants::Network;
487         use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
488         use core::convert::TryFrom;
489         use core::time::Duration;
490         use crate::ln::features::InvoiceRequestFeatures;
491         use crate::ln::msgs::MAX_VALUE_MSAT;
492         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
493         use crate::offers::offer::OfferTlvStreamRef;
494         use crate::offers::parse::SemanticError;
495         use crate::offers::payer::PayerTlvStreamRef;
496         use crate::onion_message::{BlindedHop, BlindedPath};
497         use crate::util::ser::Writeable;
498         use crate::util::string::PrintableString;
499
500         fn payer_pubkey() -> PublicKey {
501                 let secp_ctx = Secp256k1::new();
502                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()).public_key()
503         }
504
505         fn pubkey(byte: u8) -> PublicKey {
506                 let secp_ctx = Secp256k1::new();
507                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
508         }
509
510         fn privkey(byte: u8) -> SecretKey {
511                 SecretKey::from_slice(&[byte; 32]).unwrap()
512         }
513
514         #[test]
515         fn builds_refund_with_defaults() {
516                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
517                         .build().unwrap();
518
519                 let mut buffer = Vec::new();
520                 refund.write(&mut buffer).unwrap();
521
522                 assert_eq!(refund.bytes, buffer.as_slice());
523                 assert_eq!(refund.metadata(), &[1; 32]);
524                 assert_eq!(refund.description(), PrintableString("foo"));
525                 assert_eq!(refund.absolute_expiry(), None);
526                 #[cfg(feature = "std")]
527                 assert!(!refund.is_expired());
528                 assert_eq!(refund.paths(), &[]);
529                 assert_eq!(refund.issuer(), None);
530                 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
531                 assert_eq!(refund.amount_msats(), 1000);
532                 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
533                 assert_eq!(refund.payer_id(), payer_pubkey());
534                 assert_eq!(refund.payer_note(), None);
535
536                 assert_eq!(
537                         refund.as_tlv_stream(),
538                         (
539                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
540                                 OfferTlvStreamRef {
541                                         chains: None,
542                                         metadata: None,
543                                         currency: None,
544                                         amount: None,
545                                         description: Some(&String::from("foo")),
546                                         features: None,
547                                         absolute_expiry: None,
548                                         paths: None,
549                                         issuer: None,
550                                         quantity_max: None,
551                                         node_id: None,
552                                 },
553                                 InvoiceRequestTlvStreamRef {
554                                         chain: None,
555                                         amount: Some(1000),
556                                         features: None,
557                                         quantity: None,
558                                         payer_id: Some(&payer_pubkey()),
559                                         payer_note: None,
560                                 },
561                         ),
562                 );
563
564                 if let Err(e) = Refund::try_from(buffer) {
565                         panic!("error parsing refund: {:?}", e);
566                 }
567         }
568
569         #[test]
570         fn fails_building_refund_with_invalid_amount() {
571                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
572                         Ok(_) => panic!("expected error"),
573                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
574                 }
575         }
576
577         #[test]
578         fn builds_refund_with_absolute_expiry() {
579                 let future_expiry = Duration::from_secs(u64::max_value());
580                 let past_expiry = Duration::from_secs(0);
581
582                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
583                         .absolute_expiry(future_expiry)
584                         .build()
585                         .unwrap();
586                 let (_, tlv_stream, _) = refund.as_tlv_stream();
587                 #[cfg(feature = "std")]
588                 assert!(!refund.is_expired());
589                 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
590                 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
591
592                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
593                         .absolute_expiry(future_expiry)
594                         .absolute_expiry(past_expiry)
595                         .build()
596                         .unwrap();
597                 let (_, tlv_stream, _) = refund.as_tlv_stream();
598                 #[cfg(feature = "std")]
599                 assert!(refund.is_expired());
600                 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
601                 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
602         }
603
604         #[test]
605         fn builds_refund_with_paths() {
606                 let paths = vec![
607                         BlindedPath {
608                                 introduction_node_id: pubkey(40),
609                                 blinding_point: pubkey(41),
610                                 blinded_hops: vec![
611                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
612                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
613                                 ],
614                         },
615                         BlindedPath {
616                                 introduction_node_id: pubkey(40),
617                                 blinding_point: pubkey(41),
618                                 blinded_hops: vec![
619                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
620                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
621                                 ],
622                         },
623                 ];
624
625                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
626                         .path(paths[0].clone())
627                         .path(paths[1].clone())
628                         .build()
629                         .unwrap();
630                 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
631                 assert_eq!(refund.paths(), paths.as_slice());
632                 assert_eq!(refund.payer_id(), pubkey(42));
633                 assert_ne!(pubkey(42), pubkey(44));
634                 assert_eq!(offer_tlv_stream.paths, Some(&paths));
635                 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
636         }
637
638         #[test]
639         fn builds_refund_with_issuer() {
640                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
641                         .issuer("bar".into())
642                         .build()
643                         .unwrap();
644                 let (_, tlv_stream, _) = refund.as_tlv_stream();
645                 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
646                 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
647
648                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
649                         .issuer("bar".into())
650                         .issuer("baz".into())
651                         .build()
652                         .unwrap();
653                 let (_, tlv_stream, _) = refund.as_tlv_stream();
654                 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
655                 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
656         }
657
658         #[test]
659         fn builds_refund_with_chain() {
660                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
661                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
662
663                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
664                         .chain(Network::Bitcoin)
665                         .build().unwrap();
666                 let (_, _, tlv_stream) = refund.as_tlv_stream();
667                 assert_eq!(refund.chain(), mainnet);
668                 assert_eq!(tlv_stream.chain, None);
669
670                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
671                         .chain(Network::Testnet)
672                         .build().unwrap();
673                 let (_, _, tlv_stream) = refund.as_tlv_stream();
674                 assert_eq!(refund.chain(), testnet);
675                 assert_eq!(tlv_stream.chain, Some(&testnet));
676
677                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
678                         .chain(Network::Regtest)
679                         .chain(Network::Testnet)
680                         .build().unwrap();
681                 let (_, _, tlv_stream) = refund.as_tlv_stream();
682                 assert_eq!(refund.chain(), testnet);
683                 assert_eq!(tlv_stream.chain, Some(&testnet));
684         }
685
686         #[test]
687         fn builds_refund_with_payer_note() {
688                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
689                         .payer_note("bar".into())
690                         .build().unwrap();
691                 let (_, _, tlv_stream) = refund.as_tlv_stream();
692                 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
693                 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
694
695                 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
696                         .payer_note("bar".into())
697                         .payer_note("baz".into())
698                         .build().unwrap();
699                 let (_, _, tlv_stream) = refund.as_tlv_stream();
700                 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
701                 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
702         }
703 }