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::PaymentHash;
82 use crate::ln::features::InvoiceRequestFeatures;
83 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
84 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
85 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
86 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
87 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
88 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
89 use crate::onion_message::BlindedPath;
90 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
91 use crate::util::string::PrintableString;
93 use crate::prelude::*;
95 #[cfg(feature = "std")]
96 use std::time::SystemTime;
98 /// Builds a [`Refund`] for the "offer for money" flow.
100 /// See [module-level documentation] for usage.
102 /// [module-level documentation]: self
103 pub struct RefundBuilder {
104 refund: RefundContents,
108 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
109 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
111 /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
112 /// [`Refund::amount_msats`].
114 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
115 ) -> Result<Self, SemanticError> {
116 if amount_msats > MAX_VALUE_MSAT {
117 return Err(SemanticError::InvalidAmount);
120 let refund = RefundContents {
121 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
122 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
123 quantity: None, payer_id, payer_note: None,
126 Ok(RefundBuilder { refund })
129 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
130 /// already passed is valid and can be checked for using [`Refund::is_expired`].
132 /// Successive calls to this method will override the previous setting.
133 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
134 self.refund.absolute_expiry = Some(absolute_expiry);
138 /// Sets the [`Refund::issuer`].
140 /// Successive calls to this method will override the previous setting.
141 pub fn issuer(mut self, issuer: String) -> Self {
142 self.refund.issuer = Some(issuer);
146 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
147 /// by private channels or if [`Refund::payer_id`] is not a public node id.
149 /// Successive calls to this method will add another blinded path. Caller is responsible for not
150 /// adding duplicate paths.
151 pub fn path(mut self, path: BlindedPath) -> Self {
152 self.refund.paths.get_or_insert_with(Vec::new).push(path);
156 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
157 /// called, [`Network::Bitcoin`] is assumed.
159 /// Successive calls to this method will override the previous setting.
160 pub fn chain(mut self, network: Network) -> Self {
161 self.refund.chain = Some(ChainHash::using_genesis_block(network));
165 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
166 /// when the refund pertains to an [`Invoice`] that paid for more than one item from an
167 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
169 /// Successive calls to this method will override the previous setting.
171 /// [`Invoice`]: crate::offers::invoice::Invoice
172 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
173 /// [`Offer`]: crate::offers::offer::Offer
174 pub fn quantity(mut self, quantity: u64) -> Self {
175 self.refund.quantity = Some(quantity);
179 /// Sets the [`Refund::payer_note`].
181 /// Successive calls to this method will override the previous setting.
182 pub fn payer_note(mut self, payer_note: String) -> Self {
183 self.refund.payer_note = Some(payer_note);
187 /// Builds a [`Refund`] after checking for valid semantics.
188 pub fn build(mut self) -> Result<Refund, SemanticError> {
189 if self.refund.chain() == self.refund.implied_chain() {
190 self.refund.chain = None;
193 let mut bytes = Vec::new();
194 self.refund.write(&mut bytes).unwrap();
198 contents: self.refund,
205 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
206 self.refund.features = features;
211 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
213 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
214 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
217 /// [`Invoice`]: crate::offers::invoice::Invoice
218 /// [`Offer`]: crate::offers::offer::Offer
219 #[derive(Clone, Debug)]
221 pub(super) bytes: Vec<u8>,
222 pub(super) contents: RefundContents,
225 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
227 /// [`Invoice`]: crate::offers::invoice::Invoice
228 #[derive(Clone, Debug)]
229 pub(super) struct RefundContents {
230 payer: PayerContents,
233 absolute_expiry: Option<Duration>,
234 issuer: Option<String>,
235 paths: Option<Vec<BlindedPath>>,
236 // invoice_request fields
237 chain: Option<ChainHash>,
239 features: InvoiceRequestFeatures,
240 quantity: Option<u64>,
242 payer_note: Option<String>,
246 /// A complete description of the purpose of the refund. Intended to be displayed to the user
247 /// but with the caveat that it has not been verified in any way.
248 pub fn description(&self) -> PrintableString {
249 PrintableString(&self.contents.description)
252 /// Duration since the Unix epoch when an invoice should no longer be sent.
254 /// If `None`, the refund does not expire.
255 pub fn absolute_expiry(&self) -> Option<Duration> {
256 self.contents.absolute_expiry
259 /// Whether the refund has expired.
260 #[cfg(feature = "std")]
261 pub fn is_expired(&self) -> bool {
262 self.contents.is_expired()
265 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
266 /// displayed to the user but with the caveat that it has not been verified in any way.
267 pub fn issuer(&self) -> Option<PrintableString> {
268 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
271 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
272 /// privacy by obfuscating its node id.
273 pub fn paths(&self) -> &[BlindedPath] {
274 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
277 /// An unpredictable series of bytes, typically containing information about the derivation of
280 /// [`payer_id`]: Self::payer_id
281 pub fn metadata(&self) -> &[u8] {
282 &self.contents.payer.0
285 /// A chain that the refund is valid for.
286 pub fn chain(&self) -> ChainHash {
287 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
290 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
292 /// [`chain`]: Self::chain
293 pub fn amount_msats(&self) -> u64 {
294 self.contents.amount_msats
297 /// Features pertaining to requesting an invoice.
298 pub fn features(&self) -> &InvoiceRequestFeatures {
299 &self.contents.features
302 /// The quantity of an item that refund is for.
303 pub fn quantity(&self) -> Option<u64> {
304 self.contents.quantity
307 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
308 /// transient pubkey.
310 /// [`paths`]: Self::paths
311 pub fn payer_id(&self) -> PublicKey {
312 self.contents.payer_id
315 /// Payer provided note to include in the invoice.
316 pub fn payer_note(&self) -> Option<PrintableString> {
317 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
320 /// Creates an [`Invoice`] for the refund with the given required fields.
322 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
323 /// calling this method in `std` builds. For `no-std` builds, a final [`Duration`] parameter
324 /// must be given, which is used to set [`Invoice::created_at`] since [`std::time::SystemTime`]
325 /// is not available.
327 /// The caller is expected to remember the preimage of `payment_hash` in order to
328 /// claim a payment for the invoice.
330 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
331 /// offer, which does have a `signing_pubkey`.
333 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
334 /// must contain one or more elements.
336 /// Errors if the request contains unknown required features.
338 /// [`Invoice`]: crate::offers::invoice::Invoice
339 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
341 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
342 signing_pubkey: PublicKey,
343 #[cfg(any(test, not(feature = "std")))]
345 ) -> Result<InvoiceBuilder, SemanticError> {
346 if self.features().requires_unknown_bits() {
347 return Err(SemanticError::UnknownRequiredFeatures);
350 #[cfg(all(not(test), feature = "std"))]
351 let created_at = std::time::SystemTime::now()
352 .duration_since(std::time::SystemTime::UNIX_EPOCH)
353 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
355 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
359 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
360 self.contents.as_tlv_stream()
364 impl AsRef<[u8]> for Refund {
365 fn as_ref(&self) -> &[u8] {
370 impl RefundContents {
371 #[cfg(feature = "std")]
372 pub(super) fn is_expired(&self) -> bool {
373 match self.absolute_expiry {
374 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
375 Ok(elapsed) => elapsed > seconds_from_epoch,
382 pub(super) fn chain(&self) -> ChainHash {
383 self.chain.unwrap_or_else(|| self.implied_chain())
386 pub fn implied_chain(&self) -> ChainHash {
387 ChainHash::using_genesis_block(Network::Bitcoin)
390 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
391 let payer = PayerTlvStreamRef {
392 metadata: Some(&self.payer.0),
395 let offer = OfferTlvStreamRef {
400 description: Some(&self.description),
402 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
403 paths: self.paths.as_ref(),
404 issuer: self.issuer.as_ref(),
410 if self.features == InvoiceRequestFeatures::empty() { None }
411 else { Some(&self.features) }
414 let invoice_request = InvoiceRequestTlvStreamRef {
415 chain: self.chain.as_ref(),
416 amount: Some(self.amount_msats),
418 quantity: self.quantity,
419 payer_id: Some(&self.payer_id),
420 payer_note: self.payer_note.as_ref(),
423 (payer, offer, invoice_request)
427 impl Writeable for Refund {
428 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
429 WithoutLength(&self.bytes).write(writer)
433 impl Writeable for RefundContents {
434 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
435 self.as_tlv_stream().write(writer)
439 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
441 type RefundTlvStreamRef<'a> = (
442 PayerTlvStreamRef<'a>,
443 OfferTlvStreamRef<'a>,
444 InvoiceRequestTlvStreamRef<'a>,
447 impl SeekReadable for RefundTlvStream {
448 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
449 let payer = SeekReadable::read(r)?;
450 let offer = SeekReadable::read(r)?;
451 let invoice_request = SeekReadable::read(r)?;
453 Ok((payer, offer, invoice_request))
457 impl Bech32Encode for Refund {
458 const BECH32_HRP: &'static str = "lnr";
461 impl FromStr for Refund {
462 type Err = ParseError;
464 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
465 Refund::from_bech32_str(s)
469 impl TryFrom<Vec<u8>> for Refund {
470 type Error = ParseError;
472 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
473 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
474 let ParsedMessage { bytes, tlv_stream } = refund;
475 let contents = RefundContents::try_from(tlv_stream)?;
477 Ok(Refund { bytes, contents })
481 impl TryFrom<RefundTlvStream> for RefundContents {
482 type Error = SemanticError;
484 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
486 PayerTlvStream { metadata: payer_metadata },
488 chains, metadata, currency, amount: offer_amount, description,
489 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
491 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
494 let payer = match payer_metadata {
495 None => return Err(SemanticError::MissingPayerMetadata),
496 Some(metadata) => PayerContents(metadata),
499 if metadata.is_some() {
500 return Err(SemanticError::UnexpectedMetadata);
503 if chains.is_some() {
504 return Err(SemanticError::UnexpectedChain);
507 if currency.is_some() || offer_amount.is_some() {
508 return Err(SemanticError::UnexpectedAmount);
511 let description = match description {
512 None => return Err(SemanticError::MissingDescription),
513 Some(description) => description,
516 if offer_features.is_some() {
517 return Err(SemanticError::UnexpectedFeatures);
520 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
522 if quantity_max.is_some() {
523 return Err(SemanticError::UnexpectedQuantity);
526 if node_id.is_some() {
527 return Err(SemanticError::UnexpectedSigningPubkey);
530 let amount_msats = match amount {
531 None => return Err(SemanticError::MissingAmount),
532 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
533 return Err(SemanticError::InvalidAmount);
535 Some(amount_msats) => amount_msats,
538 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
540 let payer_id = match payer_id {
541 None => return Err(SemanticError::MissingPayerId),
542 Some(payer_id) => payer_id,
546 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
547 quantity, payer_id, payer_note,
552 impl core::fmt::Display for Refund {
553 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
554 self.fmt_bech32_str(f)
560 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
562 use bitcoin::blockdata::constants::ChainHash;
563 use bitcoin::network::constants::Network;
564 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
565 use core::convert::TryFrom;
566 use core::time::Duration;
567 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
568 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
569 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
570 use crate::offers::offer::OfferTlvStreamRef;
571 use crate::offers::parse::{ParseError, SemanticError};
572 use crate::offers::payer::PayerTlvStreamRef;
573 use crate::onion_message::{BlindedHop, BlindedPath};
574 use crate::util::ser::{BigSize, Writeable};
575 use crate::util::string::PrintableString;
577 fn payer_pubkey() -> PublicKey {
578 let secp_ctx = Secp256k1::new();
579 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()).public_key()
582 fn pubkey(byte: u8) -> PublicKey {
583 let secp_ctx = Secp256k1::new();
584 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
587 fn privkey(byte: u8) -> SecretKey {
588 SecretKey::from_slice(&[byte; 32]).unwrap()
592 fn to_bytes(&self) -> Vec<u8>;
595 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
596 fn to_bytes(&self) -> Vec<u8> {
597 let mut buffer = Vec::new();
598 self.write(&mut buffer).unwrap();
604 fn builds_refund_with_defaults() {
605 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
608 let mut buffer = Vec::new();
609 refund.write(&mut buffer).unwrap();
611 assert_eq!(refund.bytes, buffer.as_slice());
612 assert_eq!(refund.metadata(), &[1; 32]);
613 assert_eq!(refund.description(), PrintableString("foo"));
614 assert_eq!(refund.absolute_expiry(), None);
615 #[cfg(feature = "std")]
616 assert!(!refund.is_expired());
617 assert_eq!(refund.paths(), &[]);
618 assert_eq!(refund.issuer(), None);
619 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
620 assert_eq!(refund.amount_msats(), 1000);
621 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
622 assert_eq!(refund.payer_id(), payer_pubkey());
623 assert_eq!(refund.payer_note(), None);
626 refund.as_tlv_stream(),
628 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
634 description: Some(&String::from("foo")),
636 absolute_expiry: None,
642 InvoiceRequestTlvStreamRef {
647 payer_id: Some(&payer_pubkey()),
653 if let Err(e) = Refund::try_from(buffer) {
654 panic!("error parsing refund: {:?}", e);
659 fn fails_building_refund_with_invalid_amount() {
660 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
661 Ok(_) => panic!("expected error"),
662 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
667 fn builds_refund_with_absolute_expiry() {
668 let future_expiry = Duration::from_secs(u64::max_value());
669 let past_expiry = Duration::from_secs(0);
671 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
672 .absolute_expiry(future_expiry)
675 let (_, tlv_stream, _) = refund.as_tlv_stream();
676 #[cfg(feature = "std")]
677 assert!(!refund.is_expired());
678 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
679 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
681 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
682 .absolute_expiry(future_expiry)
683 .absolute_expiry(past_expiry)
686 let (_, tlv_stream, _) = refund.as_tlv_stream();
687 #[cfg(feature = "std")]
688 assert!(refund.is_expired());
689 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
690 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
694 fn builds_refund_with_paths() {
697 introduction_node_id: pubkey(40),
698 blinding_point: pubkey(41),
700 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
701 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
705 introduction_node_id: pubkey(40),
706 blinding_point: pubkey(41),
708 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
709 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
714 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
715 .path(paths[0].clone())
716 .path(paths[1].clone())
719 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
720 assert_eq!(refund.paths(), paths.as_slice());
721 assert_eq!(refund.payer_id(), pubkey(42));
722 assert_ne!(pubkey(42), pubkey(44));
723 assert_eq!(offer_tlv_stream.paths, Some(&paths));
724 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
728 fn builds_refund_with_issuer() {
729 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
730 .issuer("bar".into())
733 let (_, tlv_stream, _) = refund.as_tlv_stream();
734 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
735 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
737 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
738 .issuer("bar".into())
739 .issuer("baz".into())
742 let (_, tlv_stream, _) = refund.as_tlv_stream();
743 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
744 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
748 fn builds_refund_with_chain() {
749 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
750 let testnet = ChainHash::using_genesis_block(Network::Testnet);
752 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
753 .chain(Network::Bitcoin)
755 let (_, _, tlv_stream) = refund.as_tlv_stream();
756 assert_eq!(refund.chain(), mainnet);
757 assert_eq!(tlv_stream.chain, None);
759 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
760 .chain(Network::Testnet)
762 let (_, _, tlv_stream) = refund.as_tlv_stream();
763 assert_eq!(refund.chain(), testnet);
764 assert_eq!(tlv_stream.chain, Some(&testnet));
766 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
767 .chain(Network::Regtest)
768 .chain(Network::Testnet)
770 let (_, _, tlv_stream) = refund.as_tlv_stream();
771 assert_eq!(refund.chain(), testnet);
772 assert_eq!(tlv_stream.chain, Some(&testnet));
776 fn builds_refund_with_quantity() {
777 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
780 let (_, _, tlv_stream) = refund.as_tlv_stream();
781 assert_eq!(refund.quantity(), Some(10));
782 assert_eq!(tlv_stream.quantity, Some(10));
784 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
788 let (_, _, tlv_stream) = refund.as_tlv_stream();
789 assert_eq!(refund.quantity(), Some(1));
790 assert_eq!(tlv_stream.quantity, Some(1));
794 fn builds_refund_with_payer_note() {
795 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
796 .payer_note("bar".into())
798 let (_, _, tlv_stream) = refund.as_tlv_stream();
799 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
800 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
802 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
803 .payer_note("bar".into())
804 .payer_note("baz".into())
806 let (_, _, tlv_stream) = refund.as_tlv_stream();
807 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
808 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
812 fn parses_refund_with_metadata() {
813 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
815 if let Err(e) = refund.to_string().parse::<Refund>() {
816 panic!("error parsing refund: {:?}", e);
819 let mut tlv_stream = refund.as_tlv_stream();
820 tlv_stream.0.metadata = None;
822 match Refund::try_from(tlv_stream.to_bytes()) {
823 Ok(_) => panic!("expected error"),
825 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
831 fn parses_refund_with_description() {
832 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
834 if let Err(e) = refund.to_string().parse::<Refund>() {
835 panic!("error parsing refund: {:?}", e);
838 let mut tlv_stream = refund.as_tlv_stream();
839 tlv_stream.1.description = None;
841 match Refund::try_from(tlv_stream.to_bytes()) {
842 Ok(_) => panic!("expected error"),
844 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
850 fn parses_refund_with_amount() {
851 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
853 if let Err(e) = refund.to_string().parse::<Refund>() {
854 panic!("error parsing refund: {:?}", e);
857 let mut tlv_stream = refund.as_tlv_stream();
858 tlv_stream.2.amount = None;
860 match Refund::try_from(tlv_stream.to_bytes()) {
861 Ok(_) => panic!("expected error"),
863 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
867 let mut tlv_stream = refund.as_tlv_stream();
868 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
870 match Refund::try_from(tlv_stream.to_bytes()) {
871 Ok(_) => panic!("expected error"),
873 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
879 fn parses_refund_with_payer_id() {
880 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
882 if let Err(e) = refund.to_string().parse::<Refund>() {
883 panic!("error parsing refund: {:?}", e);
886 let mut tlv_stream = refund.as_tlv_stream();
887 tlv_stream.2.payer_id = None;
889 match Refund::try_from(tlv_stream.to_bytes()) {
890 Ok(_) => panic!("expected error"),
892 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
898 fn parses_refund_with_optional_fields() {
899 let past_expiry = Duration::from_secs(0);
902 introduction_node_id: pubkey(40),
903 blinding_point: pubkey(41),
905 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
906 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
910 introduction_node_id: pubkey(40),
911 blinding_point: pubkey(41),
913 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
914 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
919 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
920 .absolute_expiry(past_expiry)
921 .issuer("bar".into())
922 .path(paths[0].clone())
923 .path(paths[1].clone())
924 .chain(Network::Testnet)
925 .features_unchecked(InvoiceRequestFeatures::unknown())
927 .payer_note("baz".into())
930 match refund.to_string().parse::<Refund>() {
932 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
933 #[cfg(feature = "std")]
934 assert!(refund.is_expired());
935 assert_eq!(refund.paths(), &paths[..]);
936 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
937 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
938 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
939 assert_eq!(refund.quantity(), Some(10));
940 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
942 Err(e) => panic!("error parsing refund: {:?}", e),
947 fn fails_parsing_refund_with_unexpected_fields() {
948 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
950 if let Err(e) = refund.to_string().parse::<Refund>() {
951 panic!("error parsing refund: {:?}", e);
954 let metadata = vec![42; 32];
955 let mut tlv_stream = refund.as_tlv_stream();
956 tlv_stream.1.metadata = Some(&metadata);
958 match Refund::try_from(tlv_stream.to_bytes()) {
959 Ok(_) => panic!("expected error"),
961 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
965 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
966 let mut tlv_stream = refund.as_tlv_stream();
967 tlv_stream.1.chains = Some(&chains);
969 match Refund::try_from(tlv_stream.to_bytes()) {
970 Ok(_) => panic!("expected error"),
972 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
976 let mut tlv_stream = refund.as_tlv_stream();
977 tlv_stream.1.currency = Some(&b"USD");
978 tlv_stream.1.amount = Some(1000);
980 match Refund::try_from(tlv_stream.to_bytes()) {
981 Ok(_) => panic!("expected error"),
983 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
987 let features = OfferFeatures::unknown();
988 let mut tlv_stream = refund.as_tlv_stream();
989 tlv_stream.1.features = Some(&features);
991 match Refund::try_from(tlv_stream.to_bytes()) {
992 Ok(_) => panic!("expected error"),
994 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
998 let mut tlv_stream = refund.as_tlv_stream();
999 tlv_stream.1.quantity_max = Some(10);
1001 match Refund::try_from(tlv_stream.to_bytes()) {
1002 Ok(_) => panic!("expected error"),
1004 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1008 let node_id = payer_pubkey();
1009 let mut tlv_stream = refund.as_tlv_stream();
1010 tlv_stream.1.node_id = Some(&node_id);
1012 match Refund::try_from(tlv_stream.to_bytes()) {
1013 Ok(_) => panic!("expected error"),
1015 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1021 fn fails_parsing_refund_with_extra_tlv_records() {
1022 let secp_ctx = Secp256k1::new();
1023 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1024 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1027 let mut encoded_refund = Vec::new();
1028 refund.write(&mut encoded_refund).unwrap();
1029 BigSize(1002).write(&mut encoded_refund).unwrap();
1030 BigSize(32).write(&mut encoded_refund).unwrap();
1031 [42u8; 32].write(&mut encoded_refund).unwrap();
1033 match Refund::try_from(encoded_refund) {
1034 Ok(_) => panic!("expected error"),
1035 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),