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, Secp256k1, self};
77 use core::convert::TryFrom;
79 use core::str::FromStr;
80 use core::time::Duration;
81 use crate::chain::keysinterface::EntropySource;
83 use crate::ln::PaymentHash;
84 use crate::ln::features::InvoiceRequestFeatures;
85 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
86 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
87 use crate::offers::invoice::{BlindedPayInfo, InvoiceBuilder};
88 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
89 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
90 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
91 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
92 use crate::offers::signer::{Metadata, MetadataMaterial};
93 use crate::onion_message::BlindedPath;
94 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
95 use crate::util::string::PrintableString;
97 use crate::prelude::*;
99 #[cfg(feature = "std")]
100 use std::time::SystemTime;
102 const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
104 /// Builds a [`Refund`] for the "offer for money" flow.
106 /// See [module-level documentation] for usage.
108 /// [module-level documentation]: self
109 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
110 refund: RefundContents,
111 secp_ctx: Option<&'a Secp256k1<T>>,
114 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
115 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
116 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
118 /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
119 /// [`Refund::amount_msats`].
121 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
122 ) -> Result<Self, SemanticError> {
123 if amount_msats > MAX_VALUE_MSAT {
124 return Err(SemanticError::InvalidAmount);
127 let metadata = Metadata::Bytes(metadata);
129 refund: RefundContents {
130 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
131 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
132 quantity: None, payer_id, payer_note: None,
139 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
140 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
141 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
142 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
143 /// provided `node_id` is used for the payer id.
145 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
146 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
148 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
149 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
150 pub fn deriving_payer_id<ES: Deref>(
151 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
152 secp_ctx: &'a Secp256k1<T>, amount_msats: u64
153 ) -> Result<Self, SemanticError> where ES::Target: EntropySource {
154 if amount_msats > MAX_VALUE_MSAT {
155 return Err(SemanticError::InvalidAmount);
158 let nonce = Nonce::from_entropy_source(entropy_source);
159 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
160 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
162 refund: RefundContents {
163 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
164 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
165 quantity: None, payer_id: node_id, payer_note: None,
167 secp_ctx: Some(secp_ctx),
171 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
172 /// already passed is valid and can be checked for using [`Refund::is_expired`].
174 /// Successive calls to this method will override the previous setting.
175 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
176 self.refund.absolute_expiry = Some(absolute_expiry);
180 /// Sets the [`Refund::issuer`].
182 /// Successive calls to this method will override the previous setting.
183 pub fn issuer(mut self, issuer: String) -> Self {
184 self.refund.issuer = Some(issuer);
188 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
189 /// by private channels or if [`Refund::payer_id`] is not a public node id.
191 /// Successive calls to this method will add another blinded path. Caller is responsible for not
192 /// adding duplicate paths.
193 pub fn path(mut self, path: BlindedPath) -> Self {
194 self.refund.paths.get_or_insert_with(Vec::new).push(path);
198 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
199 /// called, [`Network::Bitcoin`] is assumed.
201 /// Successive calls to this method will override the previous setting.
202 pub fn chain(mut self, network: Network) -> Self {
203 self.refund.chain = Some(ChainHash::using_genesis_block(network));
207 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
208 /// when the refund pertains to an [`Invoice`] that paid for more than one item from an
209 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
211 /// Successive calls to this method will override the previous setting.
213 /// [`Invoice`]: crate::offers::invoice::Invoice
214 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
215 /// [`Offer`]: crate::offers::offer::Offer
216 pub fn quantity(mut self, quantity: u64) -> Self {
217 self.refund.quantity = Some(quantity);
221 /// Sets the [`Refund::payer_note`].
223 /// Successive calls to this method will override the previous setting.
224 pub fn payer_note(mut self, payer_note: String) -> Self {
225 self.refund.payer_note = Some(payer_note);
229 /// Builds a [`Refund`] after checking for valid semantics.
230 pub fn build(mut self) -> Result<Refund, SemanticError> {
231 if self.refund.chain() == self.refund.implied_chain() {
232 self.refund.chain = None;
235 // Create the metadata for stateless verification of an Invoice.
236 if self.refund.payer.0.has_derivation_material() {
237 let mut metadata = core::mem::take(&mut self.refund.payer.0);
239 if self.refund.paths.is_none() {
240 metadata = metadata.without_keys();
243 let mut tlv_stream = self.refund.as_tlv_stream();
244 tlv_stream.0.metadata = None;
245 if metadata.derives_keys() {
246 tlv_stream.2.payer_id = None;
249 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
250 metadata = derived_metadata;
251 if let Some(keys) = keys {
252 self.refund.payer_id = keys.public_key();
255 self.refund.payer.0 = metadata;
258 let mut bytes = Vec::new();
259 self.refund.write(&mut bytes).unwrap();
261 Ok(Refund { bytes, contents: self.refund })
266 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
267 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
268 self.refund.features = features;
273 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
275 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
276 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
279 /// [`Invoice`]: crate::offers::invoice::Invoice
280 /// [`Offer`]: crate::offers::offer::Offer
281 #[derive(Clone, Debug)]
282 #[cfg_attr(test, derive(PartialEq))]
284 pub(super) bytes: Vec<u8>,
285 pub(super) contents: RefundContents,
288 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
290 /// [`Invoice`]: crate::offers::invoice::Invoice
291 #[derive(Clone, Debug)]
292 #[cfg_attr(test, derive(PartialEq))]
293 pub(super) struct RefundContents {
294 payer: PayerContents,
297 absolute_expiry: Option<Duration>,
298 issuer: Option<String>,
299 paths: Option<Vec<BlindedPath>>,
300 // invoice_request fields
301 chain: Option<ChainHash>,
303 features: InvoiceRequestFeatures,
304 quantity: Option<u64>,
306 payer_note: Option<String>,
310 /// A complete description of the purpose of the refund. Intended to be displayed to the user
311 /// but with the caveat that it has not been verified in any way.
312 pub fn description(&self) -> PrintableString {
313 PrintableString(&self.contents.description)
316 /// Duration since the Unix epoch when an invoice should no longer be sent.
318 /// If `None`, the refund does not expire.
319 pub fn absolute_expiry(&self) -> Option<Duration> {
320 self.contents.absolute_expiry
323 /// Whether the refund has expired.
324 #[cfg(feature = "std")]
325 pub fn is_expired(&self) -> bool {
326 self.contents.is_expired()
329 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
330 /// displayed to the user but with the caveat that it has not been verified in any way.
331 pub fn issuer(&self) -> Option<PrintableString> {
332 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
335 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
336 /// privacy by obfuscating its node id.
337 pub fn paths(&self) -> &[BlindedPath] {
338 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
341 /// An unpredictable series of bytes, typically containing information about the derivation of
344 /// [`payer_id`]: Self::payer_id
345 pub fn metadata(&self) -> &[u8] {
346 self.contents.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
349 /// A chain that the refund is valid for.
350 pub fn chain(&self) -> ChainHash {
351 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
354 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
356 /// [`chain`]: Self::chain
357 pub fn amount_msats(&self) -> u64 {
358 self.contents.amount_msats
361 /// Features pertaining to requesting an invoice.
362 pub fn features(&self) -> &InvoiceRequestFeatures {
363 &self.contents.features
366 /// The quantity of an item that refund is for.
367 pub fn quantity(&self) -> Option<u64> {
368 self.contents.quantity
371 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
372 /// transient pubkey.
374 /// [`paths`]: Self::paths
375 pub fn payer_id(&self) -> PublicKey {
376 self.contents.payer_id
379 /// Payer provided note to include in the invoice.
380 pub fn payer_note(&self) -> Option<PrintableString> {
381 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
384 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
385 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
387 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
388 /// time is used for the `created_at` parameter.
390 /// [`Duration`]: core::time::Duration
391 #[cfg(feature = "std")]
393 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
394 signing_pubkey: PublicKey,
395 ) -> Result<InvoiceBuilder, SemanticError> {
396 let created_at = std::time::SystemTime::now()
397 .duration_since(std::time::SystemTime::UNIX_EPOCH)
398 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
400 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
403 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
405 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
406 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
407 /// [`std::time::SystemTime`] is not available.
409 /// The caller is expected to remember the preimage of `payment_hash` in order to
410 /// claim a payment for the invoice.
412 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
413 /// offer, which does have a `signing_pubkey`.
415 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
416 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
417 /// a preference. Note, however, that any privacy is lost if a public node id is used for
418 /// `signing_pubkey`.
420 /// Errors if the request contains unknown required features.
422 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
423 pub fn respond_with_no_std(
424 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
425 signing_pubkey: PublicKey, created_at: Duration
426 ) -> Result<InvoiceBuilder, SemanticError> {
427 if self.features().requires_unknown_bits() {
428 return Err(SemanticError::UnknownRequiredFeatures);
431 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
435 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
436 self.contents.as_tlv_stream()
440 impl AsRef<[u8]> for Refund {
441 fn as_ref(&self) -> &[u8] {
446 impl RefundContents {
447 #[cfg(feature = "std")]
448 pub(super) fn is_expired(&self) -> bool {
449 match self.absolute_expiry {
450 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
451 Ok(elapsed) => elapsed > seconds_from_epoch,
458 pub(super) fn chain(&self) -> ChainHash {
459 self.chain.unwrap_or_else(|| self.implied_chain())
462 pub fn implied_chain(&self) -> ChainHash {
463 ChainHash::using_genesis_block(Network::Bitcoin)
466 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
467 let payer = PayerTlvStreamRef {
468 metadata: self.payer.0.as_bytes(),
471 let offer = OfferTlvStreamRef {
476 description: Some(&self.description),
478 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
479 paths: self.paths.as_ref(),
480 issuer: self.issuer.as_ref(),
486 if self.features == InvoiceRequestFeatures::empty() { None }
487 else { Some(&self.features) }
490 let invoice_request = InvoiceRequestTlvStreamRef {
491 chain: self.chain.as_ref(),
492 amount: Some(self.amount_msats),
494 quantity: self.quantity,
495 payer_id: Some(&self.payer_id),
496 payer_note: self.payer_note.as_ref(),
499 (payer, offer, invoice_request)
503 impl Writeable for Refund {
504 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
505 WithoutLength(&self.bytes).write(writer)
509 impl Writeable for RefundContents {
510 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
511 self.as_tlv_stream().write(writer)
515 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
517 type RefundTlvStreamRef<'a> = (
518 PayerTlvStreamRef<'a>,
519 OfferTlvStreamRef<'a>,
520 InvoiceRequestTlvStreamRef<'a>,
523 impl SeekReadable for RefundTlvStream {
524 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
525 let payer = SeekReadable::read(r)?;
526 let offer = SeekReadable::read(r)?;
527 let invoice_request = SeekReadable::read(r)?;
529 Ok((payer, offer, invoice_request))
533 impl Bech32Encode for Refund {
534 const BECH32_HRP: &'static str = "lnr";
537 impl FromStr for Refund {
538 type Err = ParseError;
540 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
541 Refund::from_bech32_str(s)
545 impl TryFrom<Vec<u8>> for Refund {
546 type Error = ParseError;
548 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
549 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
550 let ParsedMessage { bytes, tlv_stream } = refund;
551 let contents = RefundContents::try_from(tlv_stream)?;
553 Ok(Refund { bytes, contents })
557 impl TryFrom<RefundTlvStream> for RefundContents {
558 type Error = SemanticError;
560 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
562 PayerTlvStream { metadata: payer_metadata },
564 chains, metadata, currency, amount: offer_amount, description,
565 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
567 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
570 let payer = match payer_metadata {
571 None => return Err(SemanticError::MissingPayerMetadata),
572 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
575 if metadata.is_some() {
576 return Err(SemanticError::UnexpectedMetadata);
579 if chains.is_some() {
580 return Err(SemanticError::UnexpectedChain);
583 if currency.is_some() || offer_amount.is_some() {
584 return Err(SemanticError::UnexpectedAmount);
587 let description = match description {
588 None => return Err(SemanticError::MissingDescription),
589 Some(description) => description,
592 if offer_features.is_some() {
593 return Err(SemanticError::UnexpectedFeatures);
596 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
598 if quantity_max.is_some() {
599 return Err(SemanticError::UnexpectedQuantity);
602 if node_id.is_some() {
603 return Err(SemanticError::UnexpectedSigningPubkey);
606 let amount_msats = match amount {
607 None => return Err(SemanticError::MissingAmount),
608 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
609 return Err(SemanticError::InvalidAmount);
611 Some(amount_msats) => amount_msats,
614 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
616 let payer_id = match payer_id {
617 None => return Err(SemanticError::MissingPayerId),
618 Some(payer_id) => payer_id,
622 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
623 quantity, payer_id, payer_note,
628 impl core::fmt::Display for Refund {
629 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
630 self.fmt_bech32_str(f)
636 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
638 use bitcoin::blockdata::constants::ChainHash;
639 use bitcoin::network::constants::Network;
640 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
641 use core::convert::TryFrom;
642 use core::time::Duration;
643 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
644 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
645 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
646 use crate::offers::offer::OfferTlvStreamRef;
647 use crate::offers::parse::{ParseError, SemanticError};
648 use crate::offers::payer::PayerTlvStreamRef;
649 use crate::offers::test_utils::*;
650 use crate::onion_message::{BlindedHop, BlindedPath};
651 use crate::util::ser::{BigSize, Writeable};
652 use crate::util::string::PrintableString;
655 fn to_bytes(&self) -> Vec<u8>;
658 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
659 fn to_bytes(&self) -> Vec<u8> {
660 let mut buffer = Vec::new();
661 self.write(&mut buffer).unwrap();
667 fn builds_refund_with_defaults() {
668 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
671 let mut buffer = Vec::new();
672 refund.write(&mut buffer).unwrap();
674 assert_eq!(refund.bytes, buffer.as_slice());
675 assert_eq!(refund.metadata(), &[1; 32]);
676 assert_eq!(refund.description(), PrintableString("foo"));
677 assert_eq!(refund.absolute_expiry(), None);
678 #[cfg(feature = "std")]
679 assert!(!refund.is_expired());
680 assert_eq!(refund.paths(), &[]);
681 assert_eq!(refund.issuer(), None);
682 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
683 assert_eq!(refund.amount_msats(), 1000);
684 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
685 assert_eq!(refund.payer_id(), payer_pubkey());
686 assert_eq!(refund.payer_note(), None);
689 refund.as_tlv_stream(),
691 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
697 description: Some(&String::from("foo")),
699 absolute_expiry: None,
705 InvoiceRequestTlvStreamRef {
710 payer_id: Some(&payer_pubkey()),
716 if let Err(e) = Refund::try_from(buffer) {
717 panic!("error parsing refund: {:?}", e);
722 fn fails_building_refund_with_invalid_amount() {
723 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
724 Ok(_) => panic!("expected error"),
725 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
730 fn builds_refund_with_absolute_expiry() {
731 let future_expiry = Duration::from_secs(u64::max_value());
732 let past_expiry = Duration::from_secs(0);
734 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
735 .absolute_expiry(future_expiry)
738 let (_, tlv_stream, _) = refund.as_tlv_stream();
739 #[cfg(feature = "std")]
740 assert!(!refund.is_expired());
741 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
742 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
744 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
745 .absolute_expiry(future_expiry)
746 .absolute_expiry(past_expiry)
749 let (_, tlv_stream, _) = refund.as_tlv_stream();
750 #[cfg(feature = "std")]
751 assert!(refund.is_expired());
752 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
753 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
757 fn builds_refund_with_paths() {
760 introduction_node_id: pubkey(40),
761 blinding_point: pubkey(41),
763 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
764 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
768 introduction_node_id: pubkey(40),
769 blinding_point: pubkey(41),
771 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
772 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
777 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
778 .path(paths[0].clone())
779 .path(paths[1].clone())
782 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
783 assert_eq!(refund.paths(), paths.as_slice());
784 assert_eq!(refund.payer_id(), pubkey(42));
785 assert_ne!(pubkey(42), pubkey(44));
786 assert_eq!(offer_tlv_stream.paths, Some(&paths));
787 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
791 fn builds_refund_with_issuer() {
792 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
793 .issuer("bar".into())
796 let (_, tlv_stream, _) = refund.as_tlv_stream();
797 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
798 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
800 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
801 .issuer("bar".into())
802 .issuer("baz".into())
805 let (_, tlv_stream, _) = refund.as_tlv_stream();
806 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
807 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
811 fn builds_refund_with_chain() {
812 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
813 let testnet = ChainHash::using_genesis_block(Network::Testnet);
815 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
816 .chain(Network::Bitcoin)
818 let (_, _, tlv_stream) = refund.as_tlv_stream();
819 assert_eq!(refund.chain(), mainnet);
820 assert_eq!(tlv_stream.chain, None);
822 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
823 .chain(Network::Testnet)
825 let (_, _, tlv_stream) = refund.as_tlv_stream();
826 assert_eq!(refund.chain(), testnet);
827 assert_eq!(tlv_stream.chain, Some(&testnet));
829 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
830 .chain(Network::Regtest)
831 .chain(Network::Testnet)
833 let (_, _, tlv_stream) = refund.as_tlv_stream();
834 assert_eq!(refund.chain(), testnet);
835 assert_eq!(tlv_stream.chain, Some(&testnet));
839 fn builds_refund_with_quantity() {
840 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
843 let (_, _, tlv_stream) = refund.as_tlv_stream();
844 assert_eq!(refund.quantity(), Some(10));
845 assert_eq!(tlv_stream.quantity, Some(10));
847 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
851 let (_, _, tlv_stream) = refund.as_tlv_stream();
852 assert_eq!(refund.quantity(), Some(1));
853 assert_eq!(tlv_stream.quantity, Some(1));
857 fn builds_refund_with_payer_note() {
858 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
859 .payer_note("bar".into())
861 let (_, _, tlv_stream) = refund.as_tlv_stream();
862 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
863 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
865 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
866 .payer_note("bar".into())
867 .payer_note("baz".into())
869 let (_, _, tlv_stream) = refund.as_tlv_stream();
870 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
871 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
875 fn fails_responding_with_unknown_required_features() {
876 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
877 .features_unchecked(InvoiceRequestFeatures::unknown())
879 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
881 Ok(_) => panic!("expected error"),
882 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
887 fn parses_refund_with_metadata() {
888 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
890 if let Err(e) = refund.to_string().parse::<Refund>() {
891 panic!("error parsing refund: {:?}", e);
894 let mut tlv_stream = refund.as_tlv_stream();
895 tlv_stream.0.metadata = None;
897 match Refund::try_from(tlv_stream.to_bytes()) {
898 Ok(_) => panic!("expected error"),
900 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
906 fn parses_refund_with_description() {
907 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
909 if let Err(e) = refund.to_string().parse::<Refund>() {
910 panic!("error parsing refund: {:?}", e);
913 let mut tlv_stream = refund.as_tlv_stream();
914 tlv_stream.1.description = None;
916 match Refund::try_from(tlv_stream.to_bytes()) {
917 Ok(_) => panic!("expected error"),
919 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
925 fn parses_refund_with_amount() {
926 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
928 if let Err(e) = refund.to_string().parse::<Refund>() {
929 panic!("error parsing refund: {:?}", e);
932 let mut tlv_stream = refund.as_tlv_stream();
933 tlv_stream.2.amount = None;
935 match Refund::try_from(tlv_stream.to_bytes()) {
936 Ok(_) => panic!("expected error"),
938 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
942 let mut tlv_stream = refund.as_tlv_stream();
943 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
945 match Refund::try_from(tlv_stream.to_bytes()) {
946 Ok(_) => panic!("expected error"),
948 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
954 fn parses_refund_with_payer_id() {
955 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
957 if let Err(e) = refund.to_string().parse::<Refund>() {
958 panic!("error parsing refund: {:?}", e);
961 let mut tlv_stream = refund.as_tlv_stream();
962 tlv_stream.2.payer_id = None;
964 match Refund::try_from(tlv_stream.to_bytes()) {
965 Ok(_) => panic!("expected error"),
967 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
973 fn parses_refund_with_optional_fields() {
974 let past_expiry = Duration::from_secs(0);
977 introduction_node_id: pubkey(40),
978 blinding_point: pubkey(41),
980 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
981 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
985 introduction_node_id: pubkey(40),
986 blinding_point: pubkey(41),
988 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
989 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
994 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
995 .absolute_expiry(past_expiry)
996 .issuer("bar".into())
997 .path(paths[0].clone())
998 .path(paths[1].clone())
999 .chain(Network::Testnet)
1000 .features_unchecked(InvoiceRequestFeatures::unknown())
1002 .payer_note("baz".into())
1005 match refund.to_string().parse::<Refund>() {
1007 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1008 #[cfg(feature = "std")]
1009 assert!(refund.is_expired());
1010 assert_eq!(refund.paths(), &paths[..]);
1011 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1012 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1013 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1014 assert_eq!(refund.quantity(), Some(10));
1015 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1017 Err(e) => panic!("error parsing refund: {:?}", e),
1022 fn fails_parsing_refund_with_unexpected_fields() {
1023 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1025 if let Err(e) = refund.to_string().parse::<Refund>() {
1026 panic!("error parsing refund: {:?}", e);
1029 let metadata = vec![42; 32];
1030 let mut tlv_stream = refund.as_tlv_stream();
1031 tlv_stream.1.metadata = Some(&metadata);
1033 match Refund::try_from(tlv_stream.to_bytes()) {
1034 Ok(_) => panic!("expected error"),
1036 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
1040 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1041 let mut tlv_stream = refund.as_tlv_stream();
1042 tlv_stream.1.chains = Some(&chains);
1044 match Refund::try_from(tlv_stream.to_bytes()) {
1045 Ok(_) => panic!("expected error"),
1047 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
1051 let mut tlv_stream = refund.as_tlv_stream();
1052 tlv_stream.1.currency = Some(&b"USD");
1053 tlv_stream.1.amount = Some(1000);
1055 match Refund::try_from(tlv_stream.to_bytes()) {
1056 Ok(_) => panic!("expected error"),
1058 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
1062 let features = OfferFeatures::unknown();
1063 let mut tlv_stream = refund.as_tlv_stream();
1064 tlv_stream.1.features = Some(&features);
1066 match Refund::try_from(tlv_stream.to_bytes()) {
1067 Ok(_) => panic!("expected error"),
1069 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
1073 let mut tlv_stream = refund.as_tlv_stream();
1074 tlv_stream.1.quantity_max = Some(10);
1076 match Refund::try_from(tlv_stream.to_bytes()) {
1077 Ok(_) => panic!("expected error"),
1079 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1083 let node_id = payer_pubkey();
1084 let mut tlv_stream = refund.as_tlv_stream();
1085 tlv_stream.1.node_id = Some(&node_id);
1087 match Refund::try_from(tlv_stream.to_bytes()) {
1088 Ok(_) => panic!("expected error"),
1090 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1096 fn fails_parsing_refund_with_extra_tlv_records() {
1097 let secp_ctx = Secp256k1::new();
1098 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1099 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1102 let mut encoded_refund = Vec::new();
1103 refund.write(&mut encoded_refund).unwrap();
1104 BigSize(1002).write(&mut encoded_refund).unwrap();
1105 BigSize(32).write(&mut encoded_refund).unwrap();
1106 [42u8; 32].write(&mut encoded_refund).unwrap();
1108 match Refund::try_from(encoded_refund) {
1109 Ok(_) => panic!("expected error"),
1110 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),