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;
89 use core::str::FromStr;
90 use core::time::Duration;
91 use crate::sign::EntropySource;
93 use crate::blinded_path::BlindedPath;
94 use crate::ln::PaymentHash;
95 use crate::ln::channelmanager::PaymentId;
96 use crate::ln::features::InvoiceRequestFeatures;
97 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
98 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
99 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
100 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
101 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
102 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
103 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
104 use crate::offers::signer::{Metadata, MetadataMaterial, self};
105 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
106 use crate::util::string::PrintableString;
108 use crate::prelude::*;
110 #[cfg(feature = "std")]
111 use std::time::SystemTime;
113 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
115 /// Builds a [`Refund`] for the "offer for money" flow.
117 /// See [module-level documentation] for usage.
119 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
121 /// [module-level documentation]: self
122 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
123 refund: RefundContents,
124 secp_ctx: Option<&'a Secp256k1<T>>,
127 /// Builds a [`Refund`] for the "offer for money" flow.
129 /// See [module-level documentation] for usage.
131 /// [module-level documentation]: self
133 pub struct RefundMaybeWithDerivedMetadataBuilder<'a> {
134 refund: RefundContents,
135 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
138 macro_rules! refund_explicit_metadata_builder_methods { () => {
139 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
140 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
142 /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
143 /// [`Refund::amount_msats`].
147 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
148 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
150 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
151 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
153 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
154 ) -> Result<Self, Bolt12SemanticError> {
155 if amount_msats > MAX_VALUE_MSAT {
156 return Err(Bolt12SemanticError::InvalidAmount);
159 let metadata = Metadata::Bytes(metadata);
161 refund: RefundContents {
162 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
163 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
164 quantity: None, payer_id, payer_note: None,
171 macro_rules! refund_builder_methods { (
172 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr, $secp_context: ty $(, $self_mut: tt)?
174 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
175 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
176 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
177 /// provided `node_id` is used for the payer id.
179 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
180 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
182 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
183 /// one invoice will be paid for the refund and that payments can be uniquely identified.
185 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
186 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
187 pub fn deriving_payer_id<ES: Deref>(
188 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
189 secp_ctx: &'a Secp256k1<$secp_context>, amount_msats: u64, payment_id: PaymentId
190 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
191 if amount_msats > MAX_VALUE_MSAT {
192 return Err(Bolt12SemanticError::InvalidAmount);
195 let nonce = Nonce::from_entropy_source(entropy_source);
196 let payment_id = Some(payment_id);
197 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
198 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
200 refund: RefundContents {
201 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
202 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
203 quantity: None, payer_id: node_id, payer_note: None,
205 secp_ctx: Some(secp_ctx),
209 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
210 /// already passed is valid and can be checked for using [`Refund::is_expired`].
212 /// Successive calls to this method will override the previous setting.
213 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
214 $self.refund.absolute_expiry = Some(absolute_expiry);
218 /// Sets the [`Refund::issuer`].
220 /// Successive calls to this method will override the previous setting.
221 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
222 $self.refund.issuer = Some(issuer);
226 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
227 /// by private channels or if [`Refund::payer_id`] is not a public node id.
229 /// Successive calls to this method will add another blinded path. Caller is responsible for not
230 /// adding duplicate paths.
231 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
232 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
236 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
237 /// called, [`Network::Bitcoin`] is assumed.
239 /// Successive calls to this method will override the previous setting.
240 pub fn chain($self: $self_type, network: Network) -> $return_type {
241 $self.chain_hash(ChainHash::using_genesis_block(network))
244 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
245 /// [`Network::Bitcoin`] is assumed.
247 /// Successive calls to this method will override the previous setting.
248 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
249 $self.refund.chain = Some(chain);
253 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
254 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
255 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
257 /// Successive calls to this method will override the previous setting.
259 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
260 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
261 /// [`Offer`]: crate::offers::offer::Offer
262 pub fn quantity($($self_mut)* $self: $self_type, quantity: u64) -> $return_type {
263 $self.refund.quantity = Some(quantity);
267 /// Sets the [`Refund::payer_note`].
269 /// Successive calls to this method will override the previous setting.
270 pub fn payer_note($($self_mut)* $self: $self_type, payer_note: String) -> $return_type {
271 $self.refund.payer_note = Some(payer_note);
275 /// Builds a [`Refund`] after checking for valid semantics.
276 pub fn build($($self_mut)* $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
277 if $self.refund.chain() == $self.refund.implied_chain() {
278 $self.refund.chain = None;
281 // Create the metadata for stateless verification of a Bolt12Invoice.
282 if $self.refund.payer.0.has_derivation_material() {
283 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
285 if $self.refund.paths.is_none() {
286 metadata = metadata.without_keys();
289 let mut tlv_stream = $self.refund.as_tlv_stream();
290 tlv_stream.0.metadata = None;
291 if metadata.derives_payer_keys() {
292 tlv_stream.2.payer_id = None;
295 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
296 metadata = derived_metadata;
297 if let Some(keys) = keys {
298 $self.refund.payer_id = keys.public_key();
301 $self.refund.payer.0 = metadata;
304 let mut bytes = Vec::new();
305 $self.refund.write(&mut bytes).unwrap();
309 #[cfg(not(c_bindings))]
310 contents: $self.refund,
312 contents: $self.refund.clone(),
318 macro_rules! refund_builder_test_methods { (
319 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
321 #[cfg_attr(c_bindings, allow(dead_code))]
322 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
323 $self.refund.paths = None;
327 #[cfg_attr(c_bindings, allow(dead_code))]
328 fn features_unchecked($($self_mut)* $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
329 $self.refund.features = features;
334 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
335 refund_explicit_metadata_builder_methods!();
338 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
339 refund_builder_methods!(self, Self, Self, self, T, mut);
342 refund_builder_test_methods!(self, Self, Self, self, mut);
345 #[cfg(all(c_bindings, not(test)))]
346 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
347 refund_explicit_metadata_builder_methods!();
348 refund_builder_methods!(self, &mut Self, (), (), secp256k1::All);
351 #[cfg(all(c_bindings, test))]
352 impl<'a> RefundMaybeWithDerivedMetadataBuilder<'a> {
353 refund_explicit_metadata_builder_methods!();
354 refund_builder_methods!(self, &mut Self, &mut Self, self, secp256k1::All);
355 refund_builder_test_methods!(self, &mut Self, &mut Self, self);
359 impl<'a> From<RefundBuilder<'a, secp256k1::All>>
360 for RefundMaybeWithDerivedMetadataBuilder<'a> {
361 fn from(builder: RefundBuilder<'a, secp256k1::All>) -> Self {
362 let RefundBuilder { refund, secp_ctx } = builder;
364 Self { refund, secp_ctx }
368 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
370 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
371 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
374 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
375 /// [`Offer`]: crate::offers::offer::Offer
376 #[derive(Clone, Debug)]
377 #[cfg_attr(test, derive(PartialEq))]
379 pub(super) bytes: Vec<u8>,
380 pub(super) contents: RefundContents,
383 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
385 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
386 #[derive(Clone, Debug)]
387 #[cfg_attr(test, derive(PartialEq))]
388 pub(super) struct RefundContents {
389 payer: PayerContents,
392 absolute_expiry: Option<Duration>,
393 issuer: Option<String>,
394 paths: Option<Vec<BlindedPath>>,
395 // invoice_request fields
396 chain: Option<ChainHash>,
398 features: InvoiceRequestFeatures,
399 quantity: Option<u64>,
401 payer_note: Option<String>,
405 /// A complete description of the purpose of the refund. Intended to be displayed to the user
406 /// but with the caveat that it has not been verified in any way.
407 pub fn description(&self) -> PrintableString {
408 self.contents.description()
411 /// Duration since the Unix epoch when an invoice should no longer be sent.
413 /// If `None`, the refund does not expire.
414 pub fn absolute_expiry(&self) -> Option<Duration> {
415 self.contents.absolute_expiry()
418 /// Whether the refund has expired.
419 #[cfg(feature = "std")]
420 pub fn is_expired(&self) -> bool {
421 self.contents.is_expired()
424 /// Whether the refund has expired given the duration since the Unix epoch.
425 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
426 self.contents.is_expired_no_std(duration_since_epoch)
429 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
430 /// displayed to the user but with the caveat that it has not been verified in any way.
431 pub fn issuer(&self) -> Option<PrintableString> {
432 self.contents.issuer()
435 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
436 /// privacy by obfuscating its node id.
437 pub fn paths(&self) -> &[BlindedPath] {
438 self.contents.paths()
441 /// An unpredictable series of bytes, typically containing information about the derivation of
444 /// [`payer_id`]: Self::payer_id
445 pub fn payer_metadata(&self) -> &[u8] {
446 self.contents.metadata()
449 /// A chain that the refund is valid for.
450 pub fn chain(&self) -> ChainHash {
451 self.contents.chain()
454 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
456 /// [`chain`]: Self::chain
457 pub fn amount_msats(&self) -> u64 {
458 self.contents.amount_msats()
461 /// Features pertaining to requesting an invoice.
462 pub fn features(&self) -> &InvoiceRequestFeatures {
463 &self.contents.features()
466 /// The quantity of an item that refund is for.
467 pub fn quantity(&self) -> Option<u64> {
468 self.contents.quantity()
471 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
472 /// transient pubkey.
474 /// [`paths`]: Self::paths
475 pub fn payer_id(&self) -> PublicKey {
476 self.contents.payer_id()
479 /// Payer provided note to include in the invoice.
480 pub fn payer_note(&self) -> Option<PrintableString> {
481 self.contents.payer_note()
485 macro_rules! respond_with_explicit_signing_pubkey_methods { ($self: ident, $builder: ty) => {
486 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
487 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
489 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
490 /// time is used for the `created_at` parameter.
492 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
494 /// [`Duration`]: core::time::Duration
495 #[cfg(feature = "std")]
497 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
498 signing_pubkey: PublicKey,
499 ) -> Result<$builder, Bolt12SemanticError> {
500 let created_at = std::time::SystemTime::now()
501 .duration_since(std::time::SystemTime::UNIX_EPOCH)
502 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
504 $self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
507 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
509 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
510 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
511 /// where [`std::time::SystemTime`] is not available.
513 /// The caller is expected to remember the preimage of `payment_hash` in order to
514 /// claim a payment for the invoice.
516 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
517 /// offer, which does have a `signing_pubkey`.
519 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
520 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
521 /// a preference. Note, however, that any privacy is lost if a public node id is used for
522 /// `signing_pubkey`.
524 /// Errors if the request contains unknown required features.
526 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
528 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
529 pub fn respond_with_no_std(
530 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
531 signing_pubkey: PublicKey, created_at: Duration
532 ) -> Result<$builder, Bolt12SemanticError> {
533 if $self.features().requires_unknown_bits() {
534 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
537 <$builder>::for_refund($self, payment_paths, created_at, payment_hash, signing_pubkey)
541 macro_rules! respond_with_derived_signing_pubkey_methods { ($self: ident, $builder: ty) => {
542 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
543 /// derived signing keys to sign the [`Bolt12Invoice`].
545 /// See [`Refund::respond_with`] for further details.
547 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
549 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
550 #[cfg(feature = "std")]
551 pub fn respond_using_derived_keys<ES: Deref>(
552 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
553 expanded_key: &ExpandedKey, entropy_source: ES
554 ) -> Result<$builder, Bolt12SemanticError>
556 ES::Target: EntropySource,
558 let created_at = std::time::SystemTime::now()
559 .duration_since(std::time::SystemTime::UNIX_EPOCH)
560 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
562 $self.respond_using_derived_keys_no_std(
563 payment_paths, payment_hash, created_at, expanded_key, entropy_source
567 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
568 /// derived signing keys to sign the [`Bolt12Invoice`].
570 /// See [`Refund::respond_with_no_std`] for further details.
572 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
574 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
575 pub fn respond_using_derived_keys_no_std<ES: Deref>(
576 &$self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
577 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
578 ) -> Result<$builder, Bolt12SemanticError>
580 ES::Target: EntropySource,
582 if $self.features().requires_unknown_bits() {
583 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
586 let nonce = Nonce::from_entropy_source(entropy_source);
587 let keys = signer::derive_keys(nonce, expanded_key);
588 <$builder>::for_refund_using_keys($self, payment_paths, created_at, payment_hash, keys)
593 respond_with_explicit_signing_pubkey_methods!(self, InvoiceBuilder<ExplicitSigningPubkey>);
594 respond_with_derived_signing_pubkey_methods!(self, InvoiceBuilder<DerivedSigningPubkey>);
599 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
600 self.contents.as_tlv_stream()
604 impl AsRef<[u8]> for Refund {
605 fn as_ref(&self) -> &[u8] {
610 impl RefundContents {
611 pub fn description(&self) -> PrintableString {
612 PrintableString(&self.description)
615 pub fn absolute_expiry(&self) -> Option<Duration> {
619 #[cfg(feature = "std")]
620 pub(super) fn is_expired(&self) -> bool {
621 SystemTime::UNIX_EPOCH
623 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
627 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
629 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
633 pub fn issuer(&self) -> Option<PrintableString> {
634 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
637 pub fn paths(&self) -> &[BlindedPath] {
638 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
641 pub(super) fn metadata(&self) -> &[u8] {
642 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
645 pub(super) fn chain(&self) -> ChainHash {
646 self.chain.unwrap_or_else(|| self.implied_chain())
649 pub fn implied_chain(&self) -> ChainHash {
650 ChainHash::using_genesis_block(Network::Bitcoin)
653 pub fn amount_msats(&self) -> u64 {
657 /// Features pertaining to requesting an invoice.
658 pub fn features(&self) -> &InvoiceRequestFeatures {
662 /// The quantity of an item that refund is for.
663 pub fn quantity(&self) -> Option<u64> {
667 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
668 /// transient pubkey.
670 /// [`paths`]: Self::paths
671 pub fn payer_id(&self) -> PublicKey {
675 /// Payer provided note to include in the invoice.
676 pub fn payer_note(&self) -> Option<PrintableString> {
677 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
680 pub(super) fn derives_keys(&self) -> bool {
681 self.payer.0.derives_payer_keys()
684 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
685 let payer = PayerTlvStreamRef {
686 metadata: self.payer.0.as_bytes(),
689 let offer = OfferTlvStreamRef {
694 description: Some(&self.description),
696 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
697 paths: self.paths.as_ref(),
698 issuer: self.issuer.as_ref(),
704 if self.features == InvoiceRequestFeatures::empty() { None }
705 else { Some(&self.features) }
708 let invoice_request = InvoiceRequestTlvStreamRef {
709 chain: self.chain.as_ref(),
710 amount: Some(self.amount_msats),
712 quantity: self.quantity,
713 payer_id: Some(&self.payer_id),
714 payer_note: self.payer_note.as_ref(),
717 (payer, offer, invoice_request)
721 impl Writeable for Refund {
722 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
723 WithoutLength(&self.bytes).write(writer)
727 impl Writeable for RefundContents {
728 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
729 self.as_tlv_stream().write(writer)
733 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
735 type RefundTlvStreamRef<'a> = (
736 PayerTlvStreamRef<'a>,
737 OfferTlvStreamRef<'a>,
738 InvoiceRequestTlvStreamRef<'a>,
741 impl SeekReadable for RefundTlvStream {
742 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
743 let payer = SeekReadable::read(r)?;
744 let offer = SeekReadable::read(r)?;
745 let invoice_request = SeekReadable::read(r)?;
747 Ok((payer, offer, invoice_request))
751 impl Bech32Encode for Refund {
752 const BECH32_HRP: &'static str = "lnr";
755 impl FromStr for Refund {
756 type Err = Bolt12ParseError;
758 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
759 Refund::from_bech32_str(s)
763 impl TryFrom<Vec<u8>> for Refund {
764 type Error = Bolt12ParseError;
766 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
767 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
768 let ParsedMessage { bytes, tlv_stream } = refund;
769 let contents = RefundContents::try_from(tlv_stream)?;
771 Ok(Refund { bytes, contents })
775 impl TryFrom<RefundTlvStream> for RefundContents {
776 type Error = Bolt12SemanticError;
778 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
780 PayerTlvStream { metadata: payer_metadata },
782 chains, metadata, currency, amount: offer_amount, description,
783 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
785 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
788 let payer = match payer_metadata {
789 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
790 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
793 if metadata.is_some() {
794 return Err(Bolt12SemanticError::UnexpectedMetadata);
797 if chains.is_some() {
798 return Err(Bolt12SemanticError::UnexpectedChain);
801 if currency.is_some() || offer_amount.is_some() {
802 return Err(Bolt12SemanticError::UnexpectedAmount);
805 let description = match description {
806 None => return Err(Bolt12SemanticError::MissingDescription),
807 Some(description) => description,
810 if offer_features.is_some() {
811 return Err(Bolt12SemanticError::UnexpectedFeatures);
814 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
816 if quantity_max.is_some() {
817 return Err(Bolt12SemanticError::UnexpectedQuantity);
820 if node_id.is_some() {
821 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
824 let amount_msats = match amount {
825 None => return Err(Bolt12SemanticError::MissingAmount),
826 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
827 return Err(Bolt12SemanticError::InvalidAmount);
829 Some(amount_msats) => amount_msats,
832 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
834 let payer_id = match payer_id {
835 None => return Err(Bolt12SemanticError::MissingPayerId),
836 Some(payer_id) => payer_id,
840 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
841 quantity, payer_id, payer_note,
846 impl core::fmt::Display for Refund {
847 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
848 self.fmt_bech32_str(f)
854 use super::{Refund, RefundTlvStreamRef};
855 #[cfg(not(c_bindings))]
857 super::RefundBuilder,
861 super::RefundMaybeWithDerivedMetadataBuilder as RefundBuilder,
864 use bitcoin::blockdata::constants::ChainHash;
865 use bitcoin::network::constants::Network;
866 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
867 use core::convert::TryFrom;
868 use core::time::Duration;
869 use crate::blinded_path::{BlindedHop, BlindedPath};
870 use crate::sign::KeyMaterial;
871 use crate::ln::channelmanager::PaymentId;
872 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
873 use crate::ln::inbound_payment::ExpandedKey;
874 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
875 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
876 use crate::offers::offer::OfferTlvStreamRef;
877 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
878 use crate::offers::payer::PayerTlvStreamRef;
879 use crate::offers::test_utils::*;
880 use crate::util::ser::{BigSize, Writeable};
881 use crate::util::string::PrintableString;
884 fn to_bytes(&self) -> Vec<u8>;
887 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
888 fn to_bytes(&self) -> Vec<u8> {
889 let mut buffer = Vec::new();
890 self.write(&mut buffer).unwrap();
896 fn builds_refund_with_defaults() {
897 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
900 let mut buffer = Vec::new();
901 refund.write(&mut buffer).unwrap();
903 assert_eq!(refund.bytes, buffer.as_slice());
904 assert_eq!(refund.payer_metadata(), &[1; 32]);
905 assert_eq!(refund.description(), PrintableString("foo"));
906 assert_eq!(refund.absolute_expiry(), None);
907 #[cfg(feature = "std")]
908 assert!(!refund.is_expired());
909 assert_eq!(refund.paths(), &[]);
910 assert_eq!(refund.issuer(), None);
911 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
912 assert_eq!(refund.amount_msats(), 1000);
913 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
914 assert_eq!(refund.payer_id(), payer_pubkey());
915 assert_eq!(refund.payer_note(), None);
918 refund.as_tlv_stream(),
920 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
926 description: Some(&String::from("foo")),
928 absolute_expiry: None,
934 InvoiceRequestTlvStreamRef {
939 payer_id: Some(&payer_pubkey()),
945 if let Err(e) = Refund::try_from(buffer) {
946 panic!("error parsing refund: {:?}", e);
951 fn fails_building_refund_with_invalid_amount() {
952 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
953 Ok(_) => panic!("expected error"),
954 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
959 fn builds_refund_with_metadata_derived() {
960 let desc = "foo".to_string();
961 let node_id = payer_pubkey();
962 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
963 let entropy = FixedEntropy {};
964 let secp_ctx = Secp256k1::new();
965 let payment_id = PaymentId([1; 32]);
967 let refund = RefundBuilder
968 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
971 assert_eq!(refund.payer_id(), node_id);
973 // Fails verification with altered fields
975 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
978 .sign(recipient_sign).unwrap();
979 match invoice.verify(&expanded_key, &secp_ctx) {
980 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
981 Err(()) => panic!("verification failed"),
984 let mut tlv_stream = refund.as_tlv_stream();
985 tlv_stream.2.amount = Some(2000);
987 let mut encoded_refund = Vec::new();
988 tlv_stream.write(&mut encoded_refund).unwrap();
990 let invoice = Refund::try_from(encoded_refund).unwrap()
991 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
994 .sign(recipient_sign).unwrap();
995 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
997 // Fails verification with altered metadata
998 let mut tlv_stream = refund.as_tlv_stream();
999 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
1000 tlv_stream.0.metadata = Some(&metadata);
1002 let mut encoded_refund = Vec::new();
1003 tlv_stream.write(&mut encoded_refund).unwrap();
1005 let invoice = Refund::try_from(encoded_refund).unwrap()
1006 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1009 .sign(recipient_sign).unwrap();
1010 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1014 fn builds_refund_with_derived_payer_id() {
1015 let desc = "foo".to_string();
1016 let node_id = payer_pubkey();
1017 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1018 let entropy = FixedEntropy {};
1019 let secp_ctx = Secp256k1::new();
1020 let payment_id = PaymentId([1; 32]);
1022 let blinded_path = BlindedPath {
1023 introduction_node_id: pubkey(40),
1024 blinding_point: pubkey(41),
1026 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1027 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1031 let refund = RefundBuilder
1032 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
1036 assert_ne!(refund.payer_id(), node_id);
1038 let invoice = refund
1039 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1042 .sign(recipient_sign).unwrap();
1043 match invoice.verify(&expanded_key, &secp_ctx) {
1044 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
1045 Err(()) => panic!("verification failed"),
1048 // Fails verification with altered fields
1049 let mut tlv_stream = refund.as_tlv_stream();
1050 tlv_stream.2.amount = Some(2000);
1052 let mut encoded_refund = Vec::new();
1053 tlv_stream.write(&mut encoded_refund).unwrap();
1055 let invoice = Refund::try_from(encoded_refund).unwrap()
1056 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1059 .sign(recipient_sign).unwrap();
1060 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1062 // Fails verification with altered payer_id
1063 let mut tlv_stream = refund.as_tlv_stream();
1064 let payer_id = pubkey(1);
1065 tlv_stream.2.payer_id = Some(&payer_id);
1067 let mut encoded_refund = Vec::new();
1068 tlv_stream.write(&mut encoded_refund).unwrap();
1070 let invoice = Refund::try_from(encoded_refund).unwrap()
1071 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1074 .sign(recipient_sign).unwrap();
1075 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1079 fn builds_refund_with_absolute_expiry() {
1080 let future_expiry = Duration::from_secs(u64::max_value());
1081 let past_expiry = Duration::from_secs(0);
1082 let now = future_expiry - Duration::from_secs(1_000);
1084 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1085 .absolute_expiry(future_expiry)
1088 let (_, tlv_stream, _) = refund.as_tlv_stream();
1089 #[cfg(feature = "std")]
1090 assert!(!refund.is_expired());
1091 assert!(!refund.is_expired_no_std(now));
1092 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1093 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1095 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1096 .absolute_expiry(future_expiry)
1097 .absolute_expiry(past_expiry)
1100 let (_, tlv_stream, _) = refund.as_tlv_stream();
1101 #[cfg(feature = "std")]
1102 assert!(refund.is_expired());
1103 assert!(refund.is_expired_no_std(now));
1104 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1105 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1109 fn builds_refund_with_paths() {
1112 introduction_node_id: pubkey(40),
1113 blinding_point: pubkey(41),
1115 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1116 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1120 introduction_node_id: pubkey(40),
1121 blinding_point: pubkey(41),
1123 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1124 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1129 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1130 .path(paths[0].clone())
1131 .path(paths[1].clone())
1134 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1135 assert_eq!(refund.paths(), paths.as_slice());
1136 assert_eq!(refund.payer_id(), pubkey(42));
1137 assert_ne!(pubkey(42), pubkey(44));
1138 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1139 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1143 fn builds_refund_with_issuer() {
1144 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1145 .issuer("bar".into())
1148 let (_, tlv_stream, _) = refund.as_tlv_stream();
1149 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1150 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1152 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1153 .issuer("bar".into())
1154 .issuer("baz".into())
1157 let (_, tlv_stream, _) = refund.as_tlv_stream();
1158 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1159 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1163 fn builds_refund_with_chain() {
1164 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1165 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1167 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1168 .chain(Network::Bitcoin)
1170 let (_, _, tlv_stream) = refund.as_tlv_stream();
1171 assert_eq!(refund.chain(), mainnet);
1172 assert_eq!(tlv_stream.chain, None);
1174 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1175 .chain(Network::Testnet)
1177 let (_, _, tlv_stream) = refund.as_tlv_stream();
1178 assert_eq!(refund.chain(), testnet);
1179 assert_eq!(tlv_stream.chain, Some(&testnet));
1181 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1182 .chain(Network::Regtest)
1183 .chain(Network::Testnet)
1185 let (_, _, tlv_stream) = refund.as_tlv_stream();
1186 assert_eq!(refund.chain(), testnet);
1187 assert_eq!(tlv_stream.chain, Some(&testnet));
1191 fn builds_refund_with_quantity() {
1192 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1195 let (_, _, tlv_stream) = refund.as_tlv_stream();
1196 assert_eq!(refund.quantity(), Some(10));
1197 assert_eq!(tlv_stream.quantity, Some(10));
1199 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1203 let (_, _, tlv_stream) = refund.as_tlv_stream();
1204 assert_eq!(refund.quantity(), Some(1));
1205 assert_eq!(tlv_stream.quantity, Some(1));
1209 fn builds_refund_with_payer_note() {
1210 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1211 .payer_note("bar".into())
1213 let (_, _, tlv_stream) = refund.as_tlv_stream();
1214 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1215 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1217 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1218 .payer_note("bar".into())
1219 .payer_note("baz".into())
1221 let (_, _, tlv_stream) = refund.as_tlv_stream();
1222 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1223 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1227 fn fails_responding_with_unknown_required_features() {
1228 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1229 .features_unchecked(InvoiceRequestFeatures::unknown())
1231 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1233 Ok(_) => panic!("expected error"),
1234 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1239 fn parses_refund_with_metadata() {
1240 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1242 if let Err(e) = refund.to_string().parse::<Refund>() {
1243 panic!("error parsing refund: {:?}", e);
1246 let mut tlv_stream = refund.as_tlv_stream();
1247 tlv_stream.0.metadata = None;
1249 match Refund::try_from(tlv_stream.to_bytes()) {
1250 Ok(_) => panic!("expected error"),
1252 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1258 fn parses_refund_with_description() {
1259 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1261 if let Err(e) = refund.to_string().parse::<Refund>() {
1262 panic!("error parsing refund: {:?}", e);
1265 let mut tlv_stream = refund.as_tlv_stream();
1266 tlv_stream.1.description = None;
1268 match Refund::try_from(tlv_stream.to_bytes()) {
1269 Ok(_) => panic!("expected error"),
1271 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1277 fn parses_refund_with_amount() {
1278 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1280 if let Err(e) = refund.to_string().parse::<Refund>() {
1281 panic!("error parsing refund: {:?}", e);
1284 let mut tlv_stream = refund.as_tlv_stream();
1285 tlv_stream.2.amount = None;
1287 match Refund::try_from(tlv_stream.to_bytes()) {
1288 Ok(_) => panic!("expected error"),
1290 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1294 let mut tlv_stream = refund.as_tlv_stream();
1295 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1297 match Refund::try_from(tlv_stream.to_bytes()) {
1298 Ok(_) => panic!("expected error"),
1300 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1306 fn parses_refund_with_payer_id() {
1307 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1309 if let Err(e) = refund.to_string().parse::<Refund>() {
1310 panic!("error parsing refund: {:?}", e);
1313 let mut tlv_stream = refund.as_tlv_stream();
1314 tlv_stream.2.payer_id = None;
1316 match Refund::try_from(tlv_stream.to_bytes()) {
1317 Ok(_) => panic!("expected error"),
1319 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1325 fn parses_refund_with_optional_fields() {
1326 let past_expiry = Duration::from_secs(0);
1329 introduction_node_id: pubkey(40),
1330 blinding_point: pubkey(41),
1332 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1333 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1337 introduction_node_id: pubkey(40),
1338 blinding_point: pubkey(41),
1340 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1341 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1346 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1347 .absolute_expiry(past_expiry)
1348 .issuer("bar".into())
1349 .path(paths[0].clone())
1350 .path(paths[1].clone())
1351 .chain(Network::Testnet)
1352 .features_unchecked(InvoiceRequestFeatures::unknown())
1354 .payer_note("baz".into())
1357 match refund.to_string().parse::<Refund>() {
1359 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1360 #[cfg(feature = "std")]
1361 assert!(refund.is_expired());
1362 assert_eq!(refund.paths(), &paths[..]);
1363 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1364 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1365 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1366 assert_eq!(refund.quantity(), Some(10));
1367 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1369 Err(e) => panic!("error parsing refund: {:?}", e),
1374 fn fails_parsing_refund_with_unexpected_fields() {
1375 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1377 if let Err(e) = refund.to_string().parse::<Refund>() {
1378 panic!("error parsing refund: {:?}", e);
1381 let metadata = vec![42; 32];
1382 let mut tlv_stream = refund.as_tlv_stream();
1383 tlv_stream.1.metadata = Some(&metadata);
1385 match Refund::try_from(tlv_stream.to_bytes()) {
1386 Ok(_) => panic!("expected error"),
1388 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1392 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1393 let mut tlv_stream = refund.as_tlv_stream();
1394 tlv_stream.1.chains = Some(&chains);
1396 match Refund::try_from(tlv_stream.to_bytes()) {
1397 Ok(_) => panic!("expected error"),
1399 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1403 let mut tlv_stream = refund.as_tlv_stream();
1404 tlv_stream.1.currency = Some(&b"USD");
1405 tlv_stream.1.amount = Some(1000);
1407 match Refund::try_from(tlv_stream.to_bytes()) {
1408 Ok(_) => panic!("expected error"),
1410 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1414 let features = OfferFeatures::unknown();
1415 let mut tlv_stream = refund.as_tlv_stream();
1416 tlv_stream.1.features = Some(&features);
1418 match Refund::try_from(tlv_stream.to_bytes()) {
1419 Ok(_) => panic!("expected error"),
1421 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1425 let mut tlv_stream = refund.as_tlv_stream();
1426 tlv_stream.1.quantity_max = Some(10);
1428 match Refund::try_from(tlv_stream.to_bytes()) {
1429 Ok(_) => panic!("expected error"),
1431 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1435 let node_id = payer_pubkey();
1436 let mut tlv_stream = refund.as_tlv_stream();
1437 tlv_stream.1.node_id = Some(&node_id);
1439 match Refund::try_from(tlv_stream.to_bytes()) {
1440 Ok(_) => panic!("expected error"),
1442 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1448 fn fails_parsing_refund_with_extra_tlv_records() {
1449 let secp_ctx = Secp256k1::new();
1450 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1451 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1454 let mut encoded_refund = Vec::new();
1455 refund.write(&mut encoded_refund).unwrap();
1456 BigSize(1002).write(&mut encoded_refund).unwrap();
1457 BigSize(32).write(&mut encoded_refund).unwrap();
1458 [42u8; 32].write(&mut encoded_refund).unwrap();
1460 match Refund::try_from(encoded_refund) {
1461 Ok(_) => panic!("expected error"),
1462 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),