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::{INVOICE_REQUEST_PAYER_ID_TYPE, INVOICE_REQUEST_TYPES, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
89 use crate::offers::merkle::TlvStream;
90 use crate::offers::offer::{OFFER_TYPES, OfferTlvStream, OfferTlvStreamRef};
91 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
92 use crate::offers::payer::{PAYER_METADATA_TYPE, PayerContents, PayerTlvStream, PayerTlvStreamRef};
93 use crate::offers::signer::{Metadata, MetadataMaterial, self};
94 use crate::onion_message::BlindedPath;
95 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
96 use crate::util::string::PrintableString;
98 use crate::prelude::*;
100 #[cfg(feature = "std")]
101 use std::time::SystemTime;
103 const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
105 /// Builds a [`Refund`] for the "offer for money" flow.
107 /// See [module-level documentation] for usage.
109 /// [module-level documentation]: self
110 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
111 refund: RefundContents,
112 secp_ctx: Option<&'a Secp256k1<T>>,
115 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
116 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
117 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
119 /// Additionally, sets the required [`Refund::description`], [`Refund::metadata`], and
120 /// [`Refund::amount_msats`].
122 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
123 ) -> Result<Self, SemanticError> {
124 if amount_msats > MAX_VALUE_MSAT {
125 return Err(SemanticError::InvalidAmount);
128 let metadata = Metadata::Bytes(metadata);
130 refund: RefundContents {
131 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
132 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
133 quantity: None, payer_id, payer_note: None,
140 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
141 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
142 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
143 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
144 /// provided `node_id` is used for the payer id.
146 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
147 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
149 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
150 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
151 pub fn deriving_payer_id<ES: Deref>(
152 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
153 secp_ctx: &'a Secp256k1<T>, amount_msats: u64
154 ) -> Result<Self, SemanticError> where ES::Target: EntropySource {
155 if amount_msats > MAX_VALUE_MSAT {
156 return Err(SemanticError::InvalidAmount);
159 let nonce = Nonce::from_entropy_source(entropy_source);
160 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
161 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
163 refund: RefundContents {
164 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
165 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
166 quantity: None, payer_id: node_id, payer_note: None,
168 secp_ctx: Some(secp_ctx),
172 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
173 /// already passed is valid and can be checked for using [`Refund::is_expired`].
175 /// Successive calls to this method will override the previous setting.
176 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
177 self.refund.absolute_expiry = Some(absolute_expiry);
181 /// Sets the [`Refund::issuer`].
183 /// Successive calls to this method will override the previous setting.
184 pub fn issuer(mut self, issuer: String) -> Self {
185 self.refund.issuer = Some(issuer);
189 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
190 /// by private channels or if [`Refund::payer_id`] is not a public node id.
192 /// Successive calls to this method will add another blinded path. Caller is responsible for not
193 /// adding duplicate paths.
194 pub fn path(mut self, path: BlindedPath) -> Self {
195 self.refund.paths.get_or_insert_with(Vec::new).push(path);
199 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
200 /// called, [`Network::Bitcoin`] is assumed.
202 /// Successive calls to this method will override the previous setting.
203 pub fn chain(mut self, network: Network) -> Self {
204 self.refund.chain = Some(ChainHash::using_genesis_block(network));
208 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
209 /// when the refund pertains to an [`Invoice`] that paid for more than one item from an
210 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
212 /// Successive calls to this method will override the previous setting.
214 /// [`Invoice`]: crate::offers::invoice::Invoice
215 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
216 /// [`Offer`]: crate::offers::offer::Offer
217 pub fn quantity(mut self, quantity: u64) -> Self {
218 self.refund.quantity = Some(quantity);
222 /// Sets the [`Refund::payer_note`].
224 /// Successive calls to this method will override the previous setting.
225 pub fn payer_note(mut self, payer_note: String) -> Self {
226 self.refund.payer_note = Some(payer_note);
230 /// Builds a [`Refund`] after checking for valid semantics.
231 pub fn build(mut self) -> Result<Refund, SemanticError> {
232 if self.refund.chain() == self.refund.implied_chain() {
233 self.refund.chain = None;
236 // Create the metadata for stateless verification of an Invoice.
237 if self.refund.payer.0.has_derivation_material() {
238 let mut metadata = core::mem::take(&mut self.refund.payer.0);
240 if self.refund.paths.is_none() {
241 metadata = metadata.without_keys();
244 let mut tlv_stream = self.refund.as_tlv_stream();
245 tlv_stream.0.metadata = None;
246 if metadata.derives_keys() {
247 tlv_stream.2.payer_id = None;
250 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
251 metadata = derived_metadata;
252 if let Some(keys) = keys {
253 self.refund.payer_id = keys.public_key();
256 self.refund.payer.0 = metadata;
259 let mut bytes = Vec::new();
260 self.refund.write(&mut bytes).unwrap();
262 Ok(Refund { bytes, contents: self.refund })
267 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
268 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
269 self.refund.features = features;
274 /// A `Refund` is a request to send an [`Invoice`] without a preceding [`Offer`].
276 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
277 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
280 /// [`Invoice`]: crate::offers::invoice::Invoice
281 /// [`Offer`]: crate::offers::offer::Offer
282 #[derive(Clone, Debug)]
283 #[cfg_attr(test, derive(PartialEq))]
285 pub(super) bytes: Vec<u8>,
286 pub(super) contents: RefundContents,
289 /// The contents of a [`Refund`], which may be shared with an [`Invoice`].
291 /// [`Invoice`]: crate::offers::invoice::Invoice
292 #[derive(Clone, Debug)]
293 #[cfg_attr(test, derive(PartialEq))]
294 pub(super) struct RefundContents {
295 payer: PayerContents,
298 absolute_expiry: Option<Duration>,
299 issuer: Option<String>,
300 paths: Option<Vec<BlindedPath>>,
301 // invoice_request fields
302 chain: Option<ChainHash>,
304 features: InvoiceRequestFeatures,
305 quantity: Option<u64>,
307 payer_note: Option<String>,
311 /// A complete description of the purpose of the refund. Intended to be displayed to the user
312 /// but with the caveat that it has not been verified in any way.
313 pub fn description(&self) -> PrintableString {
314 PrintableString(&self.contents.description)
317 /// Duration since the Unix epoch when an invoice should no longer be sent.
319 /// If `None`, the refund does not expire.
320 pub fn absolute_expiry(&self) -> Option<Duration> {
321 self.contents.absolute_expiry
324 /// Whether the refund has expired.
325 #[cfg(feature = "std")]
326 pub fn is_expired(&self) -> bool {
327 self.contents.is_expired()
330 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
331 /// displayed to the user but with the caveat that it has not been verified in any way.
332 pub fn issuer(&self) -> Option<PrintableString> {
333 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
336 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
337 /// privacy by obfuscating its node id.
338 pub fn paths(&self) -> &[BlindedPath] {
339 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
342 /// An unpredictable series of bytes, typically containing information about the derivation of
345 /// [`payer_id`]: Self::payer_id
346 pub fn metadata(&self) -> &[u8] {
347 self.contents.metadata()
350 /// A chain that the refund is valid for.
351 pub fn chain(&self) -> ChainHash {
352 self.contents.chain.unwrap_or_else(|| self.contents.implied_chain())
355 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
357 /// [`chain`]: Self::chain
358 pub fn amount_msats(&self) -> u64 {
359 self.contents.amount_msats
362 /// Features pertaining to requesting an invoice.
363 pub fn features(&self) -> &InvoiceRequestFeatures {
364 &self.contents.features
367 /// The quantity of an item that refund is for.
368 pub fn quantity(&self) -> Option<u64> {
369 self.contents.quantity
372 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
373 /// transient pubkey.
375 /// [`paths`]: Self::paths
376 pub fn payer_id(&self) -> PublicKey {
377 self.contents.payer_id
380 /// Payer provided note to include in the invoice.
381 pub fn payer_note(&self) -> Option<PrintableString> {
382 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
385 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
386 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
388 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
389 /// time is used for the `created_at` parameter.
391 /// [`Duration`]: core::time::Duration
392 #[cfg(feature = "std")]
394 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
395 signing_pubkey: PublicKey,
396 ) -> Result<InvoiceBuilder, SemanticError> {
397 let created_at = std::time::SystemTime::now()
398 .duration_since(std::time::SystemTime::UNIX_EPOCH)
399 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
401 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
404 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
406 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
407 /// `created_at`, which is used to set [`Invoice::created_at`]. Useful for `no-std` builds where
408 /// [`std::time::SystemTime`] is not available.
410 /// The caller is expected to remember the preimage of `payment_hash` in order to
411 /// claim a payment for the invoice.
413 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
414 /// offer, which does have a `signing_pubkey`.
416 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
417 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
418 /// a preference. Note, however, that any privacy is lost if a public node id is used for
419 /// `signing_pubkey`.
421 /// Errors if the request contains unknown required features.
423 /// [`Invoice::created_at`]: crate::offers::invoice::Invoice::created_at
424 pub fn respond_with_no_std(
425 &self, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, payment_hash: PaymentHash,
426 signing_pubkey: PublicKey, created_at: Duration
427 ) -> Result<InvoiceBuilder, SemanticError> {
428 if self.features().requires_unknown_bits() {
429 return Err(SemanticError::UnknownRequiredFeatures);
432 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
436 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
437 self.contents.as_tlv_stream()
441 impl AsRef<[u8]> for Refund {
442 fn as_ref(&self) -> &[u8] {
447 impl RefundContents {
448 #[cfg(feature = "std")]
449 pub(super) fn is_expired(&self) -> bool {
450 match self.absolute_expiry {
451 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
452 Ok(elapsed) => elapsed > seconds_from_epoch,
459 fn metadata(&self) -> &[u8] {
460 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
463 pub(super) fn chain(&self) -> ChainHash {
464 self.chain.unwrap_or_else(|| self.implied_chain())
467 pub fn implied_chain(&self) -> ChainHash {
468 ChainHash::using_genesis_block(Network::Bitcoin)
471 /// Verifies that the payer metadata was produced from the refund in the TLV stream.
472 pub(super) fn verify<T: secp256k1::Signing>(
473 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
475 let offer_records = tlv_stream.clone().range(OFFER_TYPES);
476 let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
477 match record.r#type {
478 PAYER_METADATA_TYPE => false, // Should be outside range
479 INVOICE_REQUEST_PAYER_ID_TYPE => !self.payer.0.derives_keys(),
483 let tlv_stream = offer_records.chain(invreq_records);
484 signer::verify_metadata(self.metadata(), key, IV_BYTES, self.payer_id, tlv_stream, secp_ctx)
487 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
488 let payer = PayerTlvStreamRef {
489 metadata: self.payer.0.as_bytes(),
492 let offer = OfferTlvStreamRef {
497 description: Some(&self.description),
499 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
500 paths: self.paths.as_ref(),
501 issuer: self.issuer.as_ref(),
507 if self.features == InvoiceRequestFeatures::empty() { None }
508 else { Some(&self.features) }
511 let invoice_request = InvoiceRequestTlvStreamRef {
512 chain: self.chain.as_ref(),
513 amount: Some(self.amount_msats),
515 quantity: self.quantity,
516 payer_id: Some(&self.payer_id),
517 payer_note: self.payer_note.as_ref(),
520 (payer, offer, invoice_request)
524 impl Writeable for Refund {
525 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
526 WithoutLength(&self.bytes).write(writer)
530 impl Writeable for RefundContents {
531 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
532 self.as_tlv_stream().write(writer)
536 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
538 type RefundTlvStreamRef<'a> = (
539 PayerTlvStreamRef<'a>,
540 OfferTlvStreamRef<'a>,
541 InvoiceRequestTlvStreamRef<'a>,
544 impl SeekReadable for RefundTlvStream {
545 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
546 let payer = SeekReadable::read(r)?;
547 let offer = SeekReadable::read(r)?;
548 let invoice_request = SeekReadable::read(r)?;
550 Ok((payer, offer, invoice_request))
554 impl Bech32Encode for Refund {
555 const BECH32_HRP: &'static str = "lnr";
558 impl FromStr for Refund {
559 type Err = ParseError;
561 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
562 Refund::from_bech32_str(s)
566 impl TryFrom<Vec<u8>> for Refund {
567 type Error = ParseError;
569 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
570 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
571 let ParsedMessage { bytes, tlv_stream } = refund;
572 let contents = RefundContents::try_from(tlv_stream)?;
574 Ok(Refund { bytes, contents })
578 impl TryFrom<RefundTlvStream> for RefundContents {
579 type Error = SemanticError;
581 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
583 PayerTlvStream { metadata: payer_metadata },
585 chains, metadata, currency, amount: offer_amount, description,
586 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
588 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
591 let payer = match payer_metadata {
592 None => return Err(SemanticError::MissingPayerMetadata),
593 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
596 if metadata.is_some() {
597 return Err(SemanticError::UnexpectedMetadata);
600 if chains.is_some() {
601 return Err(SemanticError::UnexpectedChain);
604 if currency.is_some() || offer_amount.is_some() {
605 return Err(SemanticError::UnexpectedAmount);
608 let description = match description {
609 None => return Err(SemanticError::MissingDescription),
610 Some(description) => description,
613 if offer_features.is_some() {
614 return Err(SemanticError::UnexpectedFeatures);
617 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
619 if quantity_max.is_some() {
620 return Err(SemanticError::UnexpectedQuantity);
623 if node_id.is_some() {
624 return Err(SemanticError::UnexpectedSigningPubkey);
627 let amount_msats = match amount {
628 None => return Err(SemanticError::MissingAmount),
629 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
630 return Err(SemanticError::InvalidAmount);
632 Some(amount_msats) => amount_msats,
635 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
637 let payer_id = match payer_id {
638 None => return Err(SemanticError::MissingPayerId),
639 Some(payer_id) => payer_id,
643 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
644 quantity, payer_id, payer_note,
649 impl core::fmt::Display for Refund {
650 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
651 self.fmt_bech32_str(f)
657 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
659 use bitcoin::blockdata::constants::ChainHash;
660 use bitcoin::network::constants::Network;
661 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
662 use core::convert::TryFrom;
663 use core::time::Duration;
664 use crate::chain::keysinterface::KeyMaterial;
665 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
666 use crate::ln::inbound_payment::ExpandedKey;
667 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
668 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
669 use crate::offers::offer::OfferTlvStreamRef;
670 use crate::offers::parse::{ParseError, SemanticError};
671 use crate::offers::payer::PayerTlvStreamRef;
672 use crate::offers::test_utils::*;
673 use crate::onion_message::{BlindedHop, BlindedPath};
674 use crate::util::ser::{BigSize, Writeable};
675 use crate::util::string::PrintableString;
678 fn to_bytes(&self) -> Vec<u8>;
681 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
682 fn to_bytes(&self) -> Vec<u8> {
683 let mut buffer = Vec::new();
684 self.write(&mut buffer).unwrap();
690 fn builds_refund_with_defaults() {
691 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
694 let mut buffer = Vec::new();
695 refund.write(&mut buffer).unwrap();
697 assert_eq!(refund.bytes, buffer.as_slice());
698 assert_eq!(refund.metadata(), &[1; 32]);
699 assert_eq!(refund.description(), PrintableString("foo"));
700 assert_eq!(refund.absolute_expiry(), None);
701 #[cfg(feature = "std")]
702 assert!(!refund.is_expired());
703 assert_eq!(refund.paths(), &[]);
704 assert_eq!(refund.issuer(), None);
705 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
706 assert_eq!(refund.amount_msats(), 1000);
707 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
708 assert_eq!(refund.payer_id(), payer_pubkey());
709 assert_eq!(refund.payer_note(), None);
712 refund.as_tlv_stream(),
714 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
720 description: Some(&String::from("foo")),
722 absolute_expiry: None,
728 InvoiceRequestTlvStreamRef {
733 payer_id: Some(&payer_pubkey()),
739 if let Err(e) = Refund::try_from(buffer) {
740 panic!("error parsing refund: {:?}", e);
745 fn fails_building_refund_with_invalid_amount() {
746 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
747 Ok(_) => panic!("expected error"),
748 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
753 fn builds_refund_with_metadata_derived() {
754 let desc = "foo".to_string();
755 let node_id = payer_pubkey();
756 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
757 let entropy = FixedEntropy {};
758 let secp_ctx = Secp256k1::new();
760 let refund = RefundBuilder
761 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000)
764 assert_eq!(refund.payer_id(), node_id);
766 // Fails verification with altered fields
768 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
771 .sign(recipient_sign).unwrap();
772 assert!(invoice.verify(&expanded_key, &secp_ctx));
774 let mut tlv_stream = refund.as_tlv_stream();
775 tlv_stream.2.amount = Some(2000);
777 let mut encoded_refund = Vec::new();
778 tlv_stream.write(&mut encoded_refund).unwrap();
780 let invoice = Refund::try_from(encoded_refund).unwrap()
781 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
784 .sign(recipient_sign).unwrap();
785 assert!(!invoice.verify(&expanded_key, &secp_ctx));
787 // Fails verification with altered metadata
788 let mut tlv_stream = refund.as_tlv_stream();
789 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
790 tlv_stream.0.metadata = Some(&metadata);
792 let mut encoded_refund = Vec::new();
793 tlv_stream.write(&mut encoded_refund).unwrap();
795 let invoice = Refund::try_from(encoded_refund).unwrap()
796 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
799 .sign(recipient_sign).unwrap();
800 assert!(!invoice.verify(&expanded_key, &secp_ctx));
804 fn builds_refund_with_derived_payer_id() {
805 let desc = "foo".to_string();
806 let node_id = payer_pubkey();
807 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
808 let entropy = FixedEntropy {};
809 let secp_ctx = Secp256k1::new();
811 let blinded_path = BlindedPath {
812 introduction_node_id: pubkey(40),
813 blinding_point: pubkey(41),
815 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
816 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
820 let refund = RefundBuilder
821 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000)
825 assert_ne!(refund.payer_id(), node_id);
828 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
831 .sign(recipient_sign).unwrap();
832 assert!(invoice.verify(&expanded_key, &secp_ctx));
834 // Fails verification with altered fields
835 let mut tlv_stream = refund.as_tlv_stream();
836 tlv_stream.2.amount = Some(2000);
838 let mut encoded_refund = Vec::new();
839 tlv_stream.write(&mut encoded_refund).unwrap();
841 let invoice = Refund::try_from(encoded_refund).unwrap()
842 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
845 .sign(recipient_sign).unwrap();
846 assert!(!invoice.verify(&expanded_key, &secp_ctx));
848 // Fails verification with altered payer_id
849 let mut tlv_stream = refund.as_tlv_stream();
850 let payer_id = pubkey(1);
851 tlv_stream.2.payer_id = Some(&payer_id);
853 let mut encoded_refund = Vec::new();
854 tlv_stream.write(&mut encoded_refund).unwrap();
856 let invoice = Refund::try_from(encoded_refund).unwrap()
857 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
860 .sign(recipient_sign).unwrap();
861 assert!(!invoice.verify(&expanded_key, &secp_ctx));
865 fn builds_refund_with_absolute_expiry() {
866 let future_expiry = Duration::from_secs(u64::max_value());
867 let past_expiry = Duration::from_secs(0);
869 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
870 .absolute_expiry(future_expiry)
873 let (_, tlv_stream, _) = refund.as_tlv_stream();
874 #[cfg(feature = "std")]
875 assert!(!refund.is_expired());
876 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
877 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
879 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
880 .absolute_expiry(future_expiry)
881 .absolute_expiry(past_expiry)
884 let (_, tlv_stream, _) = refund.as_tlv_stream();
885 #[cfg(feature = "std")]
886 assert!(refund.is_expired());
887 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
888 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
892 fn builds_refund_with_paths() {
895 introduction_node_id: pubkey(40),
896 blinding_point: pubkey(41),
898 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
899 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
903 introduction_node_id: pubkey(40),
904 blinding_point: pubkey(41),
906 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
907 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
912 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
913 .path(paths[0].clone())
914 .path(paths[1].clone())
917 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
918 assert_eq!(refund.paths(), paths.as_slice());
919 assert_eq!(refund.payer_id(), pubkey(42));
920 assert_ne!(pubkey(42), pubkey(44));
921 assert_eq!(offer_tlv_stream.paths, Some(&paths));
922 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
926 fn builds_refund_with_issuer() {
927 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
928 .issuer("bar".into())
931 let (_, tlv_stream, _) = refund.as_tlv_stream();
932 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
933 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
935 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
936 .issuer("bar".into())
937 .issuer("baz".into())
940 let (_, tlv_stream, _) = refund.as_tlv_stream();
941 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
942 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
946 fn builds_refund_with_chain() {
947 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
948 let testnet = ChainHash::using_genesis_block(Network::Testnet);
950 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
951 .chain(Network::Bitcoin)
953 let (_, _, tlv_stream) = refund.as_tlv_stream();
954 assert_eq!(refund.chain(), mainnet);
955 assert_eq!(tlv_stream.chain, None);
957 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
958 .chain(Network::Testnet)
960 let (_, _, tlv_stream) = refund.as_tlv_stream();
961 assert_eq!(refund.chain(), testnet);
962 assert_eq!(tlv_stream.chain, Some(&testnet));
964 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
965 .chain(Network::Regtest)
966 .chain(Network::Testnet)
968 let (_, _, tlv_stream) = refund.as_tlv_stream();
969 assert_eq!(refund.chain(), testnet);
970 assert_eq!(tlv_stream.chain, Some(&testnet));
974 fn builds_refund_with_quantity() {
975 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
978 let (_, _, tlv_stream) = refund.as_tlv_stream();
979 assert_eq!(refund.quantity(), Some(10));
980 assert_eq!(tlv_stream.quantity, Some(10));
982 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
986 let (_, _, tlv_stream) = refund.as_tlv_stream();
987 assert_eq!(refund.quantity(), Some(1));
988 assert_eq!(tlv_stream.quantity, Some(1));
992 fn builds_refund_with_payer_note() {
993 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
994 .payer_note("bar".into())
996 let (_, _, tlv_stream) = refund.as_tlv_stream();
997 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
998 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1000 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1001 .payer_note("bar".into())
1002 .payer_note("baz".into())
1004 let (_, _, tlv_stream) = refund.as_tlv_stream();
1005 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1006 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1010 fn fails_responding_with_unknown_required_features() {
1011 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1012 .features_unchecked(InvoiceRequestFeatures::unknown())
1014 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1016 Ok(_) => panic!("expected error"),
1017 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1022 fn parses_refund_with_metadata() {
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 mut tlv_stream = refund.as_tlv_stream();
1030 tlv_stream.0.metadata = None;
1032 match Refund::try_from(tlv_stream.to_bytes()) {
1033 Ok(_) => panic!("expected error"),
1035 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerMetadata));
1041 fn parses_refund_with_description() {
1042 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1044 if let Err(e) = refund.to_string().parse::<Refund>() {
1045 panic!("error parsing refund: {:?}", e);
1048 let mut tlv_stream = refund.as_tlv_stream();
1049 tlv_stream.1.description = None;
1051 match Refund::try_from(tlv_stream.to_bytes()) {
1052 Ok(_) => panic!("expected error"),
1054 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1060 fn parses_refund_with_amount() {
1061 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1063 if let Err(e) = refund.to_string().parse::<Refund>() {
1064 panic!("error parsing refund: {:?}", e);
1067 let mut tlv_stream = refund.as_tlv_stream();
1068 tlv_stream.2.amount = None;
1070 match Refund::try_from(tlv_stream.to_bytes()) {
1071 Ok(_) => panic!("expected error"),
1073 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount));
1077 let mut tlv_stream = refund.as_tlv_stream();
1078 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1080 match Refund::try_from(tlv_stream.to_bytes()) {
1081 Ok(_) => panic!("expected error"),
1083 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount));
1089 fn parses_refund_with_payer_id() {
1090 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1092 if let Err(e) = refund.to_string().parse::<Refund>() {
1093 panic!("error parsing refund: {:?}", e);
1096 let mut tlv_stream = refund.as_tlv_stream();
1097 tlv_stream.2.payer_id = None;
1099 match Refund::try_from(tlv_stream.to_bytes()) {
1100 Ok(_) => panic!("expected error"),
1102 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPayerId));
1108 fn parses_refund_with_optional_fields() {
1109 let past_expiry = Duration::from_secs(0);
1112 introduction_node_id: pubkey(40),
1113 blinding_point: pubkey(41),
1115 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1116 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1120 introduction_node_id: pubkey(40),
1121 blinding_point: pubkey(41),
1123 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1124 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1129 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1130 .absolute_expiry(past_expiry)
1131 .issuer("bar".into())
1132 .path(paths[0].clone())
1133 .path(paths[1].clone())
1134 .chain(Network::Testnet)
1135 .features_unchecked(InvoiceRequestFeatures::unknown())
1137 .payer_note("baz".into())
1140 match refund.to_string().parse::<Refund>() {
1142 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1143 #[cfg(feature = "std")]
1144 assert!(refund.is_expired());
1145 assert_eq!(refund.paths(), &paths[..]);
1146 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1147 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1148 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1149 assert_eq!(refund.quantity(), Some(10));
1150 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1152 Err(e) => panic!("error parsing refund: {:?}", e),
1157 fn fails_parsing_refund_with_unexpected_fields() {
1158 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1160 if let Err(e) = refund.to_string().parse::<Refund>() {
1161 panic!("error parsing refund: {:?}", e);
1164 let metadata = vec![42; 32];
1165 let mut tlv_stream = refund.as_tlv_stream();
1166 tlv_stream.1.metadata = Some(&metadata);
1168 match Refund::try_from(tlv_stream.to_bytes()) {
1169 Ok(_) => panic!("expected error"),
1171 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedMetadata));
1175 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1176 let mut tlv_stream = refund.as_tlv_stream();
1177 tlv_stream.1.chains = Some(&chains);
1179 match Refund::try_from(tlv_stream.to_bytes()) {
1180 Ok(_) => panic!("expected error"),
1182 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedChain));
1186 let mut tlv_stream = refund.as_tlv_stream();
1187 tlv_stream.1.currency = Some(&b"USD");
1188 tlv_stream.1.amount = Some(1000);
1190 match Refund::try_from(tlv_stream.to_bytes()) {
1191 Ok(_) => panic!("expected error"),
1193 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedAmount));
1197 let features = OfferFeatures::unknown();
1198 let mut tlv_stream = refund.as_tlv_stream();
1199 tlv_stream.1.features = Some(&features);
1201 match Refund::try_from(tlv_stream.to_bytes()) {
1202 Ok(_) => panic!("expected error"),
1204 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedFeatures));
1208 let mut tlv_stream = refund.as_tlv_stream();
1209 tlv_stream.1.quantity_max = Some(10);
1211 match Refund::try_from(tlv_stream.to_bytes()) {
1212 Ok(_) => panic!("expected error"),
1214 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedQuantity));
1218 let node_id = payer_pubkey();
1219 let mut tlv_stream = refund.as_tlv_stream();
1220 tlv_stream.1.node_id = Some(&node_id);
1222 match Refund::try_from(tlv_stream.to_bytes()) {
1223 Ok(_) => panic!("expected error"),
1225 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::UnexpectedSigningPubkey));
1231 fn fails_parsing_refund_with_extra_tlv_records() {
1232 let secp_ctx = Secp256k1::new();
1233 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1234 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1237 let mut encoded_refund = Vec::new();
1238 refund.write(&mut encoded_refund).unwrap();
1239 BigSize(1002).write(&mut encoded_refund).unwrap();
1240 BigSize(32).write(&mut encoded_refund).unwrap();
1241 [42u8; 32].write(&mut encoded_refund).unwrap();
1243 match Refund::try_from(encoded_refund) {
1244 Ok(_) => panic!("expected error"),
1245 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),