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(vec![1; 32], pubkey, 20_000)?
52 //! .description("coffee, large".to_string())
53 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
54 //! .issuer("Foo Bar".to_string())
55 //! .path(create_blinded_path())
56 //! .path(create_another_blinded_path())
57 //! .chain(Network::Bitcoin)
58 //! .payer_note("refund for order #12345".to_string())
61 //! // Encode as a bech32 string for use in a QR code.
62 //! let encoded_refund = refund.to_string();
64 //! // Parse from a bech32 string after scanning from a QR code.
65 //! let refund = encoded_refund.parse::<Refund>()?;
67 //! // Encode refund as raw bytes.
68 //! let mut bytes = Vec::new();
69 //! refund.write(&mut bytes).unwrap();
71 //! // Decode raw bytes into an refund.
72 //! let refund = Refund::try_from(bytes)?;
79 //! If constructing a [`Refund`] for use with a [`ChannelManager`], use
80 //! [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
82 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
83 //! [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
85 use bitcoin::blockdata::constants::ChainHash;
86 use bitcoin::network::constants::Network;
87 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
88 use core::hash::{Hash, Hasher};
90 use core::str::FromStr;
91 use core::time::Duration;
92 use crate::sign::EntropySource;
94 use crate::blinded_path::BlindedPath;
95 use crate::ln::types::PaymentHash;
96 use crate::ln::channelmanager::PaymentId;
97 use crate::ln::features::InvoiceRequestFeatures;
98 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
99 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
100 use crate::offers::invoice::BlindedPayInfo;
101 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
102 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
103 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
104 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
105 use crate::offers::signer::{Metadata, MetadataMaterial, self};
106 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
107 use crate::util::string::PrintableString;
109 #[cfg(not(c_bindings))]
111 crate::offers::invoice::{DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder},
115 crate::offers::invoice::{InvoiceWithDerivedSigningPubkeyBuilder, InvoiceWithExplicitSigningPubkeyBuilder},
118 #[allow(unused_imports)]
119 use crate::prelude::*;
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
124 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
126 /// Builds a [`Refund`] for the "offer for money" flow.
128 /// See [module-level documentation] for usage.
130 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
132 /// [module-level documentation]: self
133 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
134 refund: RefundContents,
135 secp_ctx: Option<&'a Secp256k1<T>>,
138 /// Builds a [`Refund`] for the "offer for money" flow.
140 /// See [module-level documentation] for usage.
142 /// [module-level documentation]: self
144 pub struct RefundMaybeWithDerivedMetadataBuilder<'a> {
145 refund: RefundContents,
146 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
149 macro_rules! refund_explicit_metadata_builder_methods { () => {
150 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
151 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
153 /// Additionally, sets the required (empty) [`Refund::description`], [`Refund::payer_metadata`],
154 /// and [`Refund::amount_msats`].
158 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
159 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
161 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
162 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
164 metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
165 ) -> Result<Self, Bolt12SemanticError> {
166 if amount_msats > MAX_VALUE_MSAT {
167 return Err(Bolt12SemanticError::InvalidAmount);
170 let metadata = Metadata::Bytes(metadata);
172 refund: RefundContents {
173 payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
174 issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
175 quantity: None, payer_id, payer_note: None, paths: None,
182 macro_rules! refund_builder_methods { (
183 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
185 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
186 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
187 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
188 /// provided `node_id` is used for the payer id.
190 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
191 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
193 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
194 /// one invoice will be paid for the refund and that payments can be uniquely identified.
196 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
197 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
198 pub fn deriving_payer_id<ES: Deref>(
199 node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
200 secp_ctx: &'a Secp256k1<$secp_context>, amount_msats: u64, payment_id: PaymentId
201 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
202 if amount_msats > MAX_VALUE_MSAT {
203 return Err(Bolt12SemanticError::InvalidAmount);
206 let nonce = Nonce::from_entropy_source(entropy_source);
207 let payment_id = Some(payment_id);
208 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
209 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
211 refund: RefundContents {
212 payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
213 issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
214 quantity: None, payer_id: node_id, payer_note: None, paths: None,
216 secp_ctx: Some(secp_ctx),
220 /// Sets the [`Refund::description`].
222 /// Successive calls to this method will override the previous setting.
223 pub fn description($($self_mut)* $self: $self_type, description: String) -> $return_type {
224 $self.refund.description = description;
228 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
229 /// already passed is valid and can be checked for using [`Refund::is_expired`].
231 /// Successive calls to this method will override the previous setting.
232 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
233 $self.refund.absolute_expiry = Some(absolute_expiry);
237 /// Sets the [`Refund::issuer`].
239 /// Successive calls to this method will override the previous setting.
240 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
241 $self.refund.issuer = Some(issuer);
245 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
246 /// by private channels or if [`Refund::payer_id`] is not a public node id.
248 /// Successive calls to this method will add another blinded path. Caller is responsible for not
249 /// adding duplicate paths.
250 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
251 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
255 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
256 /// called, [`Network::Bitcoin`] is assumed.
258 /// Successive calls to this method will override the previous setting.
259 pub fn chain($self: $self_type, network: Network) -> $return_type {
260 $self.chain_hash(ChainHash::using_genesis_block(network))
263 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
264 /// [`Network::Bitcoin`] is assumed.
266 /// Successive calls to this method will override the previous setting.
267 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
268 $self.refund.chain = Some(chain);
272 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
273 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
274 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
276 /// Successive calls to this method will override the previous setting.
278 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
279 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
280 /// [`Offer`]: crate::offers::offer::Offer
281 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
282 $self.refund.quantity = Some(quantity);
286 /// Sets the [`Refund::payer_note`].
288 /// Successive calls to this method will override the previous setting.
289 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
290 $self.refund.payer_note = Some(payer_note);
294 /// Builds a [`Refund`] after checking for valid semantics.
295 pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
296 if $self.refund.chain() == $self.refund.implied_chain() {
297 $self.refund.chain = None;
300 // Create the metadata for stateless verification of a Bolt12Invoice.
301 if $self.refund.payer.0.has_derivation_material() {
302 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
304 if $self.refund.paths.is_none() {
305 metadata = metadata.without_keys();
308 let mut tlv_stream = $self.refund.as_tlv_stream();
309 tlv_stream.0.metadata = None;
310 if metadata.derives_payer_keys() {
311 tlv_stream.2.payer_id = None;
314 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
315 metadata = derived_metadata;
316 if let Some(keys) = keys {
317 $self.refund.payer_id = keys.public_key();
320 $self.refund.payer.0 = metadata;
323 let mut bytes = Vec::new();
324 $self.refund.write(&mut bytes).unwrap();
328 #[cfg(not(c_bindings))]
329 contents: $self.refund,
331 contents: $self.refund.clone(),
337 macro_rules! refund_builder_test_methods { (
338 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
340 #[cfg_attr(c_bindings, allow(dead_code))]
341 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
342 $self.refund.paths = None;
346 #[cfg_attr(c_bindings, allow(dead_code))]
347 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
348 $self.refund.features = features;
353 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
354 refund_explicit_metadata_builder_methods!();
357 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
358 refund_builder_methods!(self, Self, Self, self, T, mut);
361 refund_builder_test_methods!(self, Self, Self, self, mut);
364 #[cfg(all(c_bindings, not(test)))]
365 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
366 refund_explicit_metadata_builder_methods!();
367 refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
370 #[cfg(all(c_bindings, test))]
371 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
372 refund_explicit_metadata_builder_methods!();
373 refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
374 refund_builder_test_methods!(self, &mut Self, &mut Self, self);
378 impl<'a> From<RefundBuilder<'a, secp256k1::All>>
379 for RefundMaybeWithDerivedMetadataBuilder<'a> {
380 fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
381 let RefundBuilder { refund, secp_ctx } = builder;
383 Self { refund, secp_ctx }
388 impl<'a> From<RefundMaybeWithDerivedMetadataBuilder<'a>>
389 for RefundBuilder<'a, secp256k1::All> {
390 fn from(builder: RefundMaybeWithDerivedMetadataBuilder<'a>) -> Self {
391 let RefundMaybeWithDerivedMetadataBuilder { refund, secp_ctx } = builder;
393 Self { refund, secp_ctx }
397 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
399 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
400 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
403 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
404 /// [`Offer`]: crate::offers::offer::Offer
405 #[derive(Clone, Debug)]
407 pub(super) bytes: Vec<u8>,
408 pub(super) contents: RefundContents,
411 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
413 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
414 #[derive(Clone, Debug)]
415 #[cfg_attr(test, derive(PartialEq))]
416 pub(super) struct RefundContents {
417 payer: PayerContents,
420 absolute_expiry: Option<Duration>,
421 issuer: Option<String>,
422 // invoice_request fields
423 chain: Option<ChainHash>,
425 features: InvoiceRequestFeatures,
426 quantity: Option<u64>,
428 payer_note: Option<String>,
429 paths: Option<Vec<BlindedPath>>,
433 /// A complete description of the purpose of the refund. Intended to be displayed to the user
434 /// but with the caveat that it has not been verified in any way.
435 pub fn description(&self) -> PrintableString {
436 self.contents.description()
439 /// Duration since the Unix epoch when an invoice should no longer be sent.
441 /// If `None`, the refund does not expire.
442 pub fn absolute_expiry(&self) -> Option<Duration> {
443 self.contents.absolute_expiry()
446 /// Whether the refund has expired.
447 #[cfg(feature = "std")]
448 pub fn is_expired(&self) -> bool {
449 self.contents.is_expired()
452 /// Whether the refund has expired given the duration since the Unix epoch.
453 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
454 self.contents.is_expired_no_std(duration_since_epoch)
457 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
458 /// displayed to the user but with the caveat that it has not been verified in any way.
459 pub fn issuer(&self) -> Option<PrintableString> {
460 self.contents.issuer()
463 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
464 /// privacy by obfuscating its node id.
465 pub fn paths(&self) -> &[BlindedPath] {
466 self.contents.paths()
469 /// An unpredictable series of bytes, typically containing information about the derivation of
472 /// [`payer_id`]: Self::payer_id
473 pub fn payer_metadata(&self) -> &[u8] {
474 self.contents.metadata()
477 /// A chain that the refund is valid for.
478 pub fn chain(&self) -> ChainHash {
479 self.contents.chain()
482 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
484 /// [`chain`]: Self::chain
485 pub fn amount_msats(&self) -> u64 {
486 self.contents.amount_msats()
489 /// Features pertaining to requesting an invoice.
490 pub fn features(&self) -> &InvoiceRequestFeatures {
491 &self.contents.features()
494 /// The quantity of an item that refund is for.
495 pub fn quantity(&self) -> Option<u64> {
496 self.contents.quantity()
499 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
500 /// transient pubkey.
502 /// [`paths`]: Self::paths
503 pub fn payer_id(&self) -> PublicKey {
504 self.contents.payer_id()
507 /// Payer provided note to include in the invoice.
508 pub fn payer_note(&self) -> Option<PrintableString> {
509 self.contents.payer_note()
513 macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
514 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
515 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
517 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
518 /// time is used for the `created_at` parameter.
520 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
522 /// [`Duration`]: core::time::Duration
523 #[cfg(feature = "std")]
525 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
526 signing_pubkey: PublicKey,
527 ) -> Result<$builder, Bolt12SemanticError> {
528 let created_at = std::time::SystemTime::now()
529 .duration_since(std::time::SystemTime::UNIX_EPOCH)
530 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
532 $self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
535 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
537 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
538 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
539 /// where [`std::time::SystemTime`] is not available.
541 /// The caller is expected to remember the preimage of `payment_hash` in order to
542 /// claim a payment for the invoice.
544 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
545 /// offer, which does have a `signing_pubkey`.
547 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
548 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
549 /// a preference. Note, however, that any privacy is lost if a public node id is used for
550 /// `signing_pubkey`.
552 /// Errors if the request contains unknown required features.
554 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
556 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
557 pub fn respond_with_no_std(
558 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
559 signing_pubkey: PublicKey, created_at: Duration
560 ) -> Result<$builder, Bolt12SemanticError> {
561 if $self.features().requires_unknown_bits() {
562 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
565 <$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
569 macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
570 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
571 /// derived signing keys to sign the [`Bolt12Invoice`].
573 /// See [`Refund::respond_with`] for further details.
575 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
577 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
578 #[cfg(feature = "std")]
579 pub fn respond_using_derived_keys<ES: Deref>(
580 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
581 expanded_key: &ExpandedKey, entropy_source: ES
582 ) -> Result<$builder, Bolt12SemanticError>
584 ES::Target: EntropySource,
586 let created_at = std::time::SystemTime::now()
587 .duration_since(std::time::SystemTime::UNIX_EPOCH)
588 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
590 $self.respond_using_derived_keys_no_std(
591 payment_paths, payment_hash, created_at, expanded_key, entropy_source
595 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
596 /// derived signing keys to sign the [`Bolt12Invoice`].
598 /// See [`Refund::respond_with_no_std`] for further details.
600 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
602 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
603 pub fn respond_using_derived_keys_no_std<ES: Deref>(
604 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
605 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
606 ) -> Result<$builder, Bolt12SemanticError>
608 ES::Target: EntropySource,
610 if $self.features().requires_unknown_bits() {
611 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
614 let nonce = Nonce::from_entropy_source(entropy_source);
615 let keys = signer::derive_keys(nonce, expanded_key);
616 <$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
620 #[cfg(not(c_bindings))]
622 respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
623 respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
628 respond_with_explicit_signing_pubkey_methods!(self, InvoiceWithExplicitSigningPubkeyBuilder);
629 respond_with_derived_signing_pubkey_methods!(self, InvoiceWithDerivedSigningPubkeyBuilder);
634 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
635 self.contents.as_tlv_stream()
639 impl AsRef<[u8]> for Refund {
640 fn as_ref(&self) -> &[u8] {
645 impl PartialEq for Refund {
646 fn eq(&self, other: &Self) -> bool {
647 self.bytes.eq(&other.bytes)
651 impl Eq for Refund {}
653 impl Hash for Refund {
654 fn hash<H: Hasher>(&self, state: &mut H) {
655 self.bytes.hash(state);
659 impl RefundContents {
660 pub fn description(&self) -> PrintableString {
661 PrintableString(&self.description)
664 pub fn absolute_expiry(&self) -> Option<Duration> {
668 #[cfg(feature = "std")]
669 pub(super) fn is_expired(&self) -> bool {
670 SystemTime::UNIX_EPOCH
672 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
676 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
678 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
682 pub fn issuer(&self) -> Option<PrintableString> {
683 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
686 pub fn paths(&self) -> &[BlindedPath] {
687 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
690 pub(super) fn metadata(&self) -> &[u8] {
691 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
694 pub(super) fn chain(&self) -> ChainHash {
695 self.chain.unwrap_or_else(|| self.implied_chain())
698 pub fn implied_chain(&self) -> ChainHash {
699 ChainHash::using_genesis_block(Network::Bitcoin)
702 pub fn amount_msats(&self) -> u64 {
706 /// Features pertaining to requesting an invoice.
707 pub fn features(&self) -> &InvoiceRequestFeatures {
711 /// The quantity of an item that refund is for.
712 pub fn quantity(&self) -> Option<u64> {
716 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
717 /// transient pubkey.
719 /// [`paths`]: Self::paths
720 pub fn payer_id(&self) -> PublicKey {
724 /// Payer provided note to include in the invoice.
725 pub fn payer_note(&self) -> Option<PrintableString> {
726 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
729 pub(super) fn derives_keys(&self) -> bool {
730 self.payer.0.derives_payer_keys()
733 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
734 let payer = PayerTlvStreamRef {
735 metadata: self.payer.0.as_bytes(),
738 let offer = OfferTlvStreamRef {
743 description: Some(&self.description),
745 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
747 issuer: self.issuer.as_ref(),
753 if self.features == InvoiceRequestFeatures::empty() { None }
754 else { Some(&self.features) }
757 let invoice_request = InvoiceRequestTlvStreamRef {
758 chain: self.chain.as_ref(),
759 amount: Some(self.amount_msats),
761 quantity: self.quantity,
762 payer_id: Some(&self.payer_id),
763 payer_note: self.payer_note.as_ref(),
764 paths: self.paths.as_ref(),
767 (payer, offer, invoice_request)
771 impl Writeable for Refund {
772 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
773 WithoutLength(&self.bytes).write(writer)
777 impl Writeable for RefundContents {
778 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
779 self.as_tlv_stream().write(writer)
783 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
785 type RefundTlvStreamRef<'a> = (
786 PayerTlvStreamRef<'a>,
787 OfferTlvStreamRef<'a>,
788 InvoiceRequestTlvStreamRef<'a>,
791 impl SeekReadable for RefundTlvStream {
792 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
793 let payer = SeekReadable::read(r)?;
794 let offer = SeekReadable::read(r)?;
795 let invoice_request = SeekReadable::read(r)?;
797 Ok((payer, offer, invoice_request))
801 impl Bech32Encode for Refund {
802 const BECH32_HRP: &'static str = "lnr";
805 impl FromStr for Refund {
806 type Err = Bolt12ParseError;
808 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
809 Refund::from_bech32_str(s)
813 impl TryFrom<Vec<u8>> for Refund {
814 type Error = Bolt12ParseError;
816 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
817 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
818 let ParsedMessage { bytes, tlv_stream } = refund;
819 let contents = RefundContents::try_from(tlv_stream)?;
821 Ok(Refund { bytes, contents })
825 impl TryFrom<RefundTlvStream> for RefundContents {
826 type Error = Bolt12SemanticError;
828 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
830 PayerTlvStream { metadata: payer_metadata },
832 chains, metadata, currency, amount: offer_amount, description,
833 features: offer_features, absolute_expiry, paths: offer_paths, issuer, quantity_max,
836 InvoiceRequestTlvStream {
837 chain, amount, features, quantity, payer_id, payer_note, paths
841 let payer = match payer_metadata {
842 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
843 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
846 if metadata.is_some() {
847 return Err(Bolt12SemanticError::UnexpectedMetadata);
850 if chains.is_some() {
851 return Err(Bolt12SemanticError::UnexpectedChain);
854 if currency.is_some() || offer_amount.is_some() {
855 return Err(Bolt12SemanticError::UnexpectedAmount);
858 let description = match description {
859 None => return Err(Bolt12SemanticError::MissingDescription),
860 Some(description) => description,
863 if offer_features.is_some() {
864 return Err(Bolt12SemanticError::UnexpectedFeatures);
867 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
869 if offer_paths.is_some() {
870 return Err(Bolt12SemanticError::UnexpectedPaths);
873 if quantity_max.is_some() {
874 return Err(Bolt12SemanticError::UnexpectedQuantity);
877 if node_id.is_some() {
878 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
881 let amount_msats = match amount {
882 None => return Err(Bolt12SemanticError::MissingAmount),
883 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
884 return Err(Bolt12SemanticError::InvalidAmount);
886 Some(amount_msats) => amount_msats,
889 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
891 let payer_id = match payer_id {
892 None => return Err(Bolt12SemanticError::MissingPayerId),
893 Some(payer_id) => payer_id,
897 payer, description, absolute_expiry, issuer, chain, amount_msats, features, quantity,
898 payer_id, payer_note, paths,
903 impl core::fmt::Display for Refund {
904 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
905 self.fmt_bech32_str(f)
911 use super::{Refund, RefundTlvStreamRef};
912 #[cfg(not(c_bindings))]
914 super::RefundBuilder,
918 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
921 use bitcoin::blockdata::constants::ChainHash;
922 use bitcoin::network::constants::Network;
923 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
925 use core::time::Duration;
927 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
928 use crate::sign::KeyMaterial;
929 use crate::ln::channelmanager::PaymentId;
930 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
931 use crate::ln::inbound_payment::ExpandedKey;
932 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
933 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
934 use crate::offers::offer::OfferTlvStreamRef;
935 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
936 use crate::offers::payer::PayerTlvStreamRef;
937 use crate::offers::test_utils::*;
938 use crate::util::ser::{BigSize, Writeable};
939 use crate::util::string::PrintableString;
940 use crate::prelude::*;
943 fn to_bytes(&self) -> Vec<u8>;
946 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
947 fn to_bytes(&self) -> Vec<u8> {
948 let mut buffer = Vec::new();
949 self.write(&mut buffer).unwrap();
955 fn builds_refund_with_defaults() {
956 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
959 let mut buffer = Vec::new();
960 refund.write(&mut buffer).unwrap();
962 assert_eq!(refund.bytes, buffer.as_slice());
963 assert_eq!(refund.payer_metadata(), &[1; 32]);
964 assert_eq!(refund.description(), PrintableString(""));
965 assert_eq!(refund.absolute_expiry(), None);
966 #[cfg(feature = "std")]
967 assert!(!refund.is_expired());
968 assert_eq!(refund.paths(), &[]);
969 assert_eq!(refund.issuer(), None);
970 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
971 assert_eq!(refund.amount_msats(), 1000);
972 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
973 assert_eq!(refund.payer_id(), payer_pubkey());
974 assert_eq!(refund.payer_note(), None);
977 refund.as_tlv_stream(),
979 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
985 description: Some(&String::from("")),
987 absolute_expiry: None,
993 InvoiceRequestTlvStreamRef {
998 payer_id: Some(&payer_pubkey()),
1005 if let Err(e) = Refund::try_from(buffer) {
1006 panic!("error parsing refund: {:?}", e);
1011 fn fails_building_refund_with_invalid_amount() {
1012 match RefundBuilder::new(vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
1013 Ok(_) => panic!("expected error"),
1014 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1019 fn builds_refund_with_metadata_derived() {
1020 let node_id = payer_pubkey();
1021 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1022 let entropy = FixedEntropy {};
1023 let secp_ctx = Secp256k1::new();
1024 let payment_id = PaymentId([1; 32]);
1026 let refund = RefundBuilder
1027 ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1030 assert_eq!(refund.payer_id(), node_id);
1032 // Fails verification with altered fields
1033 let invoice = refund
1034 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1037 .sign(recipient_sign).unwrap();
1038 match invoice.verify(&expanded_key, &secp_ctx) {
1039 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1040 Err(()) => panic!("verification failed"),
1043 let mut tlv_stream = refund.as_tlv_stream();
1044 tlv_stream.2.amount = Some(2000);
1046 let mut encoded_refund = Vec::new();
1047 tlv_stream.write(&mut encoded_refund).unwrap();
1049 let invoice = Refund::try_from(encoded_refund).unwrap()
1050 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1053 .sign(recipient_sign).unwrap();
1054 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1056 // Fails verification with altered metadata
1057 let mut tlv_stream = refund.as_tlv_stream();
1058 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1059 tlv_stream.0.metadata = Some(&metadata);
1061 let mut encoded_refund = Vec::new();
1062 tlv_stream.write(&mut encoded_refund).unwrap();
1064 let invoice = Refund::try_from(encoded_refund).unwrap()
1065 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1068 .sign(recipient_sign).unwrap();
1069 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1073 fn builds_refund_with_derived_payer_id() {
1074 let node_id = payer_pubkey();
1075 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1076 let entropy = FixedEntropy {};
1077 let secp_ctx = Secp256k1::new();
1078 let payment_id = PaymentId([1; 32]);
1080 let blinded_path = BlindedPath {
1081 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1082 blinding_point: pubkey(41),
1084 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1085 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1089 let refund = RefundBuilder
1090 ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1094 assert_ne!(refund.payer_id(), node_id);
1096 let invoice = refund
1097 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1100 .sign(recipient_sign).unwrap();
1101 match invoice.verify(&expanded_key, &secp_ctx) {
1102 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1103 Err(()) => panic!("verification failed"),
1106 // Fails verification with altered fields
1107 let mut tlv_stream = refund.as_tlv_stream();
1108 tlv_stream.2.amount = Some(2000);
1110 let mut encoded_refund = Vec::new();
1111 tlv_stream.write(&mut encoded_refund).unwrap();
1113 let invoice = Refund::try_from(encoded_refund).unwrap()
1114 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1117 .sign(recipient_sign).unwrap();
1118 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1120 // Fails verification with altered payer_id
1121 let mut tlv_stream = refund.as_tlv_stream();
1122 let payer_id = pubkey(1);
1123 tlv_stream.2.payer_id = Some(&payer_id);
1125 let mut encoded_refund = Vec::new();
1126 tlv_stream.write(&mut encoded_refund).unwrap();
1128 let invoice = Refund::try_from(encoded_refund).unwrap()
1129 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1132 .sign(recipient_sign).unwrap();
1133 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1137 fn builds_refund_with_absolute_expiry() {
1138 let future_expiry = Duration::from_secs(u64::max_value());
1139 let past_expiry = Duration::from_secs(0);
1140 let now = future_expiry - Duration::from_secs(1_000);
1142 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1143 .absolute_expiry(future_expiry)
1146 let (_, tlv_stream, _) = refund.as_tlv_stream();
1147 #[cfg(feature = "std")]
1148 assert!(!refund.is_expired());
1149 assert!(!refund.is_expired_no_std(now));
1150 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1151 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1153 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1154 .absolute_expiry(future_expiry)
1155 .absolute_expiry(past_expiry)
1158 let (_, tlv_stream, _) = refund.as_tlv_stream();
1159 #[cfg(feature = "std")]
1160 assert!(refund.is_expired());
1161 assert!(refund.is_expired_no_std(now));
1162 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1163 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1167 fn builds_refund_with_paths() {
1170 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1171 blinding_point: pubkey(41),
1173 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1174 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1178 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1179 blinding_point: pubkey(41),
1181 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1182 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1187 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1188 .path(paths[0].clone())
1189 .path(paths[1].clone())
1192 let (_, _, invoice_request_tlv_stream) = refund.as_tlv_stream();
1193 assert_eq!(refund.payer_id(), pubkey(42));
1194 assert_eq!(refund.paths(), paths.as_slice());
1195 assert_ne!(pubkey(42), pubkey(44));
1196 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1197 assert_eq!(invoice_request_tlv_stream.paths, Some(&paths));
1201 fn builds_refund_with_issuer() {
1202 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1203 .issuer("bar".into())
1206 let (_, tlv_stream, _) = refund.as_tlv_stream();
1207 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1208 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1210 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1211 .issuer("bar".into())
1212 .issuer("baz".into())
1215 let (_, tlv_stream, _) = refund.as_tlv_stream();
1216 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1217 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1221 fn builds_refund_with_chain() {
1222 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1223 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1225 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1226 .chain(Network::Bitcoin)
1228 let (_, _, tlv_stream) = refund.as_tlv_stream();
1229 assert_eq!(refund.chain(), mainnet);
1230 assert_eq!(tlv_stream.chain, None);
1232 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1233 .chain(Network::Testnet)
1235 let (_, _, tlv_stream) = refund.as_tlv_stream();
1236 assert_eq!(refund.chain(), testnet);
1237 assert_eq!(tlv_stream.chain, Some(&testnet));
1239 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1240 .chain(Network::Regtest)
1241 .chain(Network::Testnet)
1243 let (_, _, tlv_stream) = refund.as_tlv_stream();
1244 assert_eq!(refund.chain(), testnet);
1245 assert_eq!(tlv_stream.chain, Some(&testnet));
1249 fn builds_refund_with_quantity() {
1250 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1253 let (_, _, tlv_stream) = refund.as_tlv_stream();
1254 assert_eq!(refund.quantity(), Some(10));
1255 assert_eq!(tlv_stream.quantity, Some(10));
1257 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1261 let (_, _, tlv_stream) = refund.as_tlv_stream();
1262 assert_eq!(refund.quantity(), Some(1));
1263 assert_eq!(tlv_stream.quantity, Some(1));
1267 fn builds_refund_with_payer_note() {
1268 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1269 .payer_note("bar".into())
1271 let (_, _, tlv_stream) = refund.as_tlv_stream();
1272 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1273 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1275 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1276 .payer_note("bar".into())
1277 .payer_note("baz".into())
1279 let (_, _, tlv_stream) = refund.as_tlv_stream();
1280 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1281 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1285 fn fails_responding_with_unknown_required_features() {
1286 match RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1287 .features_unchecked(InvoiceRequestFeatures::unknown())
1289 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1291 Ok(_) => panic!("expected error"),
1292 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1297 fn parses_refund_with_metadata() {
1298 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1300 if let Err(e) = refund.to_string().parse::<Refund>() {
1301 panic!("error parsing refund: {:?}", e);
1304 let mut tlv_stream = refund.as_tlv_stream();
1305 tlv_stream.0.metadata = None;
1307 match Refund::try_from(tlv_stream.to_bytes()) {
1308 Ok(_) => panic!("expected error"),
1310 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1316 fn parses_refund_with_description() {
1317 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1319 if let Err(e) = refund.to_string().parse::<Refund>() {
1320 panic!("error parsing refund: {:?}", e);
1323 let mut tlv_stream = refund.as_tlv_stream();
1324 tlv_stream.1.description = None;
1326 match Refund::try_from(tlv_stream.to_bytes()) {
1327 Ok(_) => panic!("expected error"),
1329 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1335 fn parses_refund_with_amount() {
1336 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1338 if let Err(e) = refund.to_string().parse::<Refund>() {
1339 panic!("error parsing refund: {:?}", e);
1342 let mut tlv_stream = refund.as_tlv_stream();
1343 tlv_stream.2.amount = None;
1345 match Refund::try_from(tlv_stream.to_bytes()) {
1346 Ok(_) => panic!("expected error"),
1348 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1352 let mut tlv_stream = refund.as_tlv_stream();
1353 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1355 match Refund::try_from(tlv_stream.to_bytes()) {
1356 Ok(_) => panic!("expected error"),
1358 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1364 fn parses_refund_with_payer_id() {
1365 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1367 if let Err(e) = refund.to_string().parse::<Refund>() {
1368 panic!("error parsing refund: {:?}", e);
1371 let mut tlv_stream = refund.as_tlv_stream();
1372 tlv_stream.2.payer_id = None;
1374 match Refund::try_from(tlv_stream.to_bytes()) {
1375 Ok(_) => panic!("expected error"),
1377 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1383 fn parses_refund_with_optional_fields() {
1384 let past_expiry = Duration::from_secs(0);
1387 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1388 blinding_point: pubkey(41),
1390 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1391 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1395 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1396 blinding_point: pubkey(41),
1398 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1399 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1404 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1405 .absolute_expiry(past_expiry)
1406 .issuer("bar".into())
1407 .path(paths[0].clone())
1408 .path(paths[1].clone())
1409 .chain(Network::Testnet)
1410 .features_unchecked(InvoiceRequestFeatures::unknown())
1412 .payer_note("baz".into())
1415 match refund.to_string().parse::<Refund>() {
1417 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1418 #[cfg(feature = "std")]
1419 assert!(refund.is_expired());
1420 assert_eq!(refund.paths(), &paths[..]);
1421 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1422 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1423 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1424 assert_eq!(refund.quantity(), Some(10));
1425 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1427 Err(e) => panic!("error parsing refund: {:?}", e),
1432 fn fails_parsing_refund_with_unexpected_fields() {
1433 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1435 if let Err(e) = refund.to_string().parse::<Refund>() {
1436 panic!("error parsing refund: {:?}", e);
1439 let metadata = vec![42; 32];
1440 let mut tlv_stream = refund.as_tlv_stream();
1441 tlv_stream.1.metadata = Some(&metadata);
1443 match Refund::try_from(tlv_stream.to_bytes()) {
1444 Ok(_) => panic!("expected error"),
1446 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1450 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1451 let mut tlv_stream = refund.as_tlv_stream();
1452 tlv_stream.1.chains = Some(&chains);
1454 match Refund::try_from(tlv_stream.to_bytes()) {
1455 Ok(_) => panic!("expected error"),
1457 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1461 let mut tlv_stream = refund.as_tlv_stream();
1462 tlv_stream.1.currency = Some(&b"USD");
1463 tlv_stream.1.amount = Some(1000);
1465 match Refund::try_from(tlv_stream.to_bytes()) {
1466 Ok(_) => panic!("expected error"),
1468 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1472 let features = OfferFeatures::unknown();
1473 let mut tlv_stream = refund.as_tlv_stream();
1474 tlv_stream.1.features = Some(&features);
1476 match Refund::try_from(tlv_stream.to_bytes()) {
1477 Ok(_) => panic!("expected error"),
1479 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1483 let mut tlv_stream = refund.as_tlv_stream();
1484 tlv_stream.1.quantity_max = Some(10);
1486 match Refund::try_from(tlv_stream.to_bytes()) {
1487 Ok(_) => panic!("expected error"),
1489 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1493 let node_id = payer_pubkey();
1494 let mut tlv_stream = refund.as_tlv_stream();
1495 tlv_stream.1.node_id = Some(&node_id);
1497 match Refund::try_from(tlv_stream.to_bytes()) {
1498 Ok(_) => panic!("expected error"),
1500 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1506 fn fails_parsing_refund_with_extra_tlv_records() {
1507 let secp_ctx = Secp256k1::new();
1508 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1509 let refund = RefundBuilder::new(vec![1; 32], keys.public_key(), 1000).unwrap()
1512 let mut encoded_refund = Vec::new();
1513 refund.write(&mut encoded_refund).unwrap();
1514 BigSize(1002).write(&mut encoded_refund).unwrap();
1515 BigSize(32).write(&mut encoded_refund).unwrap();
1516 [42u8; 32].write(&mut encoded_refund).unwrap();
1518 match Refund::try_from(encoded_refund) {
1519 Ok(_) => panic!("expected error"),
1520 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),