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::blinded_path::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::sign::EntropySource;
83 use crate::blinded_path::BlindedPath;
84 use crate::ln::PaymentHash;
85 use crate::ln::features::InvoiceRequestFeatures;
86 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
87 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
88 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
89 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
90 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
91 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
92 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
93 use crate::offers::signer::{Metadata, MetadataMaterial, self};
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 pub(super) 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 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
110 /// [module-level documentation]: self
111 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
112 refund: RefundContents,
113 secp_ctx: Option<&'a Secp256k1<T>>,
116 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
117 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
118 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
120 /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
121 /// [`Refund::amount_msats`].
123 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
124 ) -> Result<Self, SemanticError> {
125 if amount_msats > MAX_VALUE_MSAT {
126 return Err(SemanticError::InvalidAmount);
129 let metadata = Metadata::Bytes(metadata);
131 refund: RefundContents {
132 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
133 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
134 quantity: None, payer_id, payer_note: None,
141 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
142 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
143 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
144 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
145 /// provided `node_id` is used for the payer id.
147 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
148 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
150 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
151 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
152 pub fn deriving_payer_id<ES: Deref>(
153 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
154 secp_ctx: &'a Secp256k1<T>, amount_msats: u64
155 ) -> Result<Self, SemanticError> where ES::Target: EntropySource {
156 if amount_msats > MAX_VALUE_MSAT {
157 return Err(SemanticError::InvalidAmount);
160 let nonce = Nonce::from_entropy_source(entropy_source);
161 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
162 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
164 refund: RefundContents {
165 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
166 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
167 quantity: None, payer_id: node_id, payer_note: None,
169 secp_ctx: Some(secp_ctx),
173 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
174 /// already passed is valid and can be checked for using [`Refund::is_expired`].
176 /// Successive calls to this method will override the previous setting.
177 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
178 self.refund.absolute_expiry = Some(absolute_expiry);
182 /// Sets the [`Refund::issuer`].
184 /// Successive calls to this method will override the previous setting.
185 pub fn issuer(mut self, issuer: String) -> Self {
186 self.refund.issuer = Some(issuer);
190 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
191 /// by private channels or if [`Refund::payer_id`] is not a public node id.
193 /// Successive calls to this method will add another blinded path. Caller is responsible for not
194 /// adding duplicate paths.
195 pub fn path(mut self, path: BlindedPath) -> Self {
196 self.refund.paths.get_or_insert_with(Vec::new).push(path);
200 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
201 /// called, [`Network::Bitcoin`] is assumed.
203 /// Successive calls to this method will override the previous setting.
204 pub fn chain(mut self, network: Network) -> Self {
205 self.refund.chain = Some(ChainHash::using_genesis_block(network));
209 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
210 /// when the refund pertains to an [`Invoice`] that paid for more than one item from an
211 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
213 /// Successive calls to this method will override the previous setting.
215 /// [`Invoice`]: crate::offers::invoice::Invoice
216 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
217 /// [`Offer`]: crate::offers::offer::Offer
218 pub fn quantity(mut self, quantity: u64) -> Self {
219 self.refund.quantity = Some(quantity);
223 /// Sets the [`Refund::payer_note`].
225 /// Successive calls to this method will override the previous setting.
226 pub fn payer_note(mut self, payer_note: String) -> Self {
227 self.refund.payer_note = Some(payer_note);
231 /// Builds a [`Refund`] after checking for valid semantics.
232 pub fn build(mut self) -> Result<Refund, SemanticError> {
233 if self.refund.chain() == self.refund.implied_chain() {
234 self.refund.chain = None;
237 // Create the metadata for stateless verification of an Invoice.
238 if self.refund.payer.0.has_derivation_material() {
239 let mut metadata = core::mem::take(&mut self.refund.payer.0);
241 if self.refund.paths.is_none() {
242 metadata = metadata.without_keys();
245 let mut tlv_stream = self.refund.as_tlv_stream();
246 tlv_stream.0.metadata = None;
247 if metadata.derives_keys() {
248 tlv_stream.2.payer_id = None;
251 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
252 metadata = derived_metadata;
253 if let Some(keys) = keys {
254 self.refund.payer_id = keys.public_key();
257 self.refund.payer.0 = metadata;
260 let mut bytes = Vec::new();
261 self.refund.write(&mut bytes).unwrap();
263 Ok(Refund { bytes, contents: self.refund })
268 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
269 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
270 self.refund.features = features;
275 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
277 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
278 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
281 /// [`Invoice`]: crate::offers::invoice::Invoice
282 /// [`Offer`]: crate::offers::offer::Offer
283 #[derive(Clone, Debug)]
284 #[cfg_attr(test, derive(PartialEq))]
286 pub(super) bytes: Vec<u8>,
287 pub(super) contents: RefundContents,
290 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
292 /// [`Invoice`]: crate::offers::invoice::Invoice
293 #[derive(Clone, Debug)]
294 #[cfg_attr(test, derive(PartialEq))]
295 pub(super) struct RefundContents {
296 payer: PayerContents,
299 absolute_expiry: Option<Duration>,
300 issuer: Option<String>,
301 paths: Option<Vec<BlindedPath>>,
302 // invoice_request fields
303 chain: Option<ChainHash>,
305 features: InvoiceRequestFeatures,
306 quantity: Option<u64>,
308 payer_note: Option<String>,
312 /// A complete description of the purpose of the refund. Intended to be displayed to the user
313 /// but with the caveat that it has not been verified in any way.
314 pub fn description(&self) -> PrintableString {
315 self.contents.description()
318 /// Duration since the Unix epoch when an invoice should no longer be sent.
320 /// If `None`, the refund does not expire.
321 pub fn absolute_expiry(&self) -> Option<Duration> {
322 self.contents.absolute_expiry
325 /// Whether the refund has expired.
326 #[cfg(feature = "std")]
327 pub fn is_expired(&self) -> bool {
328 self.contents.is_expired()
331 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
332 /// displayed to the user but with the caveat that it has not been verified in any way.
333 pub fn issuer(&self) -> Option<PrintableString> {
334 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
337 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
338 /// privacy by obfuscating its node id.
339 pub fn paths(&self) -> &[BlindedPath] {
340 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
343 /// An unpredictable series of bytes, typically containing information about the derivation of
346 /// [`payer_id`]: Self::payer_id
347 pub fn metadata(&self) -> &[u8] {
348 self.contents.metadata()
351 /// A chain that the refund is valid for.
352 pub fn chain(&self) -> ChainHash {
353 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
356 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
358 /// [`chain`]: Self::chain
359 pub fn amount_msats(&self) -> u64 {
360 self.contents.amount_msats
363 /// Features pertaining to requesting an invoice.
364 pub fn features(&self) -> &InvoiceRequestFeatures {
365 &self.contents.features
368 /// The quantity of an item that refund is for.
369 pub fn quantity(&self) -> Option<u64> {
370 self.contents.quantity
373 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
374 /// transient pubkey.
376 /// [`paths`]: Self::paths
377 pub fn payer_id(&self) -> PublicKey {
378 self.contents.payer_id
381 /// Payer provided note to include in the invoice.
382 pub fn payer_note(&self) -> Option<PrintableString> {
383 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
386 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
387 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
389 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
390 /// time is used for the `created_at` parameter.
392 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
394 /// [`Duration`]: core::time::Duration
395 #[cfg(feature = "std")]
397 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
398 signing_pubkey: PublicKey,
399 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
400 let created_at = std::time::SystemTime::now()
401 .duration_since(std::time::SystemTime::UNIX_EPOCH)
402 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
404 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
407 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
409 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
410 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
411 /// [`std::time::SystemTime`] is not available.
413 /// The caller is expected to remember the preimage of `payment_hash` in order to
414 /// claim a payment for the invoice.
416 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
417 /// offer, which does have a `signing_pubkey`.
419 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
420 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
421 /// a preference. Note, however, that any privacy is lost if a public node id is used for
422 /// `signing_pubkey`.
424 /// Errors if the request contains unknown required features.
426 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
428 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
429 pub fn respond_with_no_std(
430 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
431 signing_pubkey: PublicKey, created_at: Duration
432 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, SemanticError> {
433 if self.features().requires_unknown_bits() {
434 return Err(SemanticError::UnknownRequiredFeatures);
437 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
440 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
441 /// derived signing keys to sign the [`Invoice`].
443 /// See [`Refund::respond_with`] for further details.
445 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
447 /// [`Invoice`]: crate::offers::invoice::Invoice
448 #[cfg(feature = "std")]
449 pub fn respond_using_derived_keys<ES: Deref>(
450 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
451 expanded_key: &ExpandedKey, entropy_source: ES
452 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError>
454 ES::Target: EntropySource,
456 let created_at = std::time::SystemTime::now()
457 .duration_since(std::time::SystemTime::UNIX_EPOCH)
458 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
460 self.respond_using_derived_keys_no_std(
461 payment_paths, payment_hash, created_at, expanded_key, entropy_source
465 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
466 /// derived signing keys to sign the [`Invoice`].
468 /// See [`Refund::respond_with_no_std`] for further details.
470 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
472 /// [`Invoice`]: crate::offers::invoice::Invoice
473 pub fn respond_using_derived_keys_no_std<ES: Deref>(
474 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
475 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
476 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, SemanticError>
478 ES::Target: EntropySource,
480 if self.features().requires_unknown_bits() {
481 return Err(SemanticError::UnknownRequiredFeatures);
484 let nonce = Nonce::from_entropy_source(entropy_source);
485 let keys = signer::derive_keys(nonce, expanded_key);
486 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
490 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
491 self.contents.as_tlv_stream()
495 impl AsRef<[u8]> for Refund {
496 fn as_ref(&self) -> &[u8] {
501 impl RefundContents {
502 pub fn description(&self) -> PrintableString {
503 PrintableString(&self.description)
506 #[cfg(feature = "std")]
507 pub(super) fn is_expired(&self) -> bool {
508 match self.absolute_expiry {
509 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
510 Ok(elapsed) => elapsed > seconds_from_epoch,
517 pub(super) fn metadata(&self) -> &[u8] {
518 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
521 pub(super) fn chain(&self) -> ChainHash {
522 self.chain.unwrap_or_else(|| self.implied_chain())
525 pub fn implied_chain(&self) -> ChainHash {
526 ChainHash::using_genesis_block(Network::Bitcoin)
529 pub(super) fn derives_keys(&self) -> bool {
530 self.payer.0.derives_keys()
533 pub(super) fn payer_id(&self) -> PublicKey {
537 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
538 let payer = PayerTlvStreamRef {
539 metadata: self.payer.0.as_bytes(),
542 let offer = OfferTlvStreamRef {
547 description: Some(&self.description),
549 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
550 paths: self.paths.as_ref(),
551 issuer: self.issuer.as_ref(),
557 if self.features == InvoiceRequestFeatures::empty() { None }
558 else { Some(&self.features) }
561 let invoice_request = InvoiceRequestTlvStreamRef {
562 chain: self.chain.as_ref(),
563 amount: Some(self.amount_msats),
565 quantity: self.quantity,
566 payer_id: Some(&self.payer_id),
567 payer_note: self.payer_note.as_ref(),
570 (payer, offer, invoice_request)
574 impl Writeable for Refund {
575 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
576 WithoutLength(&self.bytes).write(writer)
580 impl Writeable for RefundContents {
581 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
582 self.as_tlv_stream().write(writer)
586 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
588 type RefundTlvStreamRef<'a> = (
589 PayerTlvStreamRef<'a>,
590 OfferTlvStreamRef<'a>,
591 InvoiceRequestTlvStreamRef<'a>,
594 impl SeekReadable for RefundTlvStream {
595 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
596 let payer = SeekReadable::read(r)?;
597 let offer = SeekReadable::read(r)?;
598 let invoice_request = SeekReadable::read(r)?;
600 Ok((payer, offer, invoice_request))
604 impl Bech32Encode for Refund {
605 const BECH32_HRP: &'static str = "lnr";
608 impl FromStr for Refund {
609 type Err = ParseError;
611 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
612 Refund::from_bech32_str(s)
616 impl TryFrom<Vec<u8>> for Refund {
617 type Error = ParseError;
619 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
620 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
621 let ParsedMessage { bytes, tlv_stream } = refund;
622 let contents = RefundContents::try_from(tlv_stream)?;
624 Ok(Refund { bytes, contents })
628 impl TryFrom<RefundTlvStream> for RefundContents {
629 type Error = SemanticError;
631 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
633 PayerTlvStream { metadata: payer_metadata },
635 chains, metadata, currency, amount: offer_amount, description,
636 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
638 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
641 let payer = match payer_metadata {
642 None => return Err(SemanticError::MissingPayerMetadata),
643 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
646 if metadata.is_some() {
647 return Err(SemanticError::UnexpectedMetadata);
650 if chains.is_some() {
651 return Err(SemanticError::UnexpectedChain);
654 if currency.is_some() || offer_amount.is_some() {
655 return Err(SemanticError::UnexpectedAmount);
658 let description = match description {
659 None => return Err(SemanticError::MissingDescription),
660 Some(description) => description,
663 if offer_features.is_some() {
664 return Err(SemanticError::UnexpectedFeatures);
667 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
669 if quantity_max.is_some() {
670 return Err(SemanticError::UnexpectedQuantity);
673 if node_id.is_some() {
674 return Err(SemanticError::UnexpectedSigningPubkey);
677 let amount_msats = match amount {
678 None => return Err(SemanticError::MissingAmount),
679 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
680 return Err(SemanticError::InvalidAmount);
682 Some(amount_msats) => amount_msats,
685 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
687 let payer_id = match payer_id {
688 None => return Err(SemanticError::MissingPayerId),
689 Some(payer_id) => payer_id,
693 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
694 quantity, payer_id, payer_note,
699 impl core::fmt::Display for Refund {
700 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
701 self.fmt_bech32_str(f)
707 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
709 use bitcoin::blockdata::constants::ChainHash;
710 use bitcoin::network::constants::Network;
711 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
712 use core::convert::TryFrom;
713 use core::time::Duration;
714 use crate::blinded_path::{BlindedHop, BlindedPath};
715 use crate::sign::KeyMaterial;
716 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
717 use crate::ln::inbound_payment::ExpandedKey;
718 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
719 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
720 use crate::offers::offer::OfferTlvStreamRef;
721 use crate::offers::parse::{ParseError, SemanticError};
722 use crate::offers::payer::PayerTlvStreamRef;
723 use crate::offers::test_utils::*;
724 use crate::util::ser::{BigSize, Writeable};
725 use crate::util::string::PrintableString;
728 fn to_bytes(&self) -> Vec<u8>;
731 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
732 fn to_bytes(&self) -> Vec<u8> {
733 let mut buffer = Vec::new();
734 self.write(&mut buffer).unwrap();
740 fn builds_refund_with_defaults() {
741 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
744 let mut buffer = Vec::new();
745 refund.write(&mut buffer).unwrap();
747 assert_eq!(refund.bytes, buffer.as_slice());
748 assert_eq!(refund.metadata(), &[1; 32]);
749 assert_eq!(refund.description(), PrintableString("foo"));
750 assert_eq!(refund.absolute_expiry(), None);
751 #[cfg(feature = "std")]
752 assert!(!refund.is_expired());
753 assert_eq!(refund.paths(), &[]);
754 assert_eq!(refund.issuer(), None);
755 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
756 assert_eq!(refund.amount_msats(), 1000);
757 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
758 assert_eq!(refund.payer_id(), payer_pubkey());
759 assert_eq!(refund.payer_note(), None);
762 refund.as_tlv_stream(),
764 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
770 description: Some(&String::from("foo")),
772 absolute_expiry: None,
778 InvoiceRequestTlvStreamRef {
783 payer_id: Some(&payer_pubkey()),
789 if let Err(e) = Refund::try_from(buffer) {
790 panic!("error parsing refund: {:?}", e);
795 fn fails_building_refund_with_invalid_amount() {
796 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
797 Ok(_) => panic!("expected error"),
798 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
803 fn builds_refund_with_metadata_derived() {
804 let desc = "foo".to_string();
805 let node_id = payer_pubkey();
806 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
807 let entropy = FixedEntropy {};
808 let secp_ctx = Secp256k1::new();
810 let refund = RefundBuilder
811 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000)
814 assert_eq!(refund.payer_id(), node_id);
816 // Fails verification with altered fields
818 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
821 .sign(recipient_sign).unwrap();
822 assert!(invoice.verify(&expanded_key, &secp_ctx));
824 let mut tlv_stream = refund.as_tlv_stream();
825 tlv_stream.2.amount = Some(2000);
827 let mut encoded_refund = Vec::new();
828 tlv_stream.write(&mut encoded_refund).unwrap();
830 let invoice = Refund::try_from(encoded_refund).unwrap()
831 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
834 .sign(recipient_sign).unwrap();
835 assert!(!invoice.verify(&expanded_key, &secp_ctx));
837 // Fails verification with altered metadata
838 let mut tlv_stream = refund.as_tlv_stream();
839 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
840 tlv_stream.0.metadata = Some(&metadata);
842 let mut encoded_refund = Vec::new();
843 tlv_stream.write(&mut encoded_refund).unwrap();
845 let invoice = Refund::try_from(encoded_refund).unwrap()
846 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
849 .sign(recipient_sign).unwrap();
850 assert!(!invoice.verify(&expanded_key, &secp_ctx));
854 fn builds_refund_with_derived_payer_id() {
855 let desc = "foo".to_string();
856 let node_id = payer_pubkey();
857 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
858 let entropy = FixedEntropy {};
859 let secp_ctx = Secp256k1::new();
861 let blinded_path = BlindedPath {
862 introduction_node_id: pubkey(40),
863 blinding_point: pubkey(41),
865 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
866 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
870 let refund = RefundBuilder
871 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000)
875 assert_ne!(refund.payer_id(), node_id);
878 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
881 .sign(recipient_sign).unwrap();
882 assert!(invoice.verify(&expanded_key, &secp_ctx));
884 // Fails verification with altered fields
885 let mut tlv_stream = refund.as_tlv_stream();
886 tlv_stream.2.amount = Some(2000);
888 let mut encoded_refund = Vec::new();
889 tlv_stream.write(&mut encoded_refund).unwrap();
891 let invoice = Refund::try_from(encoded_refund).unwrap()
892 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
895 .sign(recipient_sign).unwrap();
896 assert!(!invoice.verify(&expanded_key, &secp_ctx));
898 // Fails verification with altered payer_id
899 let mut tlv_stream = refund.as_tlv_stream();
900 let payer_id = pubkey(1);
901 tlv_stream.2.payer_id = Some(&payer_id);
903 let mut encoded_refund = Vec::new();
904 tlv_stream.write(&mut encoded_refund).unwrap();
906 let invoice = Refund::try_from(encoded_refund).unwrap()
907 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
910 .sign(recipient_sign).unwrap();
911 assert!(!invoice.verify(&expanded_key, &secp_ctx));
915 fn builds_refund_with_absolute_expiry() {
916 let future_expiry = Duration::from_secs(u64::max_value());
917 let past_expiry = Duration::from_secs(0);
919 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
920 .absolute_expiry(future_expiry)
923 let (_, tlv_stream, _) = refund.as_tlv_stream();
924 #[cfg(feature = "std")]
925 assert!(!refund.is_expired());
926 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
927 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
929 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
930 .absolute_expiry(future_expiry)
931 .absolute_expiry(past_expiry)
934 let (_, tlv_stream, _) = refund.as_tlv_stream();
935 #[cfg(feature = "std")]
936 assert!(refund.is_expired());
937 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
938 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
942 fn builds_refund_with_paths() {
945 introduction_node_id: pubkey(40),
946 blinding_point: pubkey(41),
948 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
949 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
953 introduction_node_id: pubkey(40),
954 blinding_point: pubkey(41),
956 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
957 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
962 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
963 .path(paths[0].clone())
964 .path(paths[1].clone())
967 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
968 assert_eq!(refund.paths(), paths.as_slice());
969 assert_eq!(refund.payer_id(), pubkey(42));
970 assert_ne!(pubkey(42), pubkey(44));
971 assert_eq!(offer_tlv_stream.paths, Some(&paths));
972 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
976 fn builds_refund_with_issuer() {
977 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
978 .issuer("bar".into())
981 let (_, tlv_stream, _) = refund.as_tlv_stream();
982 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
983 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
985 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
986 .issuer("bar".into())
987 .issuer("baz".into())
990 let (_, tlv_stream, _) = refund.as_tlv_stream();
991 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
992 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
996 fn builds_refund_with_chain() {
997 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
998 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1000 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1001 .chain(Network::Bitcoin)
1003 let (_, _, tlv_stream) = refund.as_tlv_stream();
1004 assert_eq!(refund.chain(), mainnet);
1005 assert_eq!(tlv_stream.chain, None);
1007 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1008 .chain(Network::Testnet)
1010 let (_, _, tlv_stream) = refund.as_tlv_stream();
1011 assert_eq!(refund.chain(), testnet);
1012 assert_eq!(tlv_stream.chain, Some(&testnet));
1014 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1015 .chain(Network::Regtest)
1016 .chain(Network::Testnet)
1018 let (_, _, tlv_stream) = refund.as_tlv_stream();
1019 assert_eq!(refund.chain(), testnet);
1020 assert_eq!(tlv_stream.chain, Some(&testnet));
1024 fn builds_refund_with_quantity() {
1025 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1028 let (_, _, tlv_stream) = refund.as_tlv_stream();
1029 assert_eq!(refund.quantity(), Some(10));
1030 assert_eq!(tlv_stream.quantity, Some(10));
1032 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1036 let (_, _, tlv_stream) = refund.as_tlv_stream();
1037 assert_eq!(refund.quantity(), Some(1));
1038 assert_eq!(tlv_stream.quantity, Some(1));
1042 fn builds_refund_with_payer_note() {
1043 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1044 .payer_note("bar".into())
1046 let (_, _, tlv_stream) = refund.as_tlv_stream();
1047 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1048 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1050 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1051 .payer_note("bar".into())
1052 .payer_note("baz".into())
1054 let (_, _, tlv_stream) = refund.as_tlv_stream();
1055 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1056 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1060 fn fails_responding_with_unknown_required_features() {
1061 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1062 .features_unchecked(InvoiceRequestFeatures::unknown())
1064 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1066 Ok(_) => panic!("expected error"),
1067 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1072 fn parses_refund_with_metadata() {
1073 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1075 if let Err(e) = refund.to_string().parse::<Refund>() {
1076 panic!("error parsing refund: {:?}", e);
1079 let mut tlv_stream = refund.as_tlv_stream();
1080 tlv_stream.0.metadata = None;
1082 match Refund::try_from(tlv_stream.to_bytes()) {
1083 Ok(_) => panic!("expected error"),
1085 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1091 fn parses_refund_with_description() {
1092 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1094 if let Err(e) = refund.to_string().parse::<Refund>() {
1095 panic!("error parsing refund: {:?}", e);
1098 let mut tlv_stream = refund.as_tlv_stream();
1099 tlv_stream.1.description = None;
1101 match Refund::try_from(tlv_stream.to_bytes()) {
1102 Ok(_) => panic!("expected error"),
1104 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1110 fn parses_refund_with_amount() {
1111 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1113 if let Err(e) = refund.to_string().parse::<Refund>() {
1114 panic!("error parsing refund: {:?}", e);
1117 let mut tlv_stream = refund.as_tlv_stream();
1118 tlv_stream.2.amount = None;
1120 match Refund::try_from(tlv_stream.to_bytes()) {
1121 Ok(_) => panic!("expected error"),
1123 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
1127 let mut tlv_stream = refund.as_tlv_stream();
1128 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1130 match Refund::try_from(tlv_stream.to_bytes()) {
1131 Ok(_) => panic!("expected error"),
1133 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
1139 fn parses_refund_with_payer_id() {
1140 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1142 if let Err(e) = refund.to_string().parse::<Refund>() {
1143 panic!("error parsing refund: {:?}", e);
1146 let mut tlv_stream = refund.as_tlv_stream();
1147 tlv_stream.2.payer_id = None;
1149 match Refund::try_from(tlv_stream.to_bytes()) {
1150 Ok(_) => panic!("expected error"),
1152 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
1158 fn parses_refund_with_optional_fields() {
1159 let past_expiry = Duration::from_secs(0);
1162 introduction_node_id: pubkey(40),
1163 blinding_point: pubkey(41),
1165 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1166 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1170 introduction_node_id: pubkey(40),
1171 blinding_point: pubkey(41),
1173 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1174 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1179 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1180 .absolute_expiry(past_expiry)
1181 .issuer("bar".into())
1182 .path(paths[0].clone())
1183 .path(paths[1].clone())
1184 .chain(Network::Testnet)
1185 .features_unchecked(InvoiceRequestFeatures::unknown())
1187 .payer_note("baz".into())
1190 match refund.to_string().parse::<Refund>() {
1192 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1193 #[cfg(feature = "std")]
1194 assert!(refund.is_expired());
1195 assert_eq!(refund.paths(), &paths[..]);
1196 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1197 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1198 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1199 assert_eq!(refund.quantity(), Some(10));
1200 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1202 Err(e) => panic!("error parsing refund: {:?}", e),
1207 fn fails_parsing_refund_with_unexpected_fields() {
1208 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1210 if let Err(e) = refund.to_string().parse::<Refund>() {
1211 panic!("error parsing refund: {:?}", e);
1214 let metadata = vec![42; 32];
1215 let mut tlv_stream = refund.as_tlv_stream();
1216 tlv_stream.1.metadata = Some(&metadata);
1218 match Refund::try_from(tlv_stream.to_bytes()) {
1219 Ok(_) => panic!("expected error"),
1221 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
1225 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1226 let mut tlv_stream = refund.as_tlv_stream();
1227 tlv_stream.1.chains = Some(&chains);
1229 match Refund::try_from(tlv_stream.to_bytes()) {
1230 Ok(_) => panic!("expected error"),
1232 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
1236 let mut tlv_stream = refund.as_tlv_stream();
1237 tlv_stream.1.currency = Some(&b"USD");
1238 tlv_stream.1.amount = Some(1000);
1240 match Refund::try_from(tlv_stream.to_bytes()) {
1241 Ok(_) => panic!("expected error"),
1243 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
1247 let features = OfferFeatures::unknown();
1248 let mut tlv_stream = refund.as_tlv_stream();
1249 tlv_stream.1.features = Some(&features);
1251 match Refund::try_from(tlv_stream.to_bytes()) {
1252 Ok(_) => panic!("expected error"),
1254 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
1258 let mut tlv_stream = refund.as_tlv_stream();
1259 tlv_stream.1.quantity_max = Some(10);
1261 match Refund::try_from(tlv_stream.to_bytes()) {
1262 Ok(_) => panic!("expected error"),
1264 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1268 let node_id = payer_pubkey();
1269 let mut tlv_stream = refund.as_tlv_stream();
1270 tlv_stream.1.node_id = Some(&node_id);
1272 match Refund::try_from(tlv_stream.to_bytes()) {
1273 Ok(_) => panic!("expected error"),
1275 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1281 fn fails_parsing_refund_with_extra_tlv_records() {
1282 let secp_ctx = Secp256k1::new();
1283 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1284 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1287 let mut encoded_refund = Vec::new();
1288 refund.write(&mut encoded_refund).unwrap();
1289 BigSize(1002).write(&mut encoded_refund).unwrap();
1290 BigSize(32).write(&mut encoded_refund).unwrap();
1291 [42u8; 32].write(&mut encoded_refund).unwrap();
1293 match Refund::try_from(encoded_refund) {
1294 Ok(_) => panic!("expected error"),
1295 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),