1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for refunds.
12 //! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
13 //! directly to the customer. The recipient responds with a [`Bolt12Invoice`] to be paid.
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
17 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
18 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19 //! [`Offer`]: crate::offers::offer::Offer
24 //! extern crate bitcoin;
25 //! extern crate core;
26 //! extern crate lightning;
28 //! use core::convert::TryFrom;
29 //! use core::time::Duration;
31 //! use bitcoin::network::constants::Network;
32 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
33 //! use lightning::offers::parse::Bolt12ParseError;
34 //! use lightning::offers::refund::{Refund, RefundBuilder};
35 //! use lightning::util::ser::{Readable, Writeable};
37 //! # use lightning::blinded_path::BlindedPath;
38 //! # #[cfg(feature = "std")]
39 //! # use std::time::SystemTime;
41 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
42 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
44 //! # #[cfg(feature = "std")]
45 //! # fn build() -> Result<(), Bolt12ParseError> {
46 //! let secp_ctx = Secp256k1::new();
47 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
48 //! let pubkey = PublicKey::from(keys);
50 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
51 //! let refund = RefundBuilder::new("coffee, large".to_string(), vec![1; 32], pubkey, 20_000)?
52 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
53 //! .issuer("Foo Bar".to_string())
54 //! .path(create_blinded_path())
55 //! .path(create_another_blinded_path())
56 //! .chain(Network::Bitcoin)
57 //! .payer_note("refund for order #12345".to_string())
60 //! // Encode as a bech32 string for use in a QR code.
61 //! let encoded_refund = refund.to_string();
63 //! // Parse from a bech32 string after scanning from a QR code.
64 //! let refund = encoded_refund.parse::<Refund>()?;
66 //! // Encode refund as raw bytes.
67 //! let mut bytes = Vec::new();
68 //! refund.write(&mut bytes).unwrap();
70 //! // Decode raw bytes into an refund.
71 //! let refund = Refund::try_from(bytes)?;
78 //! If constructing a [`Refund`] for use with a [`ChannelManager`], use
79 //! [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
81 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
82 //! [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
84 use bitcoin::blockdata::constants::ChainHash;
85 use bitcoin::network::constants::Network;
86 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
87 use core::convert::TryFrom;
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::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 [`Refund::description`], [`Refund::payer_metadata`], and
154 /// [`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 description: String, 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, absolute_expiry: None, issuer: None,
174 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
175 quantity: None, payer_id, payer_note: 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 description: String, 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, absolute_expiry: None, issuer: None,
213 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
214 quantity: None, payer_id: node_id, payer_note: None,
216 secp_ctx: Some(secp_ctx),
220 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
221 /// already passed is valid and can be checked for using [`Refund::is_expired`].
223 /// Successive calls to this method will override the previous setting.
224 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
225 $self.refund.absolute_expiry = Some(absolute_expiry);
229 /// Sets the [`Refund::issuer`].
231 /// Successive calls to this method will override the previous setting.
232 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
233 $self.refund.issuer = Some(issuer);
237 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
238 /// by private channels or if [`Refund::payer_id`] is not a public node id.
240 /// Successive calls to this method will add another blinded path. Caller is responsible for not
241 /// adding duplicate paths.
242 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
243 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
247 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
248 /// called, [`Network::Bitcoin`] is assumed.
250 /// Successive calls to this method will override the previous setting.
251 pub fn chain($self: $self_type, network: Network) -> $return_type {
252 $self.chain_hash(ChainHash::using_genesis_block(network))
255 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
256 /// [`Network::Bitcoin`] is assumed.
258 /// Successive calls to this method will override the previous setting.
259 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
260 $self.refund.chain = Some(chain);
264 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
265 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
266 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
268 /// Successive calls to this method will override the previous setting.
270 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
271 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
272 /// [`Offer`]: crate::offers::offer::Offer
273 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
274 $self.refund.quantity = Some(quantity);
278 /// Sets the [`Refund::payer_note`].
280 /// Successive calls to this method will override the previous setting.
281 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
282 $self.refund.payer_note = Some(payer_note);
286 /// Builds a [`Refund`] after checking for valid semantics.
287 pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
288 if $self.refund.chain() == $self.refund.implied_chain() {
289 $self.refund.chain = None;
292 // Create the metadata for stateless verification of a Bolt12Invoice.
293 if $self.refund.payer.0.has_derivation_material() {
294 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
296 if $self.refund.paths.is_none() {
297 metadata = metadata.without_keys();
300 let mut tlv_stream = $self.refund.as_tlv_stream();
301 tlv_stream.0.metadata = None;
302 if metadata.derives_payer_keys() {
303 tlv_stream.2.payer_id = None;
306 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
307 metadata = derived_metadata;
308 if let Some(keys) = keys {
309 $self.refund.payer_id = keys.public_key();
312 $self.refund.payer.0 = metadata;
315 let mut bytes = Vec::new();
316 $self.refund.write(&mut bytes).unwrap();
320 #[cfg(not(c_bindings))]
321 contents: $self.refund,
323 contents: $self.refund.clone(),
329 macro_rules! refund_builder_test_methods { (
330 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
332 #[cfg_attr(c_bindings, allow(dead_code))]
333 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
334 $self.refund.paths = None;
338 #[cfg_attr(c_bindings, allow(dead_code))]
339 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
340 $self.refund.features = features;
345 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
346 refund_explicit_metadata_builder_methods!();
349 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
350 refund_builder_methods!(self, Self, Self, self, T, mut);
353 refund_builder_test_methods!(self, Self, Self, self, mut);
356 #[cfg(all(c_bindings, not(test)))]
357 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
358 refund_explicit_metadata_builder_methods!();
359 refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
362 #[cfg(all(c_bindings, test))]
363 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
364 refund_explicit_metadata_builder_methods!();
365 refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
366 refund_builder_test_methods!(self, &mut Self, &mut Self, self);
370 impl<'a> From<RefundBuilder<'a, secp256k1::All>>
371 for RefundMaybeWithDerivedMetadataBuilder<'a> {
372 fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
373 let RefundBuilder { refund, secp_ctx } = builder;
375 Self { refund, secp_ctx }
379 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
381 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
382 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
385 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
386 /// [`Offer`]: crate::offers::offer::Offer
387 #[derive(Clone, Debug)]
389 pub(super) bytes: Vec<u8>,
390 pub(super) contents: RefundContents,
393 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
395 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
396 #[derive(Clone, Debug)]
397 #[cfg_attr(test, derive(PartialEq))]
398 pub(super) struct RefundContents {
399 payer: PayerContents,
402 absolute_expiry: Option<Duration>,
403 issuer: Option<String>,
404 paths: Option<Vec<BlindedPath>>,
405 // invoice_request fields
406 chain: Option<ChainHash>,
408 features: InvoiceRequestFeatures,
409 quantity: Option<u64>,
411 payer_note: Option<String>,
415 /// A complete description of the purpose of the refund. Intended to be displayed to the user
416 /// but with the caveat that it has not been verified in any way.
417 pub fn description(&self) -> PrintableString {
418 self.contents.description()
421 /// Duration since the Unix epoch when an invoice should no longer be sent.
423 /// If `None`, the refund does not expire.
424 pub fn absolute_expiry(&self) -> Option<Duration> {
425 self.contents.absolute_expiry()
428 /// Whether the refund has expired.
429 #[cfg(feature = "std")]
430 pub fn is_expired(&self) -> bool {
431 self.contents.is_expired()
434 /// Whether the refund has expired given the duration since the Unix epoch.
435 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
436 self.contents.is_expired_no_std(duration_since_epoch)
439 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
440 /// displayed to the user but with the caveat that it has not been verified in any way.
441 pub fn issuer(&self) -> Option<PrintableString> {
442 self.contents.issuer()
445 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
446 /// privacy by obfuscating its node id.
447 pub fn paths(&self) -> &[BlindedPath] {
448 self.contents.paths()
451 /// An unpredictable series of bytes, typically containing information about the derivation of
454 /// [`payer_id`]: Self::payer_id
455 pub fn payer_metadata(&self) -> &[u8] {
456 self.contents.metadata()
459 /// A chain that the refund is valid for.
460 pub fn chain(&self) -> ChainHash {
461 self.contents.chain()
464 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
466 /// [`chain`]: Self::chain
467 pub fn amount_msats(&self) -> u64 {
468 self.contents.amount_msats()
471 /// Features pertaining to requesting an invoice.
472 pub fn features(&self) -> &InvoiceRequestFeatures {
473 &self.contents.features()
476 /// The quantity of an item that refund is for.
477 pub fn quantity(&self) -> Option<u64> {
478 self.contents.quantity()
481 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
482 /// transient pubkey.
484 /// [`paths`]: Self::paths
485 pub fn payer_id(&self) -> PublicKey {
486 self.contents.payer_id()
489 /// Payer provided note to include in the invoice.
490 pub fn payer_note(&self) -> Option<PrintableString> {
491 self.contents.payer_note()
495 macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
496 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
497 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
499 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
500 /// time is used for the `created_at` parameter.
502 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
504 /// [`Duration`]: core::time::Duration
505 #[cfg(feature = "std")]
507 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
508 signing_pubkey: PublicKey,
509 ) -> Result<$builder, Bolt12SemanticError> {
510 let created_at = std::time::SystemTime::now()
511 .duration_since(std::time::SystemTime::UNIX_EPOCH)
512 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
514 $self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
517 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
519 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
520 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
521 /// where [`std::time::SystemTime`] is not available.
523 /// The caller is expected to remember the preimage of `payment_hash` in order to
524 /// claim a payment for the invoice.
526 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
527 /// offer, which does have a `signing_pubkey`.
529 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
530 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
531 /// a preference. Note, however, that any privacy is lost if a public node id is used for
532 /// `signing_pubkey`.
534 /// Errors if the request contains unknown required features.
536 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
538 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
539 pub fn respond_with_no_std(
540 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
541 signing_pubkey: PublicKey, created_at: Duration
542 ) -> Result<$builder, Bolt12SemanticError> {
543 if $self.features().requires_unknown_bits() {
544 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
547 <$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
551 macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
552 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
553 /// derived signing keys to sign the [`Bolt12Invoice`].
555 /// See [`Refund::respond_with`] for further details.
557 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
559 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
560 #[cfg(feature = "std")]
561 pub fn respond_using_derived_keys<ES: Deref>(
562 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
563 expanded_key: &ExpandedKey, entropy_source: ES
564 ) -> Result<$builder, Bolt12SemanticError>
566 ES::Target: EntropySource,
568 let created_at = std::time::SystemTime::now()
569 .duration_since(std::time::SystemTime::UNIX_EPOCH)
570 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
572 $self.respond_using_derived_keys_no_std(
573 payment_paths, payment_hash, created_at, expanded_key, entropy_source
577 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
578 /// derived signing keys to sign the [`Bolt12Invoice`].
580 /// See [`Refund::respond_with_no_std`] for further details.
582 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
584 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
585 pub fn respond_using_derived_keys_no_std<ES: Deref>(
586 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
587 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
588 ) -> Result<$builder, Bolt12SemanticError>
590 ES::Target: EntropySource,
592 if $self.features().requires_unknown_bits() {
593 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
596 let nonce = Nonce::from_entropy_source(entropy_source);
597 let keys = signer::derive_keys(nonce, expanded_key);
598 <$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
602 #[cfg(not(c_bindings))]
604 respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
605 respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
610 respond_with_explicit_signing_pubkey_methods!(self, InvoiceWithExplicitSigningPubkeyBuilder);
611 respond_with_derived_signing_pubkey_methods!(self, InvoiceWithDerivedSigningPubkeyBuilder);
616 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
617 self.contents.as_tlv_stream()
621 impl AsRef<[u8]> for Refund {
622 fn as_ref(&self) -> &[u8] {
627 impl PartialEq for Refund {
628 fn eq(&self, other: &Self) -> bool {
629 self.bytes.eq(&other.bytes)
633 impl Eq for Refund {}
635 impl Hash for Refund {
636 fn hash<H: Hasher>(&self, state: &mut H) {
637 self.bytes.hash(state);
641 impl RefundContents {
642 pub fn description(&self) -> PrintableString {
643 PrintableString(&self.description)
646 pub fn absolute_expiry(&self) -> Option<Duration> {
650 #[cfg(feature = "std")]
651 pub(super) fn is_expired(&self) -> bool {
652 SystemTime::UNIX_EPOCH
654 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
658 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
660 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
664 pub fn issuer(&self) -> Option<PrintableString> {
665 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
668 pub fn paths(&self) -> &[BlindedPath] {
669 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
672 pub(super) fn metadata(&self) -> &[u8] {
673 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
676 pub(super) fn chain(&self) -> ChainHash {
677 self.chain.unwrap_or_else(|| self.implied_chain())
680 pub fn implied_chain(&self) -> ChainHash {
681 ChainHash::using_genesis_block(Network::Bitcoin)
684 pub fn amount_msats(&self) -> u64 {
688 /// Features pertaining to requesting an invoice.
689 pub fn features(&self) -> &InvoiceRequestFeatures {
693 /// The quantity of an item that refund is for.
694 pub fn quantity(&self) -> Option<u64> {
698 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
699 /// transient pubkey.
701 /// [`paths`]: Self::paths
702 pub fn payer_id(&self) -> PublicKey {
706 /// Payer provided note to include in the invoice.
707 pub fn payer_note(&self) -> Option<PrintableString> {
708 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
711 pub(super) fn derives_keys(&self) -> bool {
712 self.payer.0.derives_payer_keys()
715 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
716 let payer = PayerTlvStreamRef {
717 metadata: self.payer.0.as_bytes(),
720 let offer = OfferTlvStreamRef {
725 description: Some(&self.description),
727 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
728 paths: self.paths.as_ref(),
729 issuer: self.issuer.as_ref(),
735 if self.features == InvoiceRequestFeatures::empty() { None }
736 else { Some(&self.features) }
739 let invoice_request = InvoiceRequestTlvStreamRef {
740 chain: self.chain.as_ref(),
741 amount: Some(self.amount_msats),
743 quantity: self.quantity,
744 payer_id: Some(&self.payer_id),
745 payer_note: self.payer_note.as_ref(),
748 (payer, offer, invoice_request)
752 impl Writeable for Refund {
753 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
754 WithoutLength(&self.bytes).write(writer)
758 impl Writeable for RefundContents {
759 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
760 self.as_tlv_stream().write(writer)
764 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
766 type RefundTlvStreamRef<'a> = (
767 PayerTlvStreamRef<'a>,
768 OfferTlvStreamRef<'a>,
769 InvoiceRequestTlvStreamRef<'a>,
772 impl SeekReadable for RefundTlvStream {
773 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
774 let payer = SeekReadable::read(r)?;
775 let offer = SeekReadable::read(r)?;
776 let invoice_request = SeekReadable::read(r)?;
778 Ok((payer, offer, invoice_request))
782 impl Bech32Encode for Refund {
783 const BECH32_HRP: &'static str = "lnr";
786 impl FromStr for Refund {
787 type Err = Bolt12ParseError;
789 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
790 Refund::from_bech32_str(s)
794 impl TryFrom<Vec<u8>> for Refund {
795 type Error = Bolt12ParseError;
797 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
798 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
799 let ParsedMessage { bytes, tlv_stream } = refund;
800 let contents = RefundContents::try_from(tlv_stream)?;
802 Ok(Refund { bytes, contents })
806 impl TryFrom<RefundTlvStream> for RefundContents {
807 type Error = Bolt12SemanticError;
809 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
811 PayerTlvStream { metadata: payer_metadata },
813 chains, metadata, currency, amount: offer_amount, description,
814 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
816 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
819 let payer = match payer_metadata {
820 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
821 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
824 if metadata.is_some() {
825 return Err(Bolt12SemanticError::UnexpectedMetadata);
828 if chains.is_some() {
829 return Err(Bolt12SemanticError::UnexpectedChain);
832 if currency.is_some() || offer_amount.is_some() {
833 return Err(Bolt12SemanticError::UnexpectedAmount);
836 let description = match description {
837 None => return Err(Bolt12SemanticError::MissingDescription),
838 Some(description) => description,
841 if offer_features.is_some() {
842 return Err(Bolt12SemanticError::UnexpectedFeatures);
845 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
847 if quantity_max.is_some() {
848 return Err(Bolt12SemanticError::UnexpectedQuantity);
851 if node_id.is_some() {
852 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
855 let amount_msats = match amount {
856 None => return Err(Bolt12SemanticError::MissingAmount),
857 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
858 return Err(Bolt12SemanticError::InvalidAmount);
860 Some(amount_msats) => amount_msats,
863 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
865 let payer_id = match payer_id {
866 None => return Err(Bolt12SemanticError::MissingPayerId),
867 Some(payer_id) => payer_id,
871 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
872 quantity, payer_id, payer_note,
877 impl core::fmt::Display for Refund {
878 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
879 self.fmt_bech32_str(f)
885 use super::{Refund, RefundTlvStreamRef};
886 #[cfg(not(c_bindings))]
888 super::RefundBuilder,
892 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
895 use bitcoin::blockdata::constants::ChainHash;
896 use bitcoin::network::constants::Network;
897 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
898 use core::convert::TryFrom;
899 use core::time::Duration;
900 use crate::blinded_path::{BlindedHop, BlindedPath};
901 use crate::sign::KeyMaterial;
902 use crate::ln::channelmanager::PaymentId;
903 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
904 use crate::ln::inbound_payment::ExpandedKey;
905 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
906 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
907 use crate::offers::offer::OfferTlvStreamRef;
908 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
909 use crate::offers::payer::PayerTlvStreamRef;
910 use crate::offers::test_utils::*;
911 use crate::util::ser::{BigSize, Writeable};
912 use crate::util::string::PrintableString;
915 fn to_bytes(&self) -> Vec<u8>;
918 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
919 fn to_bytes(&self) -> Vec<u8> {
920 let mut buffer = Vec::new();
921 self.write(&mut buffer).unwrap();
927 fn builds_refund_with_defaults() {
928 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
931 let mut buffer = Vec::new();
932 refund.write(&mut buffer).unwrap();
934 assert_eq!(refund.bytes, buffer.as_slice());
935 assert_eq!(refund.payer_metadata(), &[1; 32]);
936 assert_eq!(refund.description(), PrintableString("foo"));
937 assert_eq!(refund.absolute_expiry(), None);
938 #[cfg(feature = "std")]
939 assert!(!refund.is_expired());
940 assert_eq!(refund.paths(), &[]);
941 assert_eq!(refund.issuer(), None);
942 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
943 assert_eq!(refund.amount_msats(), 1000);
944 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
945 assert_eq!(refund.payer_id(), payer_pubkey());
946 assert_eq!(refund.payer_note(), None);
949 refund.as_tlv_stream(),
951 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
957 description: Some(&String::from("foo")),
959 absolute_expiry: None,
965 InvoiceRequestTlvStreamRef {
970 payer_id: Some(&payer_pubkey()),
976 if let Err(e) = Refund::try_from(buffer) {
977 panic!("error parsing refund: {:?}", e);
982 fn fails_building_refund_with_invalid_amount() {
983 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
984 Ok(_) => panic!("expected error"),
985 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
990 fn builds_refund_with_metadata_derived() {
991 let desc = "foo".to_string();
992 let node_id = payer_pubkey();
993 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
994 let entropy = FixedEntropy {};
995 let secp_ctx = Secp256k1::new();
996 let payment_id = PaymentId([1; 32]);
998 let refund = RefundBuilder
999 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1002 assert_eq!(refund.payer_id(), node_id);
1004 // Fails verification with altered fields
1005 let invoice = refund
1006 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1009 .sign(recipient_sign).unwrap();
1010 match invoice.verify(&expanded_key, &secp_ctx) {
1011 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1012 Err(()) => panic!("verification failed"),
1015 let mut tlv_stream = refund.as_tlv_stream();
1016 tlv_stream.2.amount = Some(2000);
1018 let mut encoded_refund = Vec::new();
1019 tlv_stream.write(&mut encoded_refund).unwrap();
1021 let invoice = Refund::try_from(encoded_refund).unwrap()
1022 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1025 .sign(recipient_sign).unwrap();
1026 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1028 // Fails verification with altered metadata
1029 let mut tlv_stream = refund.as_tlv_stream();
1030 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1031 tlv_stream.0.metadata = Some(&metadata);
1033 let mut encoded_refund = Vec::new();
1034 tlv_stream.write(&mut encoded_refund).unwrap();
1036 let invoice = Refund::try_from(encoded_refund).unwrap()
1037 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1040 .sign(recipient_sign).unwrap();
1041 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1045 fn builds_refund_with_derived_payer_id() {
1046 let desc = "foo".to_string();
1047 let node_id = payer_pubkey();
1048 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1049 let entropy = FixedEntropy {};
1050 let secp_ctx = Secp256k1::new();
1051 let payment_id = PaymentId([1; 32]);
1053 let blinded_path = BlindedPath {
1054 introduction_node_id: pubkey(40),
1055 blinding_point: pubkey(41),
1057 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1058 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1062 let refund = RefundBuilder
1063 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1067 assert_ne!(refund.payer_id(), node_id);
1069 let invoice = refund
1070 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1073 .sign(recipient_sign).unwrap();
1074 match invoice.verify(&expanded_key, &secp_ctx) {
1075 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1076 Err(()) => panic!("verification failed"),
1079 // Fails verification with altered fields
1080 let mut tlv_stream = refund.as_tlv_stream();
1081 tlv_stream.2.amount = Some(2000);
1083 let mut encoded_refund = Vec::new();
1084 tlv_stream.write(&mut encoded_refund).unwrap();
1086 let invoice = Refund::try_from(encoded_refund).unwrap()
1087 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1090 .sign(recipient_sign).unwrap();
1091 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1093 // Fails verification with altered payer_id
1094 let mut tlv_stream = refund.as_tlv_stream();
1095 let payer_id = pubkey(1);
1096 tlv_stream.2.payer_id = Some(&payer_id);
1098 let mut encoded_refund = Vec::new();
1099 tlv_stream.write(&mut encoded_refund).unwrap();
1101 let invoice = Refund::try_from(encoded_refund).unwrap()
1102 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1105 .sign(recipient_sign).unwrap();
1106 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1110 fn builds_refund_with_absolute_expiry() {
1111 let future_expiry = Duration::from_secs(u64::max_value());
1112 let past_expiry = Duration::from_secs(0);
1113 let now = future_expiry - Duration::from_secs(1_000);
1115 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1116 .absolute_expiry(future_expiry)
1119 let (_, tlv_stream, _) = refund.as_tlv_stream();
1120 #[cfg(feature = "std")]
1121 assert!(!refund.is_expired());
1122 assert!(!refund.is_expired_no_std(now));
1123 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1124 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1126 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1127 .absolute_expiry(future_expiry)
1128 .absolute_expiry(past_expiry)
1131 let (_, tlv_stream, _) = refund.as_tlv_stream();
1132 #[cfg(feature = "std")]
1133 assert!(refund.is_expired());
1134 assert!(refund.is_expired_no_std(now));
1135 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1136 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1140 fn builds_refund_with_paths() {
1143 introduction_node_id: pubkey(40),
1144 blinding_point: pubkey(41),
1146 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1147 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1151 introduction_node_id: pubkey(40),
1152 blinding_point: pubkey(41),
1154 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1155 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1160 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1161 .path(paths[0].clone())
1162 .path(paths[1].clone())
1165 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1166 assert_eq!(refund.paths(), paths.as_slice());
1167 assert_eq!(refund.payer_id(), pubkey(42));
1168 assert_ne!(pubkey(42), pubkey(44));
1169 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1170 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1174 fn builds_refund_with_issuer() {
1175 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1176 .issuer("bar".into())
1179 let (_, tlv_stream, _) = refund.as_tlv_stream();
1180 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1181 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1183 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1184 .issuer("bar".into())
1185 .issuer("baz".into())
1188 let (_, tlv_stream, _) = refund.as_tlv_stream();
1189 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1190 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1194 fn builds_refund_with_chain() {
1195 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1196 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1198 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1199 .chain(Network::Bitcoin)
1201 let (_, _, tlv_stream) = refund.as_tlv_stream();
1202 assert_eq!(refund.chain(), mainnet);
1203 assert_eq!(tlv_stream.chain, None);
1205 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1206 .chain(Network::Testnet)
1208 let (_, _, tlv_stream) = refund.as_tlv_stream();
1209 assert_eq!(refund.chain(), testnet);
1210 assert_eq!(tlv_stream.chain, Some(&testnet));
1212 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1213 .chain(Network::Regtest)
1214 .chain(Network::Testnet)
1216 let (_, _, tlv_stream) = refund.as_tlv_stream();
1217 assert_eq!(refund.chain(), testnet);
1218 assert_eq!(tlv_stream.chain, Some(&testnet));
1222 fn builds_refund_with_quantity() {
1223 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1226 let (_, _, tlv_stream) = refund.as_tlv_stream();
1227 assert_eq!(refund.quantity(), Some(10));
1228 assert_eq!(tlv_stream.quantity, Some(10));
1230 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1234 let (_, _, tlv_stream) = refund.as_tlv_stream();
1235 assert_eq!(refund.quantity(), Some(1));
1236 assert_eq!(tlv_stream.quantity, Some(1));
1240 fn builds_refund_with_payer_note() {
1241 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1242 .payer_note("bar".into())
1244 let (_, _, tlv_stream) = refund.as_tlv_stream();
1245 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1246 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1248 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1249 .payer_note("bar".into())
1250 .payer_note("baz".into())
1252 let (_, _, tlv_stream) = refund.as_tlv_stream();
1253 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1254 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1258 fn fails_responding_with_unknown_required_features() {
1259 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1260 .features_unchecked(InvoiceRequestFeatures::unknown())
1262 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1264 Ok(_) => panic!("expected error"),
1265 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1270 fn parses_refund_with_metadata() {
1271 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1273 if let Err(e) = refund.to_string().parse::<Refund>() {
1274 panic!("error parsing refund: {:?}", e);
1277 let mut tlv_stream = refund.as_tlv_stream();
1278 tlv_stream.0.metadata = None;
1280 match Refund::try_from(tlv_stream.to_bytes()) {
1281 Ok(_) => panic!("expected error"),
1283 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1289 fn parses_refund_with_description() {
1290 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1292 if let Err(e) = refund.to_string().parse::<Refund>() {
1293 panic!("error parsing refund: {:?}", e);
1296 let mut tlv_stream = refund.as_tlv_stream();
1297 tlv_stream.1.description = None;
1299 match Refund::try_from(tlv_stream.to_bytes()) {
1300 Ok(_) => panic!("expected error"),
1302 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1308 fn parses_refund_with_amount() {
1309 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1311 if let Err(e) = refund.to_string().parse::<Refund>() {
1312 panic!("error parsing refund: {:?}", e);
1315 let mut tlv_stream = refund.as_tlv_stream();
1316 tlv_stream.2.amount = None;
1318 match Refund::try_from(tlv_stream.to_bytes()) {
1319 Ok(_) => panic!("expected error"),
1321 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1325 let mut tlv_stream = refund.as_tlv_stream();
1326 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1328 match Refund::try_from(tlv_stream.to_bytes()) {
1329 Ok(_) => panic!("expected error"),
1331 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1337 fn parses_refund_with_payer_id() {
1338 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1340 if let Err(e) = refund.to_string().parse::<Refund>() {
1341 panic!("error parsing refund: {:?}", e);
1344 let mut tlv_stream = refund.as_tlv_stream();
1345 tlv_stream.2.payer_id = None;
1347 match Refund::try_from(tlv_stream.to_bytes()) {
1348 Ok(_) => panic!("expected error"),
1350 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1356 fn parses_refund_with_optional_fields() {
1357 let past_expiry = Duration::from_secs(0);
1360 introduction_node_id: pubkey(40),
1361 blinding_point: pubkey(41),
1363 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1364 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1368 introduction_node_id: pubkey(40),
1369 blinding_point: pubkey(41),
1371 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1372 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1377 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1378 .absolute_expiry(past_expiry)
1379 .issuer("bar".into())
1380 .path(paths[0].clone())
1381 .path(paths[1].clone())
1382 .chain(Network::Testnet)
1383 .features_unchecked(InvoiceRequestFeatures::unknown())
1385 .payer_note("baz".into())
1388 match refund.to_string().parse::<Refund>() {
1390 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1391 #[cfg(feature = "std")]
1392 assert!(refund.is_expired());
1393 assert_eq!(refund.paths(), &paths[..]);
1394 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1395 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1396 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1397 assert_eq!(refund.quantity(), Some(10));
1398 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1400 Err(e) => panic!("error parsing refund: {:?}", e),
1405 fn fails_parsing_refund_with_unexpected_fields() {
1406 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1408 if let Err(e) = refund.to_string().parse::<Refund>() {
1409 panic!("error parsing refund: {:?}", e);
1412 let metadata = vec![42; 32];
1413 let mut tlv_stream = refund.as_tlv_stream();
1414 tlv_stream.1.metadata = Some(&metadata);
1416 match Refund::try_from(tlv_stream.to_bytes()) {
1417 Ok(_) => panic!("expected error"),
1419 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1423 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1424 let mut tlv_stream = refund.as_tlv_stream();
1425 tlv_stream.1.chains = Some(&chains);
1427 match Refund::try_from(tlv_stream.to_bytes()) {
1428 Ok(_) => panic!("expected error"),
1430 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1434 let mut tlv_stream = refund.as_tlv_stream();
1435 tlv_stream.1.currency = Some(&b"USD");
1436 tlv_stream.1.amount = Some(1000);
1438 match Refund::try_from(tlv_stream.to_bytes()) {
1439 Ok(_) => panic!("expected error"),
1441 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1445 let features = OfferFeatures::unknown();
1446 let mut tlv_stream = refund.as_tlv_stream();
1447 tlv_stream.1.features = Some(&features);
1449 match Refund::try_from(tlv_stream.to_bytes()) {
1450 Ok(_) => panic!("expected error"),
1452 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1456 let mut tlv_stream = refund.as_tlv_stream();
1457 tlv_stream.1.quantity_max = Some(10);
1459 match Refund::try_from(tlv_stream.to_bytes()) {
1460 Ok(_) => panic!("expected error"),
1462 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1466 let node_id = payer_pubkey();
1467 let mut tlv_stream = refund.as_tlv_stream();
1468 tlv_stream.1.node_id = Some(&node_id);
1470 match Refund::try_from(tlv_stream.to_bytes()) {
1471 Ok(_) => panic!("expected error"),
1473 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1479 fn fails_parsing_refund_with_extra_tlv_records() {
1480 let secp_ctx = Secp256k1::new();
1481 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1482 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1485 let mut encoded_refund = Vec::new();
1486 refund.write(&mut encoded_refund).unwrap();
1487 BigSize(1002).write(&mut encoded_refund).unwrap();
1488 BigSize(32).write(&mut encoded_refund).unwrap();
1489 [42u8; 32].write(&mut encoded_refund).unwrap();
1491 match Refund::try_from(encoded_refund) {
1492 Ok(_) => panic!("expected error"),
1493 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),