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::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::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, Readable, 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
145 pub struct RefundMaybeWithDerivedMetadataBuilder<'a> {
146 refund: RefundContents,
147 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
150 macro_rules! refund_explicit_metadata_builder_methods { () => {
151 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
152 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
154 /// Additionally, sets the required (empty) [`Refund::description`], [`Refund::payer_metadata`],
155 /// and [`Refund::amount_msats`].
159 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
160 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
162 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
163 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
165 metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
166 ) -> Result<Self, Bolt12SemanticError> {
167 if amount_msats > MAX_VALUE_MSAT {
168 return Err(Bolt12SemanticError::InvalidAmount);
171 let metadata = Metadata::Bytes(metadata);
173 refund: RefundContents {
174 payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
175 issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
176 quantity: None, payer_id, payer_note: None, paths: None,
183 macro_rules! refund_builder_methods { (
184 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
186 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
187 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
188 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
189 /// provided `node_id` is used for the payer id.
191 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
192 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
194 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
195 /// one invoice will be paid for the refund and that payments can be uniquely identified.
197 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
198 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
199 pub fn deriving_payer_id<ES: Deref>(
200 node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
201 secp_ctx: &'a Secp256k1<$secp_context>, amount_msats: u64, payment_id: PaymentId
202 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
203 if amount_msats > MAX_VALUE_MSAT {
204 return Err(Bolt12SemanticError::InvalidAmount);
207 let nonce = Nonce::from_entropy_source(entropy_source);
208 let payment_id = Some(payment_id);
209 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
210 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
212 refund: RefundContents {
213 payer: PayerContents(metadata), description: String::new(), absolute_expiry: None,
214 issuer: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
215 quantity: None, payer_id: node_id, payer_note: None, paths: None,
217 secp_ctx: Some(secp_ctx),
221 /// Sets the [`Refund::description`].
223 /// Successive calls to this method will override the previous setting.
224 pub fn description($($self_mut)* $self: $self_type, description: String) -> $return_type {
225 $self.refund.description = description;
229 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
230 /// already passed is valid and can be checked for using [`Refund::is_expired`].
232 /// Successive calls to this method will override the previous setting.
233 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
234 $self.refund.absolute_expiry = Some(absolute_expiry);
238 /// Sets the [`Refund::issuer`].
240 /// Successive calls to this method will override the previous setting.
241 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
242 $self.refund.issuer = Some(issuer);
246 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
247 /// by private channels or if [`Refund::payer_id`] is not a public node id.
249 /// Successive calls to this method will add another blinded path. Caller is responsible for not
250 /// adding duplicate paths.
251 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
252 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
256 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
257 /// called, [`Network::Bitcoin`] is assumed.
259 /// Successive calls to this method will override the previous setting.
260 pub fn chain($self: $self_type, network: Network) -> $return_type {
261 $self.chain_hash(ChainHash::using_genesis_block(network))
264 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
265 /// [`Network::Bitcoin`] is assumed.
267 /// Successive calls to this method will override the previous setting.
268 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
269 $self.refund.chain = Some(chain);
273 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
274 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
275 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
277 /// Successive calls to this method will override the previous setting.
279 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
280 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
281 /// [`Offer`]: crate::offers::offer::Offer
282 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
283 $self.refund.quantity = Some(quantity);
287 /// Sets the [`Refund::payer_note`].
289 /// Successive calls to this method will override the previous setting.
290 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
291 $self.refund.payer_note = Some(payer_note);
295 /// Builds a [`Refund`] after checking for valid semantics.
296 pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
297 if $self.refund.chain() == $self.refund.implied_chain() {
298 $self.refund.chain = None;
301 // Create the metadata for stateless verification of a Bolt12Invoice.
302 if $self.refund.payer.0.has_derivation_material() {
303 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
305 if $self.refund.paths.is_none() {
306 metadata = metadata.without_keys();
309 let mut tlv_stream = $self.refund.as_tlv_stream();
310 tlv_stream.0.metadata = None;
311 if metadata.derives_payer_keys() {
312 tlv_stream.2.payer_id = None;
315 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
316 metadata = derived_metadata;
317 if let Some(keys) = keys {
318 $self.refund.payer_id = keys.public_key();
321 $self.refund.payer.0 = metadata;
324 let mut bytes = Vec::new();
325 $self.refund.write(&mut bytes).unwrap();
329 #[cfg(not(c_bindings))]
330 contents: $self.refund,
332 contents: $self.refund.clone(),
338 macro_rules! refund_builder_test_methods { (
339 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
341 #[cfg_attr(c_bindings, allow(dead_code))]
342 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
343 $self.refund.paths = None;
347 #[cfg_attr(c_bindings, allow(dead_code))]
348 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
349 $self.refund.features = features;
354 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
355 refund_explicit_metadata_builder_methods!();
358 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
359 refund_builder_methods!(self, Self, Self, self, T, mut);
362 refund_builder_test_methods!(self, Self, Self, self, mut);
365 #[cfg(all(c_bindings, not(test)))]
366 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
367 refund_explicit_metadata_builder_methods!();
368 refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
371 #[cfg(all(c_bindings, test))]
372 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
373 refund_explicit_metadata_builder_methods!();
374 refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
375 refund_builder_test_methods!(self, &mut Self, &mut Self, self);
379 impl<'a> From<RefundBuilder<'a, secp256k1::All>>
380 for RefundMaybeWithDerivedMetadataBuilder<'a> {
381 fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
382 let RefundBuilder { refund, secp_ctx } = builder;
384 Self { refund, secp_ctx }
389 impl<'a> From<RefundMaybeWithDerivedMetadataBuilder<'a>>
390 for RefundBuilder<'a, secp256k1::All> {
391 fn from(builder: RefundMaybeWithDerivedMetadataBuilder<'a>) -> Self {
392 let RefundMaybeWithDerivedMetadataBuilder { refund, secp_ctx } = builder;
394 Self { refund, secp_ctx }
398 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
400 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
401 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
404 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
405 /// [`Offer`]: crate::offers::offer::Offer
406 #[derive(Clone, Debug)]
408 pub(super) bytes: Vec<u8>,
409 pub(super) contents: RefundContents,
412 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
414 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
415 #[derive(Clone, Debug)]
416 #[cfg_attr(test, derive(PartialEq))]
417 pub(super) struct RefundContents {
418 payer: PayerContents,
421 absolute_expiry: Option<Duration>,
422 issuer: Option<String>,
423 // invoice_request fields
424 chain: Option<ChainHash>,
426 features: InvoiceRequestFeatures,
427 quantity: Option<u64>,
429 payer_note: Option<String>,
430 paths: Option<Vec<BlindedPath>>,
434 /// A complete description of the purpose of the refund. Intended to be displayed to the user
435 /// but with the caveat that it has not been verified in any way.
436 pub fn description(&self) -> PrintableString {
437 self.contents.description()
440 /// Duration since the Unix epoch when an invoice should no longer be sent.
442 /// If `None`, the refund does not expire.
443 pub fn absolute_expiry(&self) -> Option<Duration> {
444 self.contents.absolute_expiry()
447 /// Whether the refund has expired.
448 #[cfg(feature = "std")]
449 pub fn is_expired(&self) -> bool {
450 self.contents.is_expired()
453 /// Whether the refund has expired given the duration since the Unix epoch.
454 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
455 self.contents.is_expired_no_std(duration_since_epoch)
458 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
459 /// displayed to the user but with the caveat that it has not been verified in any way.
460 pub fn issuer(&self) -> Option<PrintableString> {
461 self.contents.issuer()
464 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
465 /// privacy by obfuscating its node id.
466 pub fn paths(&self) -> &[BlindedPath] {
467 self.contents.paths()
470 /// An unpredictable series of bytes, typically containing information about the derivation of
473 /// [`payer_id`]: Self::payer_id
474 pub fn payer_metadata(&self) -> &[u8] {
475 self.contents.metadata()
478 /// A chain that the refund is valid for.
479 pub fn chain(&self) -> ChainHash {
480 self.contents.chain()
483 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
485 /// [`chain`]: Self::chain
486 pub fn amount_msats(&self) -> u64 {
487 self.contents.amount_msats()
490 /// Features pertaining to requesting an invoice.
491 pub fn features(&self) -> &InvoiceRequestFeatures {
492 &self.contents.features()
495 /// The quantity of an item that refund is for.
496 pub fn quantity(&self) -> Option<u64> {
497 self.contents.quantity()
500 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
501 /// transient pubkey.
503 /// [`paths`]: Self::paths
504 pub fn payer_id(&self) -> PublicKey {
505 self.contents.payer_id()
508 /// Payer provided note to include in the invoice.
509 pub fn payer_note(&self) -> Option<PrintableString> {
510 self.contents.payer_note()
514 macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
515 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
516 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
518 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
519 /// time is used for the `created_at` parameter.
521 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
523 /// [`Duration`]: core::time::Duration
524 #[cfg(feature = "std")]
526 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
527 signing_pubkey: PublicKey,
528 ) -> Result<$builder, Bolt12SemanticError> {
529 let created_at = std::time::SystemTime::now()
530 .duration_since(std::time::SystemTime::UNIX_EPOCH)
531 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
533 $self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
536 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
538 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
539 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
540 /// where [`std::time::SystemTime`] is not available.
542 /// The caller is expected to remember the preimage of `payment_hash` in order to
543 /// claim a payment for the invoice.
545 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
546 /// offer, which does have a `signing_pubkey`.
548 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
549 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
550 /// a preference. Note, however, that any privacy is lost if a public node id is used for
551 /// `signing_pubkey`.
553 /// Errors if the request contains unknown required features.
555 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
557 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
558 pub fn respond_with_no_std(
559 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
560 signing_pubkey: PublicKey, created_at: Duration
561 ) -> Result<$builder, Bolt12SemanticError> {
562 if $self.features().requires_unknown_bits() {
563 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
566 <$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
570 macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
571 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
572 /// derived signing keys to sign the [`Bolt12Invoice`].
574 /// See [`Refund::respond_with`] for further details.
576 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
578 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
579 #[cfg(feature = "std")]
580 pub fn respond_using_derived_keys<ES: Deref>(
581 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
582 expanded_key: &ExpandedKey, entropy_source: ES
583 ) -> Result<$builder, Bolt12SemanticError>
585 ES::Target: EntropySource,
587 let created_at = std::time::SystemTime::now()
588 .duration_since(std::time::SystemTime::UNIX_EPOCH)
589 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
591 $self.respond_using_derived_keys_no_std(
592 payment_paths, payment_hash, created_at, expanded_key, entropy_source
596 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
597 /// derived signing keys to sign the [`Bolt12Invoice`].
599 /// See [`Refund::respond_with_no_std`] for further details.
601 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
603 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
604 pub fn respond_using_derived_keys_no_std<ES: Deref>(
605 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
606 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
607 ) -> Result<$builder, Bolt12SemanticError>
609 ES::Target: EntropySource,
611 if $self.features().requires_unknown_bits() {
612 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
615 let nonce = Nonce::from_entropy_source(entropy_source);
616 let keys = signer::derive_keys(nonce, expanded_key);
617 <$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
621 #[cfg(not(c_bindings))]
623 respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
624 respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
629 respond_with_explicit_signing_pubkey_methods!(self, InvoiceWithExplicitSigningPubkeyBuilder);
630 respond_with_derived_signing_pubkey_methods!(self, InvoiceWithDerivedSigningPubkeyBuilder);
635 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
636 self.contents.as_tlv_stream()
640 impl AsRef<[u8]> for Refund {
641 fn as_ref(&self) -> &[u8] {
646 impl PartialEq for Refund {
647 fn eq(&self, other: &Self) -> bool {
648 self.bytes.eq(&other.bytes)
652 impl Eq for Refund {}
654 impl Hash for Refund {
655 fn hash<H: Hasher>(&self, state: &mut H) {
656 self.bytes.hash(state);
660 impl RefundContents {
661 pub fn description(&self) -> PrintableString {
662 PrintableString(&self.description)
665 pub fn absolute_expiry(&self) -> Option<Duration> {
669 #[cfg(feature = "std")]
670 pub(super) fn is_expired(&self) -> bool {
671 SystemTime::UNIX_EPOCH
673 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
677 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
679 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
683 pub fn issuer(&self) -> Option<PrintableString> {
684 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
687 pub fn paths(&self) -> &[BlindedPath] {
688 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
691 pub(super) fn metadata(&self) -> &[u8] {
692 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
695 pub(super) fn chain(&self) -> ChainHash {
696 self.chain.unwrap_or_else(|| self.implied_chain())
699 pub fn implied_chain(&self) -> ChainHash {
700 ChainHash::using_genesis_block(Network::Bitcoin)
703 pub fn amount_msats(&self) -> u64 {
707 /// Features pertaining to requesting an invoice.
708 pub fn features(&self) -> &InvoiceRequestFeatures {
712 /// The quantity of an item that refund is for.
713 pub fn quantity(&self) -> Option<u64> {
717 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
718 /// transient pubkey.
720 /// [`paths`]: Self::paths
721 pub fn payer_id(&self) -> PublicKey {
725 /// Payer provided note to include in the invoice.
726 pub fn payer_note(&self) -> Option<PrintableString> {
727 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
730 pub(super) fn derives_keys(&self) -> bool {
731 self.payer.0.derives_payer_keys()
734 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
735 let payer = PayerTlvStreamRef {
736 metadata: self.payer.0.as_bytes(),
739 let offer = OfferTlvStreamRef {
744 description: Some(&self.description),
746 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
748 issuer: self.issuer.as_ref(),
754 if self.features == InvoiceRequestFeatures::empty() { None }
755 else { Some(&self.features) }
758 let invoice_request = InvoiceRequestTlvStreamRef {
759 chain: self.chain.as_ref(),
760 amount: Some(self.amount_msats),
762 quantity: self.quantity,
763 payer_id: Some(&self.payer_id),
764 payer_note: self.payer_note.as_ref(),
765 paths: self.paths.as_ref(),
768 (payer, offer, invoice_request)
772 impl Readable for Refund {
773 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
774 let bytes: WithoutLength<Vec<u8>> = Readable::read(reader)?;
775 Self::try_from(bytes.0).map_err(|_| DecodeError::InvalidValue)
779 impl Writeable for Refund {
780 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
781 WithoutLength(&self.bytes).write(writer)
785 impl Writeable for RefundContents {
786 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
787 self.as_tlv_stream().write(writer)
791 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
793 type RefundTlvStreamRef<'a> = (
794 PayerTlvStreamRef<'a>,
795 OfferTlvStreamRef<'a>,
796 InvoiceRequestTlvStreamRef<'a>,
799 impl SeekReadable for RefundTlvStream {
800 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
801 let payer = SeekReadable::read(r)?;
802 let offer = SeekReadable::read(r)?;
803 let invoice_request = SeekReadable::read(r)?;
805 Ok((payer, offer, invoice_request))
809 impl Bech32Encode for Refund {
810 const BECH32_HRP: &'static str = "lnr";
813 impl FromStr for Refund {
814 type Err = Bolt12ParseError;
816 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
817 Refund::from_bech32_str(s)
821 impl TryFrom<Vec<u8>> for Refund {
822 type Error = Bolt12ParseError;
824 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
825 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
826 let ParsedMessage { bytes, tlv_stream } = refund;
827 let contents = RefundContents::try_from(tlv_stream)?;
829 Ok(Refund { bytes, contents })
833 impl TryFrom<RefundTlvStream> for RefundContents {
834 type Error = Bolt12SemanticError;
836 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
838 PayerTlvStream { metadata: payer_metadata },
840 chains, metadata, currency, amount: offer_amount, description,
841 features: offer_features, absolute_expiry, paths: offer_paths, issuer, quantity_max,
844 InvoiceRequestTlvStream {
845 chain, amount, features, quantity, payer_id, payer_note, paths
849 let payer = match payer_metadata {
850 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
851 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
854 if metadata.is_some() {
855 return Err(Bolt12SemanticError::UnexpectedMetadata);
858 if chains.is_some() {
859 return Err(Bolt12SemanticError::UnexpectedChain);
862 if currency.is_some() || offer_amount.is_some() {
863 return Err(Bolt12SemanticError::UnexpectedAmount);
866 let description = match description {
867 None => return Err(Bolt12SemanticError::MissingDescription),
868 Some(description) => description,
871 if offer_features.is_some() {
872 return Err(Bolt12SemanticError::UnexpectedFeatures);
875 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
877 if offer_paths.is_some() {
878 return Err(Bolt12SemanticError::UnexpectedPaths);
881 if quantity_max.is_some() {
882 return Err(Bolt12SemanticError::UnexpectedQuantity);
885 if node_id.is_some() {
886 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
889 let amount_msats = match amount {
890 None => return Err(Bolt12SemanticError::MissingAmount),
891 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
892 return Err(Bolt12SemanticError::InvalidAmount);
894 Some(amount_msats) => amount_msats,
897 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
899 let payer_id = match payer_id {
900 None => return Err(Bolt12SemanticError::MissingPayerId),
901 Some(payer_id) => payer_id,
905 payer, description, absolute_expiry, issuer, chain, amount_msats, features, quantity,
906 payer_id, payer_note, paths,
911 impl core::fmt::Display for Refund {
912 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
913 self.fmt_bech32_str(f)
919 use super::{Refund, RefundTlvStreamRef};
920 #[cfg(not(c_bindings))]
922 super::RefundBuilder,
926 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
929 use bitcoin::blockdata::constants::ChainHash;
930 use bitcoin::network::Network;
931 use bitcoin::secp256k1::{Keypair, Secp256k1, SecretKey};
933 use core::time::Duration;
935 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
936 use crate::sign::KeyMaterial;
937 use crate::ln::channelmanager::PaymentId;
938 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
939 use crate::ln::inbound_payment::ExpandedKey;
940 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
941 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
942 use crate::offers::offer::OfferTlvStreamRef;
943 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
944 use crate::offers::payer::PayerTlvStreamRef;
945 use crate::offers::test_utils::*;
946 use crate::util::ser::{BigSize, Writeable};
947 use crate::util::string::PrintableString;
948 use crate::prelude::*;
951 fn to_bytes(&self) -> Vec<u8>;
954 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
955 fn to_bytes(&self) -> Vec<u8> {
956 let mut buffer = Vec::new();
957 self.write(&mut buffer).unwrap();
963 fn builds_refund_with_defaults() {
964 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
967 let mut buffer = Vec::new();
968 refund.write(&mut buffer).unwrap();
970 assert_eq!(refund.bytes, buffer.as_slice());
971 assert_eq!(refund.payer_metadata(), &[1; 32]);
972 assert_eq!(refund.description(), PrintableString(""));
973 assert_eq!(refund.absolute_expiry(), None);
974 #[cfg(feature = "std")]
975 assert!(!refund.is_expired());
976 assert_eq!(refund.paths(), &[]);
977 assert_eq!(refund.issuer(), None);
978 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
979 assert_eq!(refund.amount_msats(), 1000);
980 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
981 assert_eq!(refund.payer_id(), payer_pubkey());
982 assert_eq!(refund.payer_note(), None);
985 refund.as_tlv_stream(),
987 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
993 description: Some(&String::from("")),
995 absolute_expiry: None,
1001 InvoiceRequestTlvStreamRef {
1006 payer_id: Some(&payer_pubkey()),
1013 if let Err(e) = Refund::try_from(buffer) {
1014 panic!("error parsing refund: {:?}", e);
1019 fn fails_building_refund_with_invalid_amount() {
1020 match RefundBuilder::new(vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
1021 Ok(_) => panic!("expected error"),
1022 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1027 fn builds_refund_with_metadata_derived() {
1028 let node_id = payer_pubkey();
1029 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1030 let entropy = FixedEntropy {};
1031 let secp_ctx = Secp256k1::new();
1032 let payment_id = PaymentId([1; 32]);
1034 let refund = RefundBuilder
1035 ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1038 assert_eq!(refund.payer_id(), node_id);
1040 // Fails verification with altered fields
1041 let invoice = refund
1042 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1045 .sign(recipient_sign).unwrap();
1046 match invoice.verify(&expanded_key, &secp_ctx) {
1047 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1048 Err(()) => panic!("verification failed"),
1051 let mut tlv_stream = refund.as_tlv_stream();
1052 tlv_stream.2.amount = Some(2000);
1054 let mut encoded_refund = Vec::new();
1055 tlv_stream.write(&mut encoded_refund).unwrap();
1057 let invoice = Refund::try_from(encoded_refund).unwrap()
1058 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1061 .sign(recipient_sign).unwrap();
1062 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1064 // Fails verification with altered metadata
1065 let mut tlv_stream = refund.as_tlv_stream();
1066 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1067 tlv_stream.0.metadata = Some(&metadata);
1069 let mut encoded_refund = Vec::new();
1070 tlv_stream.write(&mut encoded_refund).unwrap();
1072 let invoice = Refund::try_from(encoded_refund).unwrap()
1073 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1076 .sign(recipient_sign).unwrap();
1077 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1081 fn builds_refund_with_derived_payer_id() {
1082 let node_id = payer_pubkey();
1083 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1084 let entropy = FixedEntropy {};
1085 let secp_ctx = Secp256k1::new();
1086 let payment_id = PaymentId([1; 32]);
1088 let blinded_path = BlindedPath {
1089 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1090 blinding_point: pubkey(41),
1092 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1093 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1097 let refund = RefundBuilder
1098 ::deriving_payer_id(node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1102 assert_ne!(refund.payer_id(), node_id);
1104 let invoice = refund
1105 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1108 .sign(recipient_sign).unwrap();
1109 match invoice.verify(&expanded_key, &secp_ctx) {
1110 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1111 Err(()) => panic!("verification failed"),
1114 // Fails verification with altered fields
1115 let mut tlv_stream = refund.as_tlv_stream();
1116 tlv_stream.2.amount = Some(2000);
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());
1128 // Fails verification with altered payer_id
1129 let mut tlv_stream = refund.as_tlv_stream();
1130 let payer_id = pubkey(1);
1131 tlv_stream.2.payer_id = Some(&payer_id);
1133 let mut encoded_refund = Vec::new();
1134 tlv_stream.write(&mut encoded_refund).unwrap();
1136 let invoice = Refund::try_from(encoded_refund).unwrap()
1137 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1140 .sign(recipient_sign).unwrap();
1141 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1145 fn builds_refund_with_absolute_expiry() {
1146 let future_expiry = Duration::from_secs(u64::max_value());
1147 let past_expiry = Duration::from_secs(0);
1148 let now = future_expiry - Duration::from_secs(1_000);
1150 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1151 .absolute_expiry(future_expiry)
1154 let (_, tlv_stream, _) = refund.as_tlv_stream();
1155 #[cfg(feature = "std")]
1156 assert!(!refund.is_expired());
1157 assert!(!refund.is_expired_no_std(now));
1158 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1159 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1161 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1162 .absolute_expiry(future_expiry)
1163 .absolute_expiry(past_expiry)
1166 let (_, tlv_stream, _) = refund.as_tlv_stream();
1167 #[cfg(feature = "std")]
1168 assert!(refund.is_expired());
1169 assert!(refund.is_expired_no_std(now));
1170 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1171 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1175 fn builds_refund_with_paths() {
1178 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1179 blinding_point: pubkey(41),
1181 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1182 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1186 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1187 blinding_point: pubkey(41),
1189 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1190 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1195 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1196 .path(paths[0].clone())
1197 .path(paths[1].clone())
1200 let (_, _, invoice_request_tlv_stream) = refund.as_tlv_stream();
1201 assert_eq!(refund.payer_id(), pubkey(42));
1202 assert_eq!(refund.paths(), paths.as_slice());
1203 assert_ne!(pubkey(42), pubkey(44));
1204 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1205 assert_eq!(invoice_request_tlv_stream.paths, Some(&paths));
1209 fn builds_refund_with_issuer() {
1210 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1211 .issuer("bar".into())
1214 let (_, tlv_stream, _) = refund.as_tlv_stream();
1215 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1216 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1218 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1219 .issuer("bar".into())
1220 .issuer("baz".into())
1223 let (_, tlv_stream, _) = refund.as_tlv_stream();
1224 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1225 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1229 fn builds_refund_with_chain() {
1230 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1231 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1233 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1234 .chain(Network::Bitcoin)
1236 let (_, _, tlv_stream) = refund.as_tlv_stream();
1237 assert_eq!(refund.chain(), mainnet);
1238 assert_eq!(tlv_stream.chain, None);
1240 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
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));
1247 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1248 .chain(Network::Regtest)
1249 .chain(Network::Testnet)
1251 let (_, _, tlv_stream) = refund.as_tlv_stream();
1252 assert_eq!(refund.chain(), testnet);
1253 assert_eq!(tlv_stream.chain, Some(&testnet));
1257 fn builds_refund_with_quantity() {
1258 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(10));
1263 assert_eq!(tlv_stream.quantity, Some(10));
1265 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1269 let (_, _, tlv_stream) = refund.as_tlv_stream();
1270 assert_eq!(refund.quantity(), Some(1));
1271 assert_eq!(tlv_stream.quantity, Some(1));
1275 fn builds_refund_with_payer_note() {
1276 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1277 .payer_note("bar".into())
1279 let (_, _, tlv_stream) = refund.as_tlv_stream();
1280 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1281 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1283 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1284 .payer_note("bar".into())
1285 .payer_note("baz".into())
1287 let (_, _, tlv_stream) = refund.as_tlv_stream();
1288 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1289 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1293 fn fails_responding_with_unknown_required_features() {
1294 match RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1295 .features_unchecked(InvoiceRequestFeatures::unknown())
1297 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1299 Ok(_) => panic!("expected error"),
1300 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1305 fn parses_refund_with_metadata() {
1306 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1308 if let Err(e) = refund.to_string().parse::<Refund>() {
1309 panic!("error parsing refund: {:?}", e);
1312 let mut tlv_stream = refund.as_tlv_stream();
1313 tlv_stream.0.metadata = None;
1315 match Refund::try_from(tlv_stream.to_bytes()) {
1316 Ok(_) => panic!("expected error"),
1318 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1324 fn parses_refund_with_description() {
1325 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1327 if let Err(e) = refund.to_string().parse::<Refund>() {
1328 panic!("error parsing refund: {:?}", e);
1331 let mut tlv_stream = refund.as_tlv_stream();
1332 tlv_stream.1.description = None;
1334 match Refund::try_from(tlv_stream.to_bytes()) {
1335 Ok(_) => panic!("expected error"),
1337 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1343 fn parses_refund_with_amount() {
1344 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1346 if let Err(e) = refund.to_string().parse::<Refund>() {
1347 panic!("error parsing refund: {:?}", e);
1350 let mut tlv_stream = refund.as_tlv_stream();
1351 tlv_stream.2.amount = None;
1353 match Refund::try_from(tlv_stream.to_bytes()) {
1354 Ok(_) => panic!("expected error"),
1356 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1360 let mut tlv_stream = refund.as_tlv_stream();
1361 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1363 match Refund::try_from(tlv_stream.to_bytes()) {
1364 Ok(_) => panic!("expected error"),
1366 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1372 fn parses_refund_with_payer_id() {
1373 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1375 if let Err(e) = refund.to_string().parse::<Refund>() {
1376 panic!("error parsing refund: {:?}", e);
1379 let mut tlv_stream = refund.as_tlv_stream();
1380 tlv_stream.2.payer_id = None;
1382 match Refund::try_from(tlv_stream.to_bytes()) {
1383 Ok(_) => panic!("expected error"),
1385 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1391 fn parses_refund_with_optional_fields() {
1392 let past_expiry = Duration::from_secs(0);
1395 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1396 blinding_point: pubkey(41),
1398 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1399 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1403 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1404 blinding_point: pubkey(41),
1406 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1407 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1412 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1413 .absolute_expiry(past_expiry)
1414 .issuer("bar".into())
1415 .path(paths[0].clone())
1416 .path(paths[1].clone())
1417 .chain(Network::Testnet)
1418 .features_unchecked(InvoiceRequestFeatures::unknown())
1420 .payer_note("baz".into())
1423 match refund.to_string().parse::<Refund>() {
1425 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1426 #[cfg(feature = "std")]
1427 assert!(refund.is_expired());
1428 assert_eq!(refund.paths(), &paths[..]);
1429 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1430 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1431 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1432 assert_eq!(refund.quantity(), Some(10));
1433 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1435 Err(e) => panic!("error parsing refund: {:?}", e),
1440 fn fails_parsing_refund_with_unexpected_fields() {
1441 let refund = RefundBuilder::new(vec![1; 32], payer_pubkey(), 1000).unwrap()
1443 if let Err(e) = refund.to_string().parse::<Refund>() {
1444 panic!("error parsing refund: {:?}", e);
1447 let metadata = vec![42; 32];
1448 let mut tlv_stream = refund.as_tlv_stream();
1449 tlv_stream.1.metadata = Some(&metadata);
1451 match Refund::try_from(tlv_stream.to_bytes()) {
1452 Ok(_) => panic!("expected error"),
1454 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1458 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1459 let mut tlv_stream = refund.as_tlv_stream();
1460 tlv_stream.1.chains = Some(&chains);
1462 match Refund::try_from(tlv_stream.to_bytes()) {
1463 Ok(_) => panic!("expected error"),
1465 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1469 let mut tlv_stream = refund.as_tlv_stream();
1470 tlv_stream.1.currency = Some(&b"USD");
1471 tlv_stream.1.amount = Some(1000);
1473 match Refund::try_from(tlv_stream.to_bytes()) {
1474 Ok(_) => panic!("expected error"),
1476 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1480 let features = OfferFeatures::unknown();
1481 let mut tlv_stream = refund.as_tlv_stream();
1482 tlv_stream.1.features = Some(&features);
1484 match Refund::try_from(tlv_stream.to_bytes()) {
1485 Ok(_) => panic!("expected error"),
1487 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1491 let mut tlv_stream = refund.as_tlv_stream();
1492 tlv_stream.1.quantity_max = Some(10);
1494 match Refund::try_from(tlv_stream.to_bytes()) {
1495 Ok(_) => panic!("expected error"),
1497 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1501 let node_id = payer_pubkey();
1502 let mut tlv_stream = refund.as_tlv_stream();
1503 tlv_stream.1.node_id = Some(&node_id);
1505 match Refund::try_from(tlv_stream.to_bytes()) {
1506 Ok(_) => panic!("expected error"),
1508 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1514 fn fails_parsing_refund_with_extra_tlv_records() {
1515 let secp_ctx = Secp256k1::new();
1516 let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1517 let refund = RefundBuilder::new(vec![1; 32], keys.public_key(), 1000).unwrap()
1520 let mut encoded_refund = Vec::new();
1521 refund.write(&mut encoded_refund).unwrap();
1522 BigSize(1002).write(&mut encoded_refund).unwrap();
1523 BigSize(32).write(&mut encoded_refund).unwrap();
1524 [42u8; 32].write(&mut encoded_refund).unwrap();
1526 match Refund::try_from(encoded_refund) {
1527 Ok(_) => panic!("expected error"),
1528 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),