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 macro_rules! refund_without_secp256k1_builder_methods { () => {
128 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
129 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
131 /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
132 /// [`Refund::amount_msats`].
136 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
137 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
139 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
140 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
142 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
143 ) -> Result<Self, Bolt12SemanticError> {
144 if amount_msats > MAX_VALUE_MSAT {
145 return Err(Bolt12SemanticError::InvalidAmount);
148 let metadata = Metadata::Bytes(metadata);
150 refund: RefundContents {
151 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
152 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
153 quantity: None, payer_id, payer_note: None,
160 macro_rules! refund_builder_methods { (
161 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
163 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
164 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
165 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
166 /// provided `node_id` is used for the payer id.
168 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
169 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
171 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
172 /// one invoice will be paid for the refund and that payments can be uniquely identified.
174 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
175 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
176 pub fn deriving_payer_id<ES: Deref>(
177 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
178 secp_ctx: &'a Secp256k1<T>, amount_msats: u64, payment_id: PaymentId
179 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
180 if amount_msats > MAX_VALUE_MSAT {
181 return Err(Bolt12SemanticError::InvalidAmount);
184 let nonce = Nonce::from_entropy_source(entropy_source);
185 let payment_id = Some(payment_id);
186 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
187 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
189 refund: RefundContents {
190 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
191 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
192 quantity: None, payer_id: node_id, payer_note: None,
194 secp_ctx: Some(secp_ctx),
198 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
199 /// already passed is valid and can be checked for using [`Refund::is_expired`].
201 /// Successive calls to this method will override the previous setting.
202 pub fn absolute_expiry(mut $self: $self_type, absolute_expiry: Duration) -> $return_type {
203 $self.refund.absolute_expiry = Some(absolute_expiry);
207 /// Sets the [`Refund::issuer`].
209 /// Successive calls to this method will override the previous setting.
210 pub fn issuer(mut $self: $self_type, issuer: String) -> $return_type {
211 $self.refund.issuer = Some(issuer);
215 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
216 /// by private channels or if [`Refund::payer_id`] is not a public node id.
218 /// Successive calls to this method will add another blinded path. Caller is responsible for not
219 /// adding duplicate paths.
220 pub fn path(mut $self: $self_type, path: BlindedPath) -> $return_type {
221 $self.refund.paths.get_or_insert_with(Vec::new).push(path);
225 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
226 /// called, [`Network::Bitcoin`] is assumed.
228 /// Successive calls to this method will override the previous setting.
229 pub fn chain($self: $self_type, network: Network) -> $return_type {
230 $self.chain_hash(ChainHash::using_genesis_block(network))
233 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
234 /// [`Network::Bitcoin`] is assumed.
236 /// Successive calls to this method will override the previous setting.
237 pub(crate) fn chain_hash(mut $self: $self_type, chain: ChainHash) -> $return_type {
238 $self.refund.chain = Some(chain);
242 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
243 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
244 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
246 /// Successive calls to this method will override the previous setting.
248 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
249 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
250 /// [`Offer`]: crate::offers::offer::Offer
251 pub fn quantity(mut $self: $self_type, quantity: u64) -> $return_type {
252 $self.refund.quantity = Some(quantity);
256 /// Sets the [`Refund::payer_note`].
258 /// Successive calls to this method will override the previous setting.
259 pub fn payer_note(mut $self: $self_type, payer_note: String) -> $return_type {
260 $self.refund.payer_note = Some(payer_note);
264 /// Builds a [`Refund`] after checking for valid semantics.
265 pub fn build(mut $self: $self_type) -> Result<Refund, Bolt12SemanticError> {
266 if $self.refund.chain() == $self.refund.implied_chain() {
267 $self.refund.chain = None;
270 // Create the metadata for stateless verification of a Bolt12Invoice.
271 if $self.refund.payer.0.has_derivation_material() {
272 let mut metadata = core::mem::take(&mut $self.refund.payer.0);
274 if $self.refund.paths.is_none() {
275 metadata = metadata.without_keys();
278 let mut tlv_stream = $self.refund.as_tlv_stream();
279 tlv_stream.0.metadata = None;
280 if metadata.derives_payer_keys() {
281 tlv_stream.2.payer_id = None;
284 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
285 metadata = derived_metadata;
286 if let Some(keys) = keys {
287 $self.refund.payer_id = keys.public_key();
290 $self.refund.payer.0 = metadata;
293 let mut bytes = Vec::new();
294 $self.refund.write(&mut bytes).unwrap();
296 Ok(Refund { bytes, contents: $self.refund })
301 macro_rules! refund_builder_test_methods { (
302 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
304 pub(crate) fn clear_paths(mut $self: $self_type) -> $return_type {
305 $self.refund.paths = None;
309 fn features_unchecked(mut $self: $self_type, features: InvoiceRequestFeatures) -> $return_type {
310 $self.refund.features = features;
315 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
316 refund_without_secp256k1_builder_methods!();
319 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
320 refund_builder_methods!(self, Self, Self, self);
323 refund_builder_test_methods!(self, Self, Self, self);
326 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
328 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
329 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
332 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
333 /// [`Offer`]: crate::offers::offer::Offer
334 #[derive(Clone, Debug)]
335 #[cfg_attr(test, derive(PartialEq))]
337 pub(super) bytes: Vec<u8>,
338 pub(super) contents: RefundContents,
341 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
343 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
344 #[derive(Clone, Debug)]
345 #[cfg_attr(test, derive(PartialEq))]
346 pub(super) struct RefundContents {
347 payer: PayerContents,
350 absolute_expiry: Option<Duration>,
351 issuer: Option<String>,
352 paths: Option<Vec<BlindedPath>>,
353 // invoice_request fields
354 chain: Option<ChainHash>,
356 features: InvoiceRequestFeatures,
357 quantity: Option<u64>,
359 payer_note: Option<String>,
363 /// A complete description of the purpose of the refund. Intended to be displayed to the user
364 /// but with the caveat that it has not been verified in any way.
365 pub fn description(&self) -> PrintableString {
366 self.contents.description()
369 /// Duration since the Unix epoch when an invoice should no longer be sent.
371 /// If `None`, the refund does not expire.
372 pub fn absolute_expiry(&self) -> Option<Duration> {
373 self.contents.absolute_expiry()
376 /// Whether the refund has expired.
377 #[cfg(feature = "std")]
378 pub fn is_expired(&self) -> bool {
379 self.contents.is_expired()
382 /// Whether the refund has expired given the duration since the Unix epoch.
383 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
384 self.contents.is_expired_no_std(duration_since_epoch)
387 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
388 /// displayed to the user but with the caveat that it has not been verified in any way.
389 pub fn issuer(&self) -> Option<PrintableString> {
390 self.contents.issuer()
393 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
394 /// privacy by obfuscating its node id.
395 pub fn paths(&self) -> &[BlindedPath] {
396 self.contents.paths()
399 /// An unpredictable series of bytes, typically containing information about the derivation of
402 /// [`payer_id`]: Self::payer_id
403 pub fn payer_metadata(&self) -> &[u8] {
404 self.contents.metadata()
407 /// A chain that the refund is valid for.
408 pub fn chain(&self) -> ChainHash {
409 self.contents.chain()
412 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
414 /// [`chain`]: Self::chain
415 pub fn amount_msats(&self) -> u64 {
416 self.contents.amount_msats()
419 /// Features pertaining to requesting an invoice.
420 pub fn features(&self) -> &InvoiceRequestFeatures {
421 &self.contents.features()
424 /// The quantity of an item that refund is for.
425 pub fn quantity(&self) -> Option<u64> {
426 self.contents.quantity()
429 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
430 /// transient pubkey.
432 /// [`paths`]: Self::paths
433 pub fn payer_id(&self) -> PublicKey {
434 self.contents.payer_id()
437 /// Payer provided note to include in the invoice.
438 pub fn payer_note(&self) -> Option<PrintableString> {
439 self.contents.payer_note()
442 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
443 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
445 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
446 /// time is used for the `created_at` parameter.
448 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
450 /// [`Duration`]: core::time::Duration
451 #[cfg(feature = "std")]
453 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
454 signing_pubkey: PublicKey,
455 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
456 let created_at = std::time::SystemTime::now()
457 .duration_since(std::time::SystemTime::UNIX_EPOCH)
458 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
460 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
463 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
465 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
466 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
467 /// where [`std::time::SystemTime`] is not available.
469 /// The caller is expected to remember the preimage of `payment_hash` in order to
470 /// claim a payment for the invoice.
472 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
473 /// offer, which does have a `signing_pubkey`.
475 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
476 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
477 /// a preference. Note, however, that any privacy is lost if a public node id is used for
478 /// `signing_pubkey`.
480 /// Errors if the request contains unknown required features.
482 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
484 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
485 pub fn respond_with_no_std(
486 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
487 signing_pubkey: PublicKey, created_at: Duration
488 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
489 if self.features().requires_unknown_bits() {
490 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
493 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
496 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
497 /// derived signing keys to sign the [`Bolt12Invoice`].
499 /// See [`Refund::respond_with`] for further details.
501 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
503 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
504 #[cfg(feature = "std")]
505 pub fn respond_using_derived_keys<ES: Deref>(
506 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
507 expanded_key: &ExpandedKey, entropy_source: ES
508 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
510 ES::Target: EntropySource,
512 let created_at = std::time::SystemTime::now()
513 .duration_since(std::time::SystemTime::UNIX_EPOCH)
514 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
516 self.respond_using_derived_keys_no_std(
517 payment_paths, payment_hash, created_at, expanded_key, entropy_source
521 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
522 /// derived signing keys to sign the [`Bolt12Invoice`].
524 /// See [`Refund::respond_with_no_std`] for further details.
526 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
528 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
529 pub fn respond_using_derived_keys_no_std<ES: Deref>(
530 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
531 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
532 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
534 ES::Target: EntropySource,
536 if self.features().requires_unknown_bits() {
537 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
540 let nonce = Nonce::from_entropy_source(entropy_source);
541 let keys = signer::derive_keys(nonce, expanded_key);
542 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
546 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
547 self.contents.as_tlv_stream()
551 impl AsRef<[u8]> for Refund {
552 fn as_ref(&self) -> &[u8] {
557 impl RefundContents {
558 pub fn description(&self) -> PrintableString {
559 PrintableString(&self.description)
562 pub fn absolute_expiry(&self) -> Option<Duration> {
566 #[cfg(feature = "std")]
567 pub(super) fn is_expired(&self) -> bool {
568 SystemTime::UNIX_EPOCH
570 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
574 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
576 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
580 pub fn issuer(&self) -> Option<PrintableString> {
581 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
584 pub fn paths(&self) -> &[BlindedPath] {
585 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
588 pub(super) fn metadata(&self) -> &[u8] {
589 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
592 pub(super) fn chain(&self) -> ChainHash {
593 self.chain.unwrap_or_else(|| self.implied_chain())
596 pub fn implied_chain(&self) -> ChainHash {
597 ChainHash::using_genesis_block(Network::Bitcoin)
600 pub fn amount_msats(&self) -> u64 {
604 /// Features pertaining to requesting an invoice.
605 pub fn features(&self) -> &InvoiceRequestFeatures {
609 /// The quantity of an item that refund is for.
610 pub fn quantity(&self) -> Option<u64> {
614 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
615 /// transient pubkey.
617 /// [`paths`]: Self::paths
618 pub fn payer_id(&self) -> PublicKey {
622 /// Payer provided note to include in the invoice.
623 pub fn payer_note(&self) -> Option<PrintableString> {
624 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
627 pub(super) fn derives_keys(&self) -> bool {
628 self.payer.0.derives_payer_keys()
631 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
632 let payer = PayerTlvStreamRef {
633 metadata: self.payer.0.as_bytes(),
636 let offer = OfferTlvStreamRef {
641 description: Some(&self.description),
643 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
644 paths: self.paths.as_ref(),
645 issuer: self.issuer.as_ref(),
651 if self.features == InvoiceRequestFeatures::empty() { None }
652 else { Some(&self.features) }
655 let invoice_request = InvoiceRequestTlvStreamRef {
656 chain: self.chain.as_ref(),
657 amount: Some(self.amount_msats),
659 quantity: self.quantity,
660 payer_id: Some(&self.payer_id),
661 payer_note: self.payer_note.as_ref(),
664 (payer, offer, invoice_request)
668 impl Writeable for Refund {
669 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
670 WithoutLength(&self.bytes).write(writer)
674 impl Writeable for RefundContents {
675 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
676 self.as_tlv_stream().write(writer)
680 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
682 type RefundTlvStreamRef<'a> = (
683 PayerTlvStreamRef<'a>,
684 OfferTlvStreamRef<'a>,
685 InvoiceRequestTlvStreamRef<'a>,
688 impl SeekReadable for RefundTlvStream {
689 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
690 let payer = SeekReadable::read(r)?;
691 let offer = SeekReadable::read(r)?;
692 let invoice_request = SeekReadable::read(r)?;
694 Ok((payer, offer, invoice_request))
698 impl Bech32Encode for Refund {
699 const BECH32_HRP: &'static str = "lnr";
702 impl FromStr for Refund {
703 type Err = Bolt12ParseError;
705 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
706 Refund::from_bech32_str(s)
710 impl TryFrom<Vec<u8>> for Refund {
711 type Error = Bolt12ParseError;
713 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
714 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
715 let ParsedMessage { bytes, tlv_stream } = refund;
716 let contents = RefundContents::try_from(tlv_stream)?;
718 Ok(Refund { bytes, contents })
722 impl TryFrom<RefundTlvStream> for RefundContents {
723 type Error = Bolt12SemanticError;
725 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
727 PayerTlvStream { metadata: payer_metadata },
729 chains, metadata, currency, amount: offer_amount, description,
730 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
732 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
735 let payer = match payer_metadata {
736 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
737 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
740 if metadata.is_some() {
741 return Err(Bolt12SemanticError::UnexpectedMetadata);
744 if chains.is_some() {
745 return Err(Bolt12SemanticError::UnexpectedChain);
748 if currency.is_some() || offer_amount.is_some() {
749 return Err(Bolt12SemanticError::UnexpectedAmount);
752 let description = match description {
753 None => return Err(Bolt12SemanticError::MissingDescription),
754 Some(description) => description,
757 if offer_features.is_some() {
758 return Err(Bolt12SemanticError::UnexpectedFeatures);
761 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
763 if quantity_max.is_some() {
764 return Err(Bolt12SemanticError::UnexpectedQuantity);
767 if node_id.is_some() {
768 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
771 let amount_msats = match amount {
772 None => return Err(Bolt12SemanticError::MissingAmount),
773 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
774 return Err(Bolt12SemanticError::InvalidAmount);
776 Some(amount_msats) => amount_msats,
779 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
781 let payer_id = match payer_id {
782 None => return Err(Bolt12SemanticError::MissingPayerId),
783 Some(payer_id) => payer_id,
787 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
788 quantity, payer_id, payer_note,
793 impl core::fmt::Display for Refund {
794 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
795 self.fmt_bech32_str(f)
801 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
803 use bitcoin::blockdata::constants::ChainHash;
804 use bitcoin::network::constants::Network;
805 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
806 use core::convert::TryFrom;
807 use core::time::Duration;
808 use crate::blinded_path::{BlindedHop, BlindedPath};
809 use crate::sign::KeyMaterial;
810 use crate::ln::channelmanager::PaymentId;
811 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
812 use crate::ln::inbound_payment::ExpandedKey;
813 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
814 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
815 use crate::offers::offer::OfferTlvStreamRef;
816 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
817 use crate::offers::payer::PayerTlvStreamRef;
818 use crate::offers::test_utils::*;
819 use crate::util::ser::{BigSize, Writeable};
820 use crate::util::string::PrintableString;
823 fn to_bytes(&self) -> Vec<u8>;
826 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
827 fn to_bytes(&self) -> Vec<u8> {
828 let mut buffer = Vec::new();
829 self.write(&mut buffer).unwrap();
835 fn builds_refund_with_defaults() {
836 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
839 let mut buffer = Vec::new();
840 refund.write(&mut buffer).unwrap();
842 assert_eq!(refund.bytes, buffer.as_slice());
843 assert_eq!(refund.payer_metadata(), &[1; 32]);
844 assert_eq!(refund.description(), PrintableString("foo"));
845 assert_eq!(refund.absolute_expiry(), None);
846 #[cfg(feature = "std")]
847 assert!(!refund.is_expired());
848 assert_eq!(refund.paths(), &[]);
849 assert_eq!(refund.issuer(), None);
850 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
851 assert_eq!(refund.amount_msats(), 1000);
852 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
853 assert_eq!(refund.payer_id(), payer_pubkey());
854 assert_eq!(refund.payer_note(), None);
857 refund.as_tlv_stream(),
859 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
865 description: Some(&String::from("foo")),
867 absolute_expiry: None,
873 InvoiceRequestTlvStreamRef {
878 payer_id: Some(&payer_pubkey()),
884 if let Err(e) = Refund::try_from(buffer) {
885 panic!("error parsing refund: {:?}", e);
890 fn fails_building_refund_with_invalid_amount() {
891 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
892 Ok(_) => panic!("expected error"),
893 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
898 fn builds_refund_with_metadata_derived() {
899 let desc = "foo".to_string();
900 let node_id = payer_pubkey();
901 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
902 let entropy = FixedEntropy {};
903 let secp_ctx = Secp256k1::new();
904 let payment_id = PaymentId([1; 32]);
906 let refund = RefundBuilder
907 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
910 assert_eq!(refund.payer_id(), node_id);
912 // Fails verification with altered fields
914 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
917 .sign(recipient_sign).unwrap();
918 match invoice.verify(&expanded_key, &secp_ctx) {
919 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
920 Err(()) => panic!("verification failed"),
923 let mut tlv_stream = refund.as_tlv_stream();
924 tlv_stream.2.amount = Some(2000);
926 let mut encoded_refund = Vec::new();
927 tlv_stream.write(&mut encoded_refund).unwrap();
929 let invoice = Refund::try_from(encoded_refund).unwrap()
930 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
933 .sign(recipient_sign).unwrap();
934 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
936 // Fails verification with altered metadata
937 let mut tlv_stream = refund.as_tlv_stream();
938 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
939 tlv_stream.0.metadata = Some(&metadata);
941 let mut encoded_refund = Vec::new();
942 tlv_stream.write(&mut encoded_refund).unwrap();
944 let invoice = Refund::try_from(encoded_refund).unwrap()
945 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
948 .sign(recipient_sign).unwrap();
949 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
953 fn builds_refund_with_derived_payer_id() {
954 let desc = "foo".to_string();
955 let node_id = payer_pubkey();
956 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
957 let entropy = FixedEntropy {};
958 let secp_ctx = Secp256k1::new();
959 let payment_id = PaymentId([1; 32]);
961 let blinded_path = BlindedPath {
962 introduction_node_id: pubkey(40),
963 blinding_point: pubkey(41),
965 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
966 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
970 let refund = RefundBuilder
971 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
975 assert_ne!(refund.payer_id(), node_id);
978 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
981 .sign(recipient_sign).unwrap();
982 match invoice.verify(&expanded_key, &secp_ctx) {
983 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
984 Err(()) => panic!("verification failed"),
987 // Fails verification with altered fields
988 let mut tlv_stream = refund.as_tlv_stream();
989 tlv_stream.2.amount = Some(2000);
991 let mut encoded_refund = Vec::new();
992 tlv_stream.write(&mut encoded_refund).unwrap();
994 let invoice = Refund::try_from(encoded_refund).unwrap()
995 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
998 .sign(recipient_sign).unwrap();
999 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1001 // Fails verification with altered payer_id
1002 let mut tlv_stream = refund.as_tlv_stream();
1003 let payer_id = pubkey(1);
1004 tlv_stream.2.payer_id = Some(&payer_id);
1006 let mut encoded_refund = Vec::new();
1007 tlv_stream.write(&mut encoded_refund).unwrap();
1009 let invoice = Refund::try_from(encoded_refund).unwrap()
1010 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1013 .sign(recipient_sign).unwrap();
1014 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1018 fn builds_refund_with_absolute_expiry() {
1019 let future_expiry = Duration::from_secs(u64::max_value());
1020 let past_expiry = Duration::from_secs(0);
1021 let now = future_expiry - Duration::from_secs(1_000);
1023 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1024 .absolute_expiry(future_expiry)
1027 let (_, tlv_stream, _) = refund.as_tlv_stream();
1028 #[cfg(feature = "std")]
1029 assert!(!refund.is_expired());
1030 assert!(!refund.is_expired_no_std(now));
1031 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1032 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1034 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1035 .absolute_expiry(future_expiry)
1036 .absolute_expiry(past_expiry)
1039 let (_, tlv_stream, _) = refund.as_tlv_stream();
1040 #[cfg(feature = "std")]
1041 assert!(refund.is_expired());
1042 assert!(refund.is_expired_no_std(now));
1043 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1044 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1048 fn builds_refund_with_paths() {
1051 introduction_node_id: pubkey(40),
1052 blinding_point: pubkey(41),
1054 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1055 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1059 introduction_node_id: pubkey(40),
1060 blinding_point: pubkey(41),
1062 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1063 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1068 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1069 .path(paths[0].clone())
1070 .path(paths[1].clone())
1073 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1074 assert_eq!(refund.paths(), paths.as_slice());
1075 assert_eq!(refund.payer_id(), pubkey(42));
1076 assert_ne!(pubkey(42), pubkey(44));
1077 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1078 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1082 fn builds_refund_with_issuer() {
1083 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1084 .issuer("bar".into())
1087 let (_, tlv_stream, _) = refund.as_tlv_stream();
1088 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1089 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1091 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1092 .issuer("bar".into())
1093 .issuer("baz".into())
1096 let (_, tlv_stream, _) = refund.as_tlv_stream();
1097 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1098 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1102 fn builds_refund_with_chain() {
1103 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1104 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1106 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1107 .chain(Network::Bitcoin)
1109 let (_, _, tlv_stream) = refund.as_tlv_stream();
1110 assert_eq!(refund.chain(), mainnet);
1111 assert_eq!(tlv_stream.chain, None);
1113 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1114 .chain(Network::Testnet)
1116 let (_, _, tlv_stream) = refund.as_tlv_stream();
1117 assert_eq!(refund.chain(), testnet);
1118 assert_eq!(tlv_stream.chain, Some(&testnet));
1120 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1121 .chain(Network::Regtest)
1122 .chain(Network::Testnet)
1124 let (_, _, tlv_stream) = refund.as_tlv_stream();
1125 assert_eq!(refund.chain(), testnet);
1126 assert_eq!(tlv_stream.chain, Some(&testnet));
1130 fn builds_refund_with_quantity() {
1131 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1134 let (_, _, tlv_stream) = refund.as_tlv_stream();
1135 assert_eq!(refund.quantity(), Some(10));
1136 assert_eq!(tlv_stream.quantity, Some(10));
1138 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1142 let (_, _, tlv_stream) = refund.as_tlv_stream();
1143 assert_eq!(refund.quantity(), Some(1));
1144 assert_eq!(tlv_stream.quantity, Some(1));
1148 fn builds_refund_with_payer_note() {
1149 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1150 .payer_note("bar".into())
1152 let (_, _, tlv_stream) = refund.as_tlv_stream();
1153 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1154 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1156 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1157 .payer_note("bar".into())
1158 .payer_note("baz".into())
1160 let (_, _, tlv_stream) = refund.as_tlv_stream();
1161 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1162 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1166 fn fails_responding_with_unknown_required_features() {
1167 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1168 .features_unchecked(InvoiceRequestFeatures::unknown())
1170 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1172 Ok(_) => panic!("expected error"),
1173 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1178 fn parses_refund_with_metadata() {
1179 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1181 if let Err(e) = refund.to_string().parse::<Refund>() {
1182 panic!("error parsing refund: {:?}", e);
1185 let mut tlv_stream = refund.as_tlv_stream();
1186 tlv_stream.0.metadata = None;
1188 match Refund::try_from(tlv_stream.to_bytes()) {
1189 Ok(_) => panic!("expected error"),
1191 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1197 fn parses_refund_with_description() {
1198 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1200 if let Err(e) = refund.to_string().parse::<Refund>() {
1201 panic!("error parsing refund: {:?}", e);
1204 let mut tlv_stream = refund.as_tlv_stream();
1205 tlv_stream.1.description = None;
1207 match Refund::try_from(tlv_stream.to_bytes()) {
1208 Ok(_) => panic!("expected error"),
1210 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1216 fn parses_refund_with_amount() {
1217 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1219 if let Err(e) = refund.to_string().parse::<Refund>() {
1220 panic!("error parsing refund: {:?}", e);
1223 let mut tlv_stream = refund.as_tlv_stream();
1224 tlv_stream.2.amount = None;
1226 match Refund::try_from(tlv_stream.to_bytes()) {
1227 Ok(_) => panic!("expected error"),
1229 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1233 let mut tlv_stream = refund.as_tlv_stream();
1234 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1236 match Refund::try_from(tlv_stream.to_bytes()) {
1237 Ok(_) => panic!("expected error"),
1239 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1245 fn parses_refund_with_payer_id() {
1246 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1248 if let Err(e) = refund.to_string().parse::<Refund>() {
1249 panic!("error parsing refund: {:?}", e);
1252 let mut tlv_stream = refund.as_tlv_stream();
1253 tlv_stream.2.payer_id = None;
1255 match Refund::try_from(tlv_stream.to_bytes()) {
1256 Ok(_) => panic!("expected error"),
1258 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1264 fn parses_refund_with_optional_fields() {
1265 let past_expiry = Duration::from_secs(0);
1268 introduction_node_id: pubkey(40),
1269 blinding_point: pubkey(41),
1271 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1272 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1276 introduction_node_id: pubkey(40),
1277 blinding_point: pubkey(41),
1279 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1280 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1285 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1286 .absolute_expiry(past_expiry)
1287 .issuer("bar".into())
1288 .path(paths[0].clone())
1289 .path(paths[1].clone())
1290 .chain(Network::Testnet)
1291 .features_unchecked(InvoiceRequestFeatures::unknown())
1293 .payer_note("baz".into())
1296 match refund.to_string().parse::<Refund>() {
1298 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1299 #[cfg(feature = "std")]
1300 assert!(refund.is_expired());
1301 assert_eq!(refund.paths(), &paths[..]);
1302 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1303 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1304 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1305 assert_eq!(refund.quantity(), Some(10));
1306 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1308 Err(e) => panic!("error parsing refund: {:?}", e),
1313 fn fails_parsing_refund_with_unexpected_fields() {
1314 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1316 if let Err(e) = refund.to_string().parse::<Refund>() {
1317 panic!("error parsing refund: {:?}", e);
1320 let metadata = vec![42; 32];
1321 let mut tlv_stream = refund.as_tlv_stream();
1322 tlv_stream.1.metadata = Some(&metadata);
1324 match Refund::try_from(tlv_stream.to_bytes()) {
1325 Ok(_) => panic!("expected error"),
1327 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1331 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1332 let mut tlv_stream = refund.as_tlv_stream();
1333 tlv_stream.1.chains = Some(&chains);
1335 match Refund::try_from(tlv_stream.to_bytes()) {
1336 Ok(_) => panic!("expected error"),
1338 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1342 let mut tlv_stream = refund.as_tlv_stream();
1343 tlv_stream.1.currency = Some(&b"USD");
1344 tlv_stream.1.amount = Some(1000);
1346 match Refund::try_from(tlv_stream.to_bytes()) {
1347 Ok(_) => panic!("expected error"),
1349 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1353 let features = OfferFeatures::unknown();
1354 let mut tlv_stream = refund.as_tlv_stream();
1355 tlv_stream.1.features = Some(&features);
1357 match Refund::try_from(tlv_stream.to_bytes()) {
1358 Ok(_) => panic!("expected error"),
1360 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1364 let mut tlv_stream = refund.as_tlv_stream();
1365 tlv_stream.1.quantity_max = Some(10);
1367 match Refund::try_from(tlv_stream.to_bytes()) {
1368 Ok(_) => panic!("expected error"),
1370 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1374 let node_id = payer_pubkey();
1375 let mut tlv_stream = refund.as_tlv_stream();
1376 tlv_stream.1.node_id = Some(&node_id);
1378 match Refund::try_from(tlv_stream.to_bytes()) {
1379 Ok(_) => panic!("expected error"),
1381 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1387 fn fails_parsing_refund_with_extra_tlv_records() {
1388 let secp_ctx = Secp256k1::new();
1389 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1390 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1393 let mut encoded_refund = Vec::new();
1394 refund.write(&mut encoded_refund).unwrap();
1395 BigSize(1002).write(&mut encoded_refund).unwrap();
1396 BigSize(32).write(&mut encoded_refund).unwrap();
1397 [42u8; 32].write(&mut encoded_refund).unwrap();
1399 match Refund::try_from(encoded_refund) {
1400 Ok(_) => panic!("expected error"),
1401 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),