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 a [`Bolt12Invoice`] to be paid.
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
17 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
18 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19 //! [`Offer`]: crate::offers::offer::Offer
24 //! extern crate bitcoin;
25 //! extern crate core;
26 //! extern crate lightning;
28 //! use core::convert::TryFrom;
29 //! use core::time::Duration;
31 //! use bitcoin::network::constants::Network;
32 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
33 //! use lightning::offers::parse::Bolt12ParseError;
34 //! use lightning::offers::refund::{Refund, RefundBuilder};
35 //! use lightning::util::ser::{Readable, Writeable};
37 //! # use lightning::blinded_path::BlindedPath;
38 //! # #[cfg(feature = "std")]
39 //! # use std::time::SystemTime;
41 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
42 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
44 //! # #[cfg(feature = "std")]
45 //! # fn build() -> Result<(), Bolt12ParseError> {
46 //! let secp_ctx = Secp256k1::new();
47 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
48 //! let pubkey = PublicKey::from(keys);
50 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
51 //! let refund = RefundBuilder::new("coffee, large".to_string(), vec![1; 32], pubkey, 20_000)?
52 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
53 //! .issuer("Foo Bar".to_string())
54 //! .path(create_blinded_path())
55 //! .path(create_another_blinded_path())
56 //! .chain(Network::Bitcoin)
57 //! .payer_note("refund for order #12345".to_string())
60 //! // Encode as a bech32 string for use in a QR code.
61 //! let encoded_refund = refund.to_string();
63 //! // Parse from a bech32 string after scanning from a QR code.
64 //! let refund = encoded_refund.parse::<Refund>()?;
66 //! // Encode refund as raw bytes.
67 //! let mut bytes = Vec::new();
68 //! refund.write(&mut bytes).unwrap();
70 //! // Decode raw bytes into an refund.
71 //! let refund = Refund::try_from(bytes)?;
78 //! If constructing a [`Refund`] for use with a [`ChannelManager`], use
79 //! [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
81 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
82 //! [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
84 use bitcoin::blockdata::constants::ChainHash;
85 use bitcoin::network::constants::Network;
86 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
87 use core::hash::{Hash, Hasher};
89 use core::str::FromStr;
90 use core::time::Duration;
91 use crate::sign::EntropySource;
93 use crate::blinded_path::BlindedPath;
94 use crate::ln::types::PaymentHash;
95 use crate::ln::channelmanager::PaymentId;
96 use crate::ln::features::InvoiceRequestFeatures;
97 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
98 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
99 use crate::offers::invoice::BlindedPayInfo;
100 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
101 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
102 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
103 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
104 use crate::offers::signer::{Metadata, MetadataMaterial, self};
105 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
106 use crate::util::string::PrintableString;
108 #[cfg(not(c_bindings))]
110 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
114 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
117 #[allow(unused_imports)]
118 use crate::prelude::*;
120 #[cfg(feature = "std")]
121 use std::time::SystemTime;
123 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
125 /// Builds a [`Refund`] for the "offer for money" flow.
127 /// See [module-level documentation] for usage.
129 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
131 /// [module-level documentation]: self
132 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
133 refund: RefundContents,
134 secp_ctx: Option<&'a Secp256k1<T>>,
137 /// Builds a [`Refund`] for the "offer for money" flow.
139 /// See [module-level documentation] for usage.
141 /// [module-level documentation]: self
143 pub struct RefundMaybeWithDerivedMetadataBuilder<'a> {
144 refund: RefundContents,
145 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
148 macro_rules! refund_explicit_metadata_builder_methods { () => {
149 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
150 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
152 /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
153 /// [`Refund::amount_msats`].
157 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
158 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
160 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
161 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
163 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
164 ) -> Result<Self, Bolt12SemanticError> {
165 if amount_msats > MAX_VALUE_MSAT {
166 return Err(Bolt12SemanticError::InvalidAmount);
169 let metadata = Metadata::Bytes(metadata);
171 refund: RefundContents {
172 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
173 chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
174 quantity: None, payer_id, payer_note: None, paths: None,
181 macro_rules! refund_builder_methods { (
182 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
184 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
185 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
186 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
187 /// provided `node_id` is used for the payer id.
189 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
190 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
192 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
193 /// one invoice will be paid for the refund and that payments can be uniquely identified.
195 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
196 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
197 pub fn deriving_payer_id<ES: Deref>(
198 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
199 secp_ctx: &'a Secp256k1<$secp_context>, amount_msats: u64, payment_id: PaymentId
200 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
201 if amount_msats > MAX_VALUE_MSAT {
202 return Err(Bolt12SemanticError::InvalidAmount);
205 let nonce = Nonce::from_entropy_source(entropy_source);
206 let payment_id = Some(payment_id);
207 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
208 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
210 refund: RefundContents {
211 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
212 chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
213 quantity: None, payer_id: node_id, payer_note: None, paths: None,
215 secp_ctx: Some(secp_ctx),
219 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
220 /// already passed is valid and can be checked for using [`Refund::is_expired`].
222 /// Successive calls to this method will override the previous setting.
223 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
224 $self.refund.absolute_expiry = Some(absolute_expiry);
228 /// Sets the [`Refund::issuer`].
230 /// Successive calls to this method will override the previous setting.
231 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
232 $self.refund.issuer = Some(issuer);
236 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
237 /// by private channels or if [`Refund::payer_id`] is not a public node id.
239 /// Successive calls to this method will add another blinded path. Caller is responsible for not
240 /// adding duplicate paths.
241 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
242 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
246 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
247 /// called, [`Network::Bitcoin`] is assumed.
249 /// Successive calls to this method will override the previous setting.
250 pub fn chain($self: $self_type, network: Network) -> $return_type {
251 $self.chain_hash(ChainHash::using_genesis_block(network))
254 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
255 /// [`Network::Bitcoin`] is assumed.
257 /// Successive calls to this method will override the previous setting.
258 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
259 $self.refund.chain = Some(chain);
263 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
264 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
265 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
267 /// Successive calls to this method will override the previous setting.
269 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
270 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
271 /// [`Offer`]: crate::offers::offer::Offer
272 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
273 $self.refund.quantity = Some(quantity);
277 /// Sets the [`Refund::payer_note`].
279 /// Successive calls to this method will override the previous setting.
280 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
281 $self.refund.payer_note = Some(payer_note);
285 /// Builds a [`Refund`] after checking for valid semantics.
286 pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
287 if $self.refund.chain() == $self.refund.implied_chain() {
288 $self.refund.chain = None;
291 // Create the metadata for stateless verification of a Bolt12Invoice.
292 if $self.refund.payer.0.has_derivation_material() {
293 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
295 if $self.refund.paths.is_none() {
296 metadata = metadata.without_keys();
299 let mut tlv_stream = $self.refund.as_tlv_stream();
300 tlv_stream.0.metadata = None;
301 if metadata.derives_payer_keys() {
302 tlv_stream.2.payer_id = None;
305 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
306 metadata = derived_metadata;
307 if let Some(keys) = keys {
308 $self.refund.payer_id = keys.public_key();
311 $self.refund.payer.0 = metadata;
314 let mut bytes = Vec::new();
315 $self.refund.write(&mut bytes).unwrap();
319 #[cfg(not(c_bindings))]
320 contents: $self.refund,
322 contents: $self.refund.clone(),
328 macro_rules! refund_builder_test_methods { (
329 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
331 #[cfg_attr(c_bindings, allow(dead_code))]
332 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
333 $self.refund.paths = None;
337 #[cfg_attr(c_bindings, allow(dead_code))]
338 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
339 $self.refund.features = features;
344 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
345 refund_explicit_metadata_builder_methods!();
348 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
349 refund_builder_methods!(self, Self, Self, self, T, mut);
352 refund_builder_test_methods!(self, Self, Self, self, mut);
355 #[cfg(all(c_bindings, not(test)))]
356 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
357 refund_explicit_metadata_builder_methods!();
358 refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
361 #[cfg(all(c_bindings, test))]
362 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
363 refund_explicit_metadata_builder_methods!();
364 refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
365 refund_builder_test_methods!(self, &mut Self, &mut Self, self);
369 impl<'a> From<RefundBuilder<'a, secp256k1::All>>
370 for RefundMaybeWithDerivedMetadataBuilder<'a> {
371 fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
372 let RefundBuilder { refund, secp_ctx } = builder;
374 Self { refund, secp_ctx }
379 impl<'a> From<RefundMaybeWithDerivedMetadataBuilder<'a>>
380 for RefundBuilder<'a, secp256k1::All> {
381 fn from(builder: RefundMaybeWithDerivedMetadataBuilder<'a>) -> Self {
382 let RefundMaybeWithDerivedMetadataBuilder { refund, secp_ctx } = builder;
384 Self { refund, secp_ctx }
388 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
390 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
391 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
394 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
395 /// [`Offer`]: crate::offers::offer::Offer
396 #[derive(Clone, Debug)]
398 pub(super) bytes: Vec<u8>,
399 pub(super) contents: RefundContents,
402 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
404 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
405 #[derive(Clone, Debug)]
406 #[cfg_attr(test, derive(PartialEq))]
407 pub(super) struct RefundContents {
408 payer: PayerContents,
411 absolute_expiry: Option<Duration>,
412 issuer: Option<String>,
413 // invoice_request fields
414 chain: Option<ChainHash>,
416 features: InvoiceRequestFeatures,
417 quantity: Option<u64>,
419 payer_note: Option<String>,
420 paths: Option<Vec<BlindedPath>>,
424 /// A complete description of the purpose of the refund. Intended to be displayed to the user
425 /// but with the caveat that it has not been verified in any way.
426 pub fn description(&self) -> PrintableString {
427 self.contents.description()
430 /// Duration since the Unix epoch when an invoice should no longer be sent.
432 /// If `None`, the refund does not expire.
433 pub fn absolute_expiry(&self) -> Option<Duration> {
434 self.contents.absolute_expiry()
437 /// Whether the refund has expired.
438 #[cfg(feature = "std")]
439 pub fn is_expired(&self) -> bool {
440 self.contents.is_expired()
443 /// Whether the refund has expired given the duration since the Unix epoch.
444 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
445 self.contents.is_expired_no_std(duration_since_epoch)
448 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
449 /// displayed to the user but with the caveat that it has not been verified in any way.
450 pub fn issuer(&self) -> Option<PrintableString> {
451 self.contents.issuer()
454 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
455 /// privacy by obfuscating its node id.
456 pub fn paths(&self) -> &[BlindedPath] {
457 self.contents.paths()
460 /// An unpredictable series of bytes, typically containing information about the derivation of
463 /// [`payer_id`]: Self::payer_id
464 pub fn payer_metadata(&self) -> &[u8] {
465 self.contents.metadata()
468 /// A chain that the refund is valid for.
469 pub fn chain(&self) -> ChainHash {
470 self.contents.chain()
473 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
475 /// [`chain`]: Self::chain
476 pub fn amount_msats(&self) -> u64 {
477 self.contents.amount_msats()
480 /// Features pertaining to requesting an invoice.
481 pub fn features(&self) -> &InvoiceRequestFeatures {
482 &self.contents.features()
485 /// The quantity of an item that refund is for.
486 pub fn quantity(&self) -> Option<u64> {
487 self.contents.quantity()
490 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
491 /// transient pubkey.
493 /// [`paths`]: Self::paths
494 pub fn payer_id(&self) -> PublicKey {
495 self.contents.payer_id()
498 /// Payer provided note to include in the invoice.
499 pub fn payer_note(&self) -> Option<PrintableString> {
500 self.contents.payer_note()
504 macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
505 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
506 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
508 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
509 /// time is used for the `created_at` parameter.
511 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
513 /// [`Duration`]: core::time::Duration
514 #[cfg(feature = "std")]
516 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
517 signing_pubkey: PublicKey,
518 ) -> Result<$builder, Bolt12SemanticError> {
519 let created_at = std::time::SystemTime::now()
520 .duration_since(std::time::SystemTime::UNIX_EPOCH)
521 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
523 $self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
526 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
528 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
529 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
530 /// where [`std::time::SystemTime`] is not available.
532 /// The caller is expected to remember the preimage of `payment_hash` in order to
533 /// claim a payment for the invoice.
535 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
536 /// offer, which does have a `signing_pubkey`.
538 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
539 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
540 /// a preference. Note, however, that any privacy is lost if a public node id is used for
541 /// `signing_pubkey`.
543 /// Errors if the request contains unknown required features.
545 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
547 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
548 pub fn respond_with_no_std(
549 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
550 signing_pubkey: PublicKey, created_at: Duration
551 ) -> Result<$builder, Bolt12SemanticError> {
552 if $self.features().requires_unknown_bits() {
553 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
556 <$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
560 macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
561 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
562 /// derived signing keys to sign the [`Bolt12Invoice`].
564 /// See [`Refund::respond_with`] for further details.
566 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
568 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
569 #[cfg(feature = "std")]
570 pub fn respond_using_derived_keys<ES: Deref>(
571 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
572 expanded_key: &ExpandedKey, entropy_source: ES
573 ) -> Result<$builder, Bolt12SemanticError>
575 ES::Target: EntropySource,
577 let created_at = std::time::SystemTime::now()
578 .duration_since(std::time::SystemTime::UNIX_EPOCH)
579 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
581 $self.respond_using_derived_keys_no_std(
582 payment_paths, payment_hash, created_at, expanded_key, entropy_source
586 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
587 /// derived signing keys to sign the [`Bolt12Invoice`].
589 /// See [`Refund::respond_with_no_std`] for further details.
591 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
593 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
594 pub fn respond_using_derived_keys_no_std<ES: Deref>(
595 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
596 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
597 ) -> Result<$builder, Bolt12SemanticError>
599 ES::Target: EntropySource,
601 if $self.features().requires_unknown_bits() {
602 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
605 let nonce = Nonce::from_entropy_source(entropy_source);
606 let keys = signer::derive_keys(nonce, expanded_key);
607 <$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
611 #[cfg(not(c_bindings))]
613 respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
614 respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
619 respond_with_explicit_signing_pubkey_methods!(self, InvoiceWithExplicitSigningPubkeyBuilder);
620 respond_with_derived_signing_pubkey_methods!(self, InvoiceWithDerivedSigningPubkeyBuilder);
625 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
626 self.contents.as_tlv_stream()
630 impl AsRef<[u8]> for Refund {
631 fn as_ref(&self) -> &[u8] {
636 impl PartialEq for Refund {
637 fn eq(&self, other: &Self) -> bool {
638 self.bytes.eq(&other.bytes)
642 impl Eq for Refund {}
644 impl Hash for Refund {
645 fn hash<H: Hasher>(&self, state: &mut H) {
646 self.bytes.hash(state);
650 impl RefundContents {
651 pub fn description(&self) -> PrintableString {
652 PrintableString(&self.description)
655 pub fn absolute_expiry(&self) -> Option<Duration> {
659 #[cfg(feature = "std")]
660 pub(super) fn is_expired(&self) -> bool {
661 SystemTime::UNIX_EPOCH
663 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
667 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
669 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
673 pub fn issuer(&self) -> Option<PrintableString> {
674 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
677 pub fn paths(&self) -> &[BlindedPath] {
678 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
681 pub(super) fn metadata(&self) -> &[u8] {
682 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
685 pub(super) fn chain(&self) -> ChainHash {
686 self.chain.unwrap_or_else(|| self.implied_chain())
689 pub fn implied_chain(&self) -> ChainHash {
690 ChainHash::using_genesis_block(Network::Bitcoin)
693 pub fn amount_msats(&self) -> u64 {
697 /// Features pertaining to requesting an invoice.
698 pub fn features(&self) -> &InvoiceRequestFeatures {
702 /// The quantity of an item that refund is for.
703 pub fn quantity(&self) -> Option<u64> {
707 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
708 /// transient pubkey.
710 /// [`paths`]: Self::paths
711 pub fn payer_id(&self) -> PublicKey {
715 /// Payer provided note to include in the invoice.
716 pub fn payer_note(&self) -> Option<PrintableString> {
717 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
720 pub(super) fn derives_keys(&self) -> bool {
721 self.payer.0.derives_payer_keys()
724 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
725 let payer = PayerTlvStreamRef {
726 metadata: self.payer.0.as_bytes(),
729 let offer = OfferTlvStreamRef {
734 description: Some(&self.description),
736 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
738 issuer: self.issuer.as_ref(),
744 if self.features == InvoiceRequestFeatures::empty() { None }
745 else { Some(&self.features) }
748 let invoice_request = InvoiceRequestTlvStreamRef {
749 chain: self.chain.as_ref(),
750 amount: Some(self.amount_msats),
752 quantity: self.quantity,
753 payer_id: Some(&self.payer_id),
754 payer_note: self.payer_note.as_ref(),
755 paths: self.paths.as_ref(),
758 (payer, offer, invoice_request)
762 impl Writeable for Refund {
763 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
764 WithoutLength(&self.bytes).write(writer)
768 impl Writeable for RefundContents {
769 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
770 self.as_tlv_stream().write(writer)
774 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
776 type RefundTlvStreamRef<'a> = (
777 PayerTlvStreamRef<'a>,
778 OfferTlvStreamRef<'a>,
779 InvoiceRequestTlvStreamRef<'a>,
782 impl SeekReadable for RefundTlvStream {
783 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
784 let payer = SeekReadable::read(r)?;
785 let offer = SeekReadable::read(r)?;
786 let invoice_request = SeekReadable::read(r)?;
788 Ok((payer, offer, invoice_request))
792 impl Bech32Encode for Refund {
793 const BECH32_HRP: &'static str = "lnr";
796 impl FromStr for Refund {
797 type Err = Bolt12ParseError;
799 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
800 Refund::from_bech32_str(s)
804 impl TryFrom<Vec<u8>> for Refund {
805 type Error = Bolt12ParseError;
807 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
808 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
809 let ParsedMessage { bytes, tlv_stream } = refund;
810 let contents = RefundContents::try_from(tlv_stream)?;
812 Ok(Refund { bytes, contents })
816 impl TryFrom<RefundTlvStream> for RefundContents {
817 type Error = Bolt12SemanticError;
819 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
821 PayerTlvStream { metadata: payer_metadata },
823 chains, metadata, currency, amount: offer_amount, description,
824 features: offer_features, absolute_expiry, paths: offer_paths, issuer, quantity_max,
827 InvoiceRequestTlvStream {
828 chain, amount, features, quantity, payer_id, payer_note, paths
832 let payer = match payer_metadata {
833 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
834 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
837 if metadata.is_some() {
838 return Err(Bolt12SemanticError::UnexpectedMetadata);
841 if chains.is_some() {
842 return Err(Bolt12SemanticError::UnexpectedChain);
845 if currency.is_some() || offer_amount.is_some() {
846 return Err(Bolt12SemanticError::UnexpectedAmount);
849 let description = match description {
850 None => return Err(Bolt12SemanticError::MissingDescription),
851 Some(description) => description,
854 if offer_features.is_some() {
855 return Err(Bolt12SemanticError::UnexpectedFeatures);
858 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
860 if offer_paths.is_some() {
861 return Err(Bolt12SemanticError::UnexpectedPaths);
864 if quantity_max.is_some() {
865 return Err(Bolt12SemanticError::UnexpectedQuantity);
868 if node_id.is_some() {
869 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
872 let amount_msats = match amount {
873 None => return Err(Bolt12SemanticError::MissingAmount),
874 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
875 return Err(Bolt12SemanticError::InvalidAmount);
877 Some(amount_msats) => amount_msats,
880 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
882 let payer_id = match payer_id {
883 None => return Err(Bolt12SemanticError::MissingPayerId),
884 Some(payer_id) => payer_id,
888 payer, description, absolute_expiry, issuer, chain, amount_msats, features, quantity,
889 payer_id, payer_note, paths,
894 impl core::fmt::Display for Refund {
895 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
896 self.fmt_bech32_str(f)
902 use super::{Refund, RefundTlvStreamRef};
903 #[cfg(not(c_bindings))]
905 super::RefundBuilder,
909 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
912 use bitcoin::blockdata::constants::ChainHash;
913 use bitcoin::network::constants::Network;
914 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
916 use core::time::Duration;
918 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
919 use crate::sign::KeyMaterial;
920 use crate::ln::channelmanager::PaymentId;
921 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
922 use crate::ln::inbound_payment::ExpandedKey;
923 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
924 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
925 use crate::offers::offer::OfferTlvStreamRef;
926 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
927 use crate::offers::payer::PayerTlvStreamRef;
928 use crate::offers::test_utils::*;
929 use crate::util::ser::{BigSize, Writeable};
930 use crate::util::string::PrintableString;
931 use crate::prelude::*;
934 fn to_bytes(&self) -> Vec<u8>;
937 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
938 fn to_bytes(&self) -> Vec<u8> {
939 let mut buffer = Vec::new();
940 self.write(&mut buffer).unwrap();
946 fn builds_refund_with_defaults() {
947 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
950 let mut buffer = Vec::new();
951 refund.write(&mut buffer).unwrap();
953 assert_eq!(refund.bytes, buffer.as_slice());
954 assert_eq!(refund.payer_metadata(), &[1; 32]);
955 assert_eq!(refund.description(), PrintableString("foo"));
956 assert_eq!(refund.absolute_expiry(), None);
957 #[cfg(feature = "std")]
958 assert!(!refund.is_expired());
959 assert_eq!(refund.paths(), &[]);
960 assert_eq!(refund.issuer(), None);
961 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
962 assert_eq!(refund.amount_msats(), 1000);
963 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
964 assert_eq!(refund.payer_id(), payer_pubkey());
965 assert_eq!(refund.payer_note(), None);
968 refund.as_tlv_stream(),
970 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
976 description: Some(&String::from("foo")),
978 absolute_expiry: None,
984 InvoiceRequestTlvStreamRef {
989 payer_id: Some(&payer_pubkey()),
996 if let Err(e) = Refund::try_from(buffer) {
997 panic!("error parsing refund: {:?}", e);
1002 fn fails_building_refund_with_invalid_amount() {
1003 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
1004 Ok(_) => panic!("expected error"),
1005 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1010 fn builds_refund_with_metadata_derived() {
1011 let desc = "foo".to_string();
1012 let node_id = payer_pubkey();
1013 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1014 let entropy = FixedEntropy {};
1015 let secp_ctx = Secp256k1::new();
1016 let payment_id = PaymentId([1; 32]);
1018 let refund = RefundBuilder
1019 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1022 assert_eq!(refund.payer_id(), node_id);
1024 // Fails verification with altered fields
1025 let invoice = refund
1026 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1029 .sign(recipient_sign).unwrap();
1030 match invoice.verify(&expanded_key, &secp_ctx) {
1031 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1032 Err(()) => panic!("verification failed"),
1035 let mut tlv_stream = refund.as_tlv_stream();
1036 tlv_stream.2.amount = Some(2000);
1038 let mut encoded_refund = Vec::new();
1039 tlv_stream.write(&mut encoded_refund).unwrap();
1041 let invoice = Refund::try_from(encoded_refund).unwrap()
1042 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1045 .sign(recipient_sign).unwrap();
1046 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1048 // Fails verification with altered metadata
1049 let mut tlv_stream = refund.as_tlv_stream();
1050 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1051 tlv_stream.0.metadata = Some(&metadata);
1053 let mut encoded_refund = Vec::new();
1054 tlv_stream.write(&mut encoded_refund).unwrap();
1056 let invoice = Refund::try_from(encoded_refund).unwrap()
1057 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1060 .sign(recipient_sign).unwrap();
1061 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1065 fn builds_refund_with_derived_payer_id() {
1066 let desc = "foo".to_string();
1067 let node_id = payer_pubkey();
1068 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1069 let entropy = FixedEntropy {};
1070 let secp_ctx = Secp256k1::new();
1071 let payment_id = PaymentId([1; 32]);
1073 let blinded_path = BlindedPath {
1074 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1075 blinding_point: pubkey(41),
1077 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1078 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1082 let refund = RefundBuilder
1083 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1087 assert_ne!(refund.payer_id(), node_id);
1089 let invoice = refund
1090 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1093 .sign(recipient_sign).unwrap();
1094 match invoice.verify(&expanded_key, &secp_ctx) {
1095 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1096 Err(()) => panic!("verification failed"),
1099 // Fails verification with altered fields
1100 let mut tlv_stream = refund.as_tlv_stream();
1101 tlv_stream.2.amount = Some(2000);
1103 let mut encoded_refund = Vec::new();
1104 tlv_stream.write(&mut encoded_refund).unwrap();
1106 let invoice = Refund::try_from(encoded_refund).unwrap()
1107 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1110 .sign(recipient_sign).unwrap();
1111 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1113 // Fails verification with altered payer_id
1114 let mut tlv_stream = refund.as_tlv_stream();
1115 let payer_id = pubkey(1);
1116 tlv_stream.2.payer_id = Some(&payer_id);
1118 let mut encoded_refund = Vec::new();
1119 tlv_stream.write(&mut encoded_refund).unwrap();
1121 let invoice = Refund::try_from(encoded_refund).unwrap()
1122 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1125 .sign(recipient_sign).unwrap();
1126 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1130 fn builds_refund_with_absolute_expiry() {
1131 let future_expiry = Duration::from_secs(u64::max_value());
1132 let past_expiry = Duration::from_secs(0);
1133 let now = future_expiry - Duration::from_secs(1_000);
1135 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1136 .absolute_expiry(future_expiry)
1139 let (_, tlv_stream, _) = refund.as_tlv_stream();
1140 #[cfg(feature = "std")]
1141 assert!(!refund.is_expired());
1142 assert!(!refund.is_expired_no_std(now));
1143 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1144 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1146 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1147 .absolute_expiry(future_expiry)
1148 .absolute_expiry(past_expiry)
1151 let (_, tlv_stream, _) = refund.as_tlv_stream();
1152 #[cfg(feature = "std")]
1153 assert!(refund.is_expired());
1154 assert!(refund.is_expired_no_std(now));
1155 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1156 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1160 fn builds_refund_with_paths() {
1163 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1164 blinding_point: pubkey(41),
1166 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1167 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1171 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1172 blinding_point: pubkey(41),
1174 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1175 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1180 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1181 .path(paths[0].clone())
1182 .path(paths[1].clone())
1185 let (_, _, invoice_request_tlv_stream) = refund.as_tlv_stream();
1186 assert_eq!(refund.payer_id(), pubkey(42));
1187 assert_eq!(refund.paths(), paths.as_slice());
1188 assert_ne!(pubkey(42), pubkey(44));
1189 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1190 assert_eq!(invoice_request_tlv_stream.paths, Some(&paths));
1194 fn builds_refund_with_issuer() {
1195 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1196 .issuer("bar".into())
1199 let (_, tlv_stream, _) = refund.as_tlv_stream();
1200 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1201 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1203 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1204 .issuer("bar".into())
1205 .issuer("baz".into())
1208 let (_, tlv_stream, _) = refund.as_tlv_stream();
1209 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1210 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1214 fn builds_refund_with_chain() {
1215 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1216 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1218 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1219 .chain(Network::Bitcoin)
1221 let (_, _, tlv_stream) = refund.as_tlv_stream();
1222 assert_eq!(refund.chain(), mainnet);
1223 assert_eq!(tlv_stream.chain, None);
1225 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1226 .chain(Network::Testnet)
1228 let (_, _, tlv_stream) = refund.as_tlv_stream();
1229 assert_eq!(refund.chain(), testnet);
1230 assert_eq!(tlv_stream.chain, Some(&testnet));
1232 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1233 .chain(Network::Regtest)
1234 .chain(Network::Testnet)
1236 let (_, _, tlv_stream) = refund.as_tlv_stream();
1237 assert_eq!(refund.chain(), testnet);
1238 assert_eq!(tlv_stream.chain, Some(&testnet));
1242 fn builds_refund_with_quantity() {
1243 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1246 let (_, _, tlv_stream) = refund.as_tlv_stream();
1247 assert_eq!(refund.quantity(), Some(10));
1248 assert_eq!(tlv_stream.quantity, Some(10));
1250 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1254 let (_, _, tlv_stream) = refund.as_tlv_stream();
1255 assert_eq!(refund.quantity(), Some(1));
1256 assert_eq!(tlv_stream.quantity, Some(1));
1260 fn builds_refund_with_payer_note() {
1261 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1262 .payer_note("bar".into())
1264 let (_, _, tlv_stream) = refund.as_tlv_stream();
1265 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1266 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1268 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1269 .payer_note("bar".into())
1270 .payer_note("baz".into())
1272 let (_, _, tlv_stream) = refund.as_tlv_stream();
1273 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1274 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1278 fn fails_responding_with_unknown_required_features() {
1279 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1280 .features_unchecked(InvoiceRequestFeatures::unknown())
1282 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1284 Ok(_) => panic!("expected error"),
1285 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1290 fn parses_refund_with_metadata() {
1291 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1293 if let Err(e) = refund.to_string().parse::<Refund>() {
1294 panic!("error parsing refund: {:?}", e);
1297 let mut tlv_stream = refund.as_tlv_stream();
1298 tlv_stream.0.metadata = None;
1300 match Refund::try_from(tlv_stream.to_bytes()) {
1301 Ok(_) => panic!("expected error"),
1303 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1309 fn parses_refund_with_description() {
1310 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1312 if let Err(e) = refund.to_string().parse::<Refund>() {
1313 panic!("error parsing refund: {:?}", e);
1316 let mut tlv_stream = refund.as_tlv_stream();
1317 tlv_stream.1.description = None;
1319 match Refund::try_from(tlv_stream.to_bytes()) {
1320 Ok(_) => panic!("expected error"),
1322 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1328 fn parses_refund_with_amount() {
1329 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1331 if let Err(e) = refund.to_string().parse::<Refund>() {
1332 panic!("error parsing refund: {:?}", e);
1335 let mut tlv_stream = refund.as_tlv_stream();
1336 tlv_stream.2.amount = None;
1338 match Refund::try_from(tlv_stream.to_bytes()) {
1339 Ok(_) => panic!("expected error"),
1341 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1345 let mut tlv_stream = refund.as_tlv_stream();
1346 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1348 match Refund::try_from(tlv_stream.to_bytes()) {
1349 Ok(_) => panic!("expected error"),
1351 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1357 fn parses_refund_with_payer_id() {
1358 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1360 if let Err(e) = refund.to_string().parse::<Refund>() {
1361 panic!("error parsing refund: {:?}", e);
1364 let mut tlv_stream = refund.as_tlv_stream();
1365 tlv_stream.2.payer_id = None;
1367 match Refund::try_from(tlv_stream.to_bytes()) {
1368 Ok(_) => panic!("expected error"),
1370 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1376 fn parses_refund_with_optional_fields() {
1377 let past_expiry = Duration::from_secs(0);
1380 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1381 blinding_point: pubkey(41),
1383 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1384 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1388 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1389 blinding_point: pubkey(41),
1391 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1392 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1397 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1398 .absolute_expiry(past_expiry)
1399 .issuer("bar".into())
1400 .path(paths[0].clone())
1401 .path(paths[1].clone())
1402 .chain(Network::Testnet)
1403 .features_unchecked(InvoiceRequestFeatures::unknown())
1405 .payer_note("baz".into())
1408 match refund.to_string().parse::<Refund>() {
1410 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1411 #[cfg(feature = "std")]
1412 assert!(refund.is_expired());
1413 assert_eq!(refund.paths(), &paths[..]);
1414 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1415 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1416 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1417 assert_eq!(refund.quantity(), Some(10));
1418 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1420 Err(e) => panic!("error parsing refund: {:?}", e),
1425 fn fails_parsing_refund_with_unexpected_fields() {
1426 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1428 if let Err(e) = refund.to_string().parse::<Refund>() {
1429 panic!("error parsing refund: {:?}", e);
1432 let metadata = vec![42; 32];
1433 let mut tlv_stream = refund.as_tlv_stream();
1434 tlv_stream.1.metadata = Some(&metadata);
1436 match Refund::try_from(tlv_stream.to_bytes()) {
1437 Ok(_) => panic!("expected error"),
1439 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1443 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1444 let mut tlv_stream = refund.as_tlv_stream();
1445 tlv_stream.1.chains = Some(&chains);
1447 match Refund::try_from(tlv_stream.to_bytes()) {
1448 Ok(_) => panic!("expected error"),
1450 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1454 let mut tlv_stream = refund.as_tlv_stream();
1455 tlv_stream.1.currency = Some(&b"USD");
1456 tlv_stream.1.amount = Some(1000);
1458 match Refund::try_from(tlv_stream.to_bytes()) {
1459 Ok(_) => panic!("expected error"),
1461 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1465 let features = OfferFeatures::unknown();
1466 let mut tlv_stream = refund.as_tlv_stream();
1467 tlv_stream.1.features = Some(&features);
1469 match Refund::try_from(tlv_stream.to_bytes()) {
1470 Ok(_) => panic!("expected error"),
1472 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1476 let mut tlv_stream = refund.as_tlv_stream();
1477 tlv_stream.1.quantity_max = Some(10);
1479 match Refund::try_from(tlv_stream.to_bytes()) {
1480 Ok(_) => panic!("expected error"),
1482 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1486 let node_id = payer_pubkey();
1487 let mut tlv_stream = refund.as_tlv_stream();
1488 tlv_stream.1.node_id = Some(&node_id);
1490 match Refund::try_from(tlv_stream.to_bytes()) {
1491 Ok(_) => panic!("expected error"),
1493 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1499 fn fails_parsing_refund_with_extra_tlv_records() {
1500 let secp_ctx = Secp256k1::new();
1501 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1502 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1505 let mut encoded_refund = Vec::new();
1506 refund.write(&mut encoded_refund).unwrap();
1507 BigSize(1002).write(&mut encoded_refund).unwrap();
1508 BigSize(32).write(&mut encoded_refund).unwrap();
1509 [42u8; 32].write(&mut encoded_refund).unwrap();
1511 match Refund::try_from(encoded_refund) {
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),