1 // This file is Copyright its original authors, visible in version control
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
10 //! Data structures and encoding for refunds.
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.
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
17 //! [`Invoice`]: crate::offers::invoice::Invoice
18 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19 //! [`Offer`]: crate::offers::offer::Offer
22 //! extern crate bitcoin;
23 //! extern crate core;
24 //! extern crate lightning;
26 //! use core::convert::TryFrom;
27 //! use core::time::Duration;
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};
35 //! # use lightning::onion_message::BlindedPath;
36 //! # #[cfg(feature = "std")]
37 //! # use std::time::SystemTime;
39 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
40 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
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);
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())
58 //! // Encode as a bech32 string for use in a QR code.
59 //! let encoded_refund = refund.to_string();
61 //! // Parse from a bech32 string after scanning from a QR code.
62 //! let refund = encoded_refund.parse::<Refund>()?;
64 //! // Encode refund as raw bytes.
65 //! let mut bytes = Vec::new();
66 //! refund.write(&mut bytes).unwrap();
68 //! // Decode raw bytes into an refund.
69 //! let refund = Refund::try_from(bytes)?;
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;
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;
91 use crate::prelude::*;
93 #[cfg(feature = "std")]
94 use std::time::SystemTime;
96 /// Builds a [`Refund`] for the "offer for money" flow.
98 /// See [module-level documentation] for usage.
100 /// [module-level documentation]: self
101 pub struct RefundBuilder {
102 refund: RefundContents,
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.
109 /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
110 /// [`Refund::amount_msats`].
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);
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,
124 Ok(RefundBuilder { refund })
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`].
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);
136 /// Sets the [`Refund::issuer`].
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);
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.
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);
154 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
155 /// called, [`Network::Bitcoin`] is assumed.
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));
163 /// Sets the [`Refund::payer_note`].
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);
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;
177 let mut bytes = Vec::new();
178 self.refund.write(&mut bytes).unwrap();
182 contents: self.refund,
189 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
190 self.refund.features = features;
195 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
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
201 /// [`Invoice`]: crate::offers::invoice::Invoice
202 /// [`Offer`]: crate::offers::offer::Offer
203 #[derive(Clone, Debug)]
206 contents: RefundContents,
209 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
211 /// [`Invoice`]: crate::offers::invoice::Invoice
212 #[derive(Clone, Debug)]
213 pub(super) struct RefundContents {
214 payer: PayerContents,
216 metadata: Option<Vec<u8>>,
218 absolute_expiry: Option<Duration>,
219 issuer: Option<String>,
220 paths: Option<Vec<BlindedPath>>,
221 // invoice_request fields
222 chain: Option<ChainHash>,
224 features: InvoiceRequestFeatures,
226 payer_note: Option<String>,
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)
236 /// Duration since the Unix epoch when an invoice should no longer be sent.
238 /// If `None`, the refund does not expire.
239 pub fn absolute_expiry(&self) -> Option<Duration> {
240 self.contents.absolute_expiry
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,
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()))
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(&[])
267 /// An unpredictable series of bytes, typically containing information about the derivation of
270 /// [`payer_id`]: Self::payer_id
271 pub fn metadata(&self) -> &[u8] {
272 &self.contents.payer.0
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())
280 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
282 /// [`chain`]: Self::chain
283 pub fn amount_msats(&self) -> u64 {
284 self.contents.amount_msats
287 /// Features pertaining to requesting an invoice.
288 pub fn features(&self) -> &InvoiceRequestFeatures {
289 &self.contents.features
292 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
293 /// transient pubkey.
295 /// [`paths`]: Self::paths
296 pub fn payer_id(&self) -> PublicKey {
297 self.contents.payer_id
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()))
306 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
307 self.contents.as_tlv_stream()
311 impl AsRef<[u8]> for Refund {
312 fn as_ref(&self) -> &[u8] {
317 impl RefundContents {
318 pub(super) fn chain(&self) -> ChainHash {
319 self.chain.unwrap_or_else(|| self.implied_chain())
322 pub fn implied_chain(&self) -> ChainHash {
323 ChainHash::using_genesis_block(Network::Bitcoin)
326 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
327 let payer = PayerTlvStreamRef {
328 metadata: Some(&self.payer.0),
331 let offer = OfferTlvStreamRef {
333 metadata: self.metadata.as_ref(),
336 description: Some(&self.description),
338 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
339 paths: self.paths.as_ref(),
340 issuer: self.issuer.as_ref(),
346 if self.features == InvoiceRequestFeatures::empty() { None }
347 else { Some(&self.features) }
350 let invoice_request = InvoiceRequestTlvStreamRef {
351 chain: self.chain.as_ref(),
352 amount: Some(self.amount_msats),
355 payer_id: Some(&self.payer_id),
356 payer_note: self.payer_note.as_ref(),
359 (payer, offer, invoice_request)
363 impl Writeable for Refund {
364 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
365 WithoutLength(&self.bytes).write(writer)
369 impl Writeable for RefundContents {
370 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
371 self.as_tlv_stream().write(writer)
375 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
377 type RefundTlvStreamRef<'a> = (
378 PayerTlvStreamRef<'a>,
379 OfferTlvStreamRef<'a>,
380 InvoiceRequestTlvStreamRef<'a>,
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)?;
389 Ok((payer, offer, invoice_request))
393 impl Bech32Encode for Refund {
394 const BECH32_HRP: &'static str = "lnr";
397 impl FromStr for Refund {
398 type Err = ParseError;
400 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
401 Refund::from_bech32_str(s)
405 impl TryFrom<Vec<u8>> for Refund {
406 type Error = ParseError;
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)?;
413 Ok(Refund { bytes, contents })
417 impl TryFrom<RefundTlvStream> for RefundContents {
418 type Error = SemanticError;
420 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
422 PayerTlvStream { metadata: payer_metadata },
424 chains, metadata, currency, amount: offer_amount, description,
425 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
427 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
430 let payer = match payer_metadata {
431 None => return Err(SemanticError::MissingPayerMetadata),
432 Some(metadata) => PayerContents(metadata),
435 if chains.is_some() {
436 return Err(SemanticError::UnexpectedChain);
439 if currency.is_some() || offer_amount.is_some() {
440 return Err(SemanticError::UnexpectedAmount);
443 let description = match description {
444 None => return Err(SemanticError::MissingDescription),
445 Some(description) => description,
448 if offer_features.is_some() {
449 return Err(SemanticError::UnexpectedFeatures);
452 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
454 if quantity_max.is_some() {
455 return Err(SemanticError::UnexpectedQuantity);
458 if node_id.is_some() {
459 return Err(SemanticError::UnexpectedSigningPubkey);
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);
467 Some(amount_msats) => amount_msats,
470 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
472 // TODO: Check why this isn't in the spec.
473 if quantity.is_some() {
474 return Err(SemanticError::UnexpectedQuantity);
477 let payer_id = match payer_id {
478 None => return Err(SemanticError::MissingPayerId),
479 Some(payer_id) => payer_id,
482 // TODO: Should metadata be included?
484 payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
485 features, payer_id, payer_note,
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)
498 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
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;
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()
520 fn pubkey(byte: u8) -> PublicKey {
521 let secp_ctx = Secp256k1::new();
522 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
525 fn privkey(byte: u8) -> SecretKey {
526 SecretKey::from_slice(&[byte; 32]).unwrap()
530 fn to_bytes(&self) -> Vec<u8>;
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();
542 fn builds_refund_with_defaults() {
543 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
546 let mut buffer = Vec::new();
547 refund.write(&mut buffer).unwrap();
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);
564 refund.as_tlv_stream(),
566 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
572 description: Some(&String::from("foo")),
574 absolute_expiry: None,
580 InvoiceRequestTlvStreamRef {
585 payer_id: Some(&payer_pubkey()),
591 if let Err(e) = Refund::try_from(buffer) {
592 panic!("error parsing refund: {:?}", e);
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),
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);
609 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
610 .absolute_expiry(future_expiry)
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()));
619 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
620 .absolute_expiry(future_expiry)
621 .absolute_expiry(past_expiry)
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()));
632 fn builds_refund_with_paths() {
635 introduction_node_id: pubkey(40),
636 blinding_point: pubkey(41),
638 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
639 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
643 introduction_node_id: pubkey(40),
644 blinding_point: pubkey(41),
646 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
647 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
652 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
653 .path(paths[0].clone())
654 .path(paths[1].clone())
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)));
666 fn builds_refund_with_issuer() {
667 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
668 .issuer("bar".into())
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")));
675 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
676 .issuer("bar".into())
677 .issuer("baz".into())
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")));
686 fn builds_refund_with_chain() {
687 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
688 let testnet = ChainHash::using_genesis_block(Network::Testnet);
690 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
691 .chain(Network::Bitcoin)
693 let (_, _, tlv_stream) = refund.as_tlv_stream();
694 assert_eq!(refund.chain(), mainnet);
695 assert_eq!(tlv_stream.chain, None);
697 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
698 .chain(Network::Testnet)
700 let (_, _, tlv_stream) = refund.as_tlv_stream();
701 assert_eq!(refund.chain(), testnet);
702 assert_eq!(tlv_stream.chain, Some(&testnet));
704 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
705 .chain(Network::Regtest)
706 .chain(Network::Testnet)
708 let (_, _, tlv_stream) = refund.as_tlv_stream();
709 assert_eq!(refund.chain(), testnet);
710 assert_eq!(tlv_stream.chain, Some(&testnet));
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())
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")));
722 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
723 .payer_note("bar".into())
724 .payer_note("baz".into())
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")));
732 fn parses_refund_with_metadata() {
733 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
735 if let Err(e) = refund.to_string().parse::<Refund>() {
736 panic!("error parsing refund: {:?}", e);
739 let mut tlv_stream = refund.as_tlv_stream();
740 tlv_stream.0.metadata = None;
742 match Refund::try_from(tlv_stream.to_bytes()) {
743 Ok(_) => panic!("expected error"),
745 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
751 fn parses_refund_with_description() {
752 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
754 if let Err(e) = refund.to_string().parse::<Refund>() {
755 panic!("error parsing refund: {:?}", e);
758 let mut tlv_stream = refund.as_tlv_stream();
759 tlv_stream.1.description = None;
761 match Refund::try_from(tlv_stream.to_bytes()) {
762 Ok(_) => panic!("expected error"),
764 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
770 fn parses_refund_with_amount() {
771 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
773 if let Err(e) = refund.to_string().parse::<Refund>() {
774 panic!("error parsing refund: {:?}", e);
777 let mut tlv_stream = refund.as_tlv_stream();
778 tlv_stream.2.amount = None;
780 match Refund::try_from(tlv_stream.to_bytes()) {
781 Ok(_) => panic!("expected error"),
783 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
787 let mut tlv_stream = refund.as_tlv_stream();
788 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
790 match Refund::try_from(tlv_stream.to_bytes()) {
791 Ok(_) => panic!("expected error"),
793 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
799 fn parses_refund_with_payer_id() {
800 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
802 if let Err(e) = refund.to_string().parse::<Refund>() {
803 panic!("error parsing refund: {:?}", e);
806 let mut tlv_stream = refund.as_tlv_stream();
807 tlv_stream.2.payer_id = None;
809 match Refund::try_from(tlv_stream.to_bytes()) {
810 Ok(_) => panic!("expected error"),
812 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
818 fn parses_refund_with_optional_fields() {
819 let past_expiry = Duration::from_secs(0);
822 introduction_node_id: pubkey(40),
823 blinding_point: pubkey(41),
825 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
826 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
830 introduction_node_id: pubkey(40),
831 blinding_point: pubkey(41),
833 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
834 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
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())
849 match refund.to_string().parse::<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")));
860 Err(e) => panic!("error parsing refund: {:?}", e),
865 fn fails_parsing_refund_with_unexpected_fields() {
866 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
868 if let Err(e) = refund.to_string().parse::<Refund>() {
869 panic!("error parsing refund: {:?}", e);
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);
876 match Refund::try_from(tlv_stream.to_bytes()) {
877 Ok(_) => panic!("expected error"),
879 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
883 let mut tlv_stream = refund.as_tlv_stream();
884 tlv_stream.1.currency = Some(&b"USD");
885 tlv_stream.1.amount = Some(1000);
887 match Refund::try_from(tlv_stream.to_bytes()) {
888 Ok(_) => panic!("expected error"),
890 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
894 let features = OfferFeatures::unknown();
895 let mut tlv_stream = refund.as_tlv_stream();
896 tlv_stream.1.features = Some(&features);
898 match Refund::try_from(tlv_stream.to_bytes()) {
899 Ok(_) => panic!("expected error"),
901 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
905 let mut tlv_stream = refund.as_tlv_stream();
906 tlv_stream.1.quantity_max = Some(10);
908 match Refund::try_from(tlv_stream.to_bytes()) {
909 Ok(_) => panic!("expected error"),
911 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
915 let node_id = payer_pubkey();
916 let mut tlv_stream = refund.as_tlv_stream();
917 tlv_stream.1.node_id = Some(&node_id);
919 match Refund::try_from(tlv_stream.to_bytes()) {
920 Ok(_) => panic!("expected error"),
922 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
926 let mut tlv_stream = refund.as_tlv_stream();
927 tlv_stream.2.quantity = Some(10);
929 match Refund::try_from(tlv_stream.to_bytes()) {
930 Ok(_) => panic!("expected error"),
932 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
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()
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();
950 match Refund::try_from(encoded_refund) {
951 Ok(_) => panic!("expected error"),
952 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),