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
22 //! extern crate bitcoin;
23 //! extern crate core;
24 //! extern crate lightning;
26 //! use core::convert::TryFrom;
27 //! use core::time::Duration;
29 //! use bitcoin::network::constants::Network;
30 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
31 //! use lightning::offers::parse::Bolt12ParseError;
32 //! use lightning::offers::refund::{Refund, RefundBuilder};
33 //! use lightning::util::ser::{Readable, Writeable};
35 //! # use lightning::blinded_path::BlindedPath;
36 //! # #[cfg(feature = "std")]
37 //! # use std::time::SystemTime;
39 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
40 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
42 //! # #[cfg(feature = "std")]
43 //! # fn build() -> Result<(), Bolt12ParseError> {
44 //! let secp_ctx = Secp256k1::new();
45 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
46 //! let pubkey = PublicKey::from(keys);
48 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
49 //! let refund = RefundBuilder::new("coffee, large".to_string(), vec![1; 32], pubkey, 20_000)?
50 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
51 //! .issuer("Foo Bar".to_string())
52 //! .path(create_blinded_path())
53 //! .path(create_another_blinded_path())
54 //! .chain(Network::Bitcoin)
55 //! .payer_note("refund for order #12345".to_string())
58 //! // Encode as a bech32 string for use in a QR code.
59 //! let encoded_refund = refund.to_string();
61 //! // Parse from a bech32 string after scanning from a QR code.
62 //! let refund = encoded_refund.parse::<Refund>()?;
64 //! // Encode refund as raw bytes.
65 //! let mut bytes = Vec::new();
66 //! refund.write(&mut bytes).unwrap();
68 //! // Decode raw bytes into an refund.
69 //! let refund = Refund::try_from(bytes)?;
74 use bitcoin::blockdata::constants::ChainHash;
75 use bitcoin::network::constants::Network;
76 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
77 use core::convert::TryFrom;
79 use core::str::FromStr;
80 use core::time::Duration;
81 use crate::sign::EntropySource;
83 use crate::blinded_path::BlindedPath;
84 use crate::ln::PaymentHash;
85 use crate::ln::channelmanager::PaymentId;
86 use crate::ln::features::InvoiceRequestFeatures;
87 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
88 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
89 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
90 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
91 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
92 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
93 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
94 use crate::offers::signer::{Metadata, MetadataMaterial, self};
95 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
96 use crate::util::string::PrintableString;
98 use crate::prelude::*;
100 #[cfg(feature = "std")]
101 use std::time::SystemTime;
103 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
105 /// Builds a [`Refund`] for the "offer for money" flow.
107 /// See [module-level documentation] for usage.
109 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
111 /// [module-level documentation]: self
112 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
113 refund: RefundContents,
114 secp_ctx: Option<&'a Secp256k1<T>>,
117 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
118 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
119 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
121 /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
122 /// [`Refund::amount_msats`].
124 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
125 ) -> Result<Self, Bolt12SemanticError> {
126 if amount_msats > MAX_VALUE_MSAT {
127 return Err(Bolt12SemanticError::InvalidAmount);
130 let metadata = Metadata::Bytes(metadata);
132 refund: RefundContents {
133 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
134 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
135 quantity: None, payer_id, payer_note: None,
142 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
143 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
144 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
145 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
146 /// provided `node_id` is used for the payer id.
148 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
149 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
151 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
152 /// one invoice will be paid for the refund and that payments can be uniquely identified.
154 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
155 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
156 pub fn deriving_payer_id<ES: Deref>(
157 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
158 secp_ctx: &'a Secp256k1<T>, amount_msats: u64, payment_id: PaymentId
159 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
160 if amount_msats > MAX_VALUE_MSAT {
161 return Err(Bolt12SemanticError::InvalidAmount);
164 let nonce = Nonce::from_entropy_source(entropy_source);
165 let payment_id = Some(payment_id);
166 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
167 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
169 refund: RefundContents {
170 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
171 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
172 quantity: None, payer_id: node_id, payer_note: None,
174 secp_ctx: Some(secp_ctx),
178 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
179 /// already passed is valid and can be checked for using [`Refund::is_expired`].
181 /// Successive calls to this method will override the previous setting.
182 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
183 self.refund.absolute_expiry = Some(absolute_expiry);
187 /// Sets the [`Refund::issuer`].
189 /// Successive calls to this method will override the previous setting.
190 pub fn issuer(mut self, issuer: String) -> Self {
191 self.refund.issuer = Some(issuer);
195 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
196 /// by private channels or if [`Refund::payer_id`] is not a public node id.
198 /// Successive calls to this method will add another blinded path. Caller is responsible for not
199 /// adding duplicate paths.
200 pub fn path(mut self, path: BlindedPath) -> Self {
201 self.refund.paths.get_or_insert_with(Vec::new).push(path);
205 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
206 /// called, [`Network::Bitcoin`] is assumed.
208 /// Successive calls to this method will override the previous setting.
209 pub fn chain(mut self, network: Network) -> Self {
210 self.refund.chain = Some(ChainHash::using_genesis_block(network));
214 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
215 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
216 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
218 /// Successive calls to this method will override the previous setting.
220 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
221 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
222 /// [`Offer`]: crate::offers::offer::Offer
223 pub fn quantity(mut self, quantity: u64) -> Self {
224 self.refund.quantity = Some(quantity);
228 /// Sets the [`Refund::payer_note`].
230 /// Successive calls to this method will override the previous setting.
231 pub fn payer_note(mut self, payer_note: String) -> Self {
232 self.refund.payer_note = Some(payer_note);
236 /// Builds a [`Refund`] after checking for valid semantics.
237 pub fn build(mut self) -> Result<Refund, Bolt12SemanticError> {
238 if self.refund.chain() == self.refund.implied_chain() {
239 self.refund.chain = None;
242 // Create the metadata for stateless verification of a Bolt12Invoice.
243 if self.refund.payer.0.has_derivation_material() {
244 let mut metadata = core::mem::take(&mut self.refund.payer.0);
246 if self.refund.paths.is_none() {
247 metadata = metadata.without_keys();
250 let mut tlv_stream = self.refund.as_tlv_stream();
251 tlv_stream.0.metadata = None;
252 if metadata.derives_payer_keys() {
253 tlv_stream.2.payer_id = None;
256 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
257 metadata = derived_metadata;
258 if let Some(keys) = keys {
259 self.refund.payer_id = keys.public_key();
262 self.refund.payer.0 = metadata;
265 let mut bytes = Vec::new();
266 self.refund.write(&mut bytes).unwrap();
268 Ok(Refund { bytes, contents: self.refund })
273 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
274 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
275 self.refund.features = features;
280 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
282 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
283 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
286 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
287 /// [`Offer`]: crate::offers::offer::Offer
288 #[derive(Clone, Debug)]
289 #[cfg_attr(test, derive(PartialEq))]
291 pub(super) bytes: Vec<u8>,
292 pub(super) contents: RefundContents,
295 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
297 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
298 #[derive(Clone, Debug)]
299 #[cfg_attr(test, derive(PartialEq))]
300 pub(super) struct RefundContents {
301 payer: PayerContents,
304 absolute_expiry: Option<Duration>,
305 issuer: Option<String>,
306 paths: Option<Vec<BlindedPath>>,
307 // invoice_request fields
308 chain: Option<ChainHash>,
310 features: InvoiceRequestFeatures,
311 quantity: Option<u64>,
313 payer_note: Option<String>,
317 /// A complete description of the purpose of the refund. Intended to be displayed to the user
318 /// but with the caveat that it has not been verified in any way.
319 pub fn description(&self) -> PrintableString {
320 self.contents.description()
323 /// Duration since the Unix epoch when an invoice should no longer be sent.
325 /// If `None`, the refund does not expire.
326 pub fn absolute_expiry(&self) -> Option<Duration> {
327 self.contents.absolute_expiry()
330 /// Whether the refund has expired.
331 #[cfg(feature = "std")]
332 pub fn is_expired(&self) -> bool {
333 self.contents.is_expired()
336 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
337 /// displayed to the user but with the caveat that it has not been verified in any way.
338 pub fn issuer(&self) -> Option<PrintableString> {
339 self.contents.issuer()
342 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
343 /// privacy by obfuscating its node id.
344 pub fn paths(&self) -> &[BlindedPath] {
345 self.contents.paths()
348 /// An unpredictable series of bytes, typically containing information about the derivation of
351 /// [`payer_id`]: Self::payer_id
352 pub fn payer_metadata(&self) -> &[u8] {
353 self.contents.metadata()
356 /// A chain that the refund is valid for.
357 pub fn chain(&self) -> ChainHash {
358 self.contents.chain()
361 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
363 /// [`chain`]: Self::chain
364 pub fn amount_msats(&self) -> u64 {
365 self.contents.amount_msats()
368 /// Features pertaining to requesting an invoice.
369 pub fn features(&self) -> &InvoiceRequestFeatures {
370 &self.contents.features()
373 /// The quantity of an item that refund is for.
374 pub fn quantity(&self) -> Option<u64> {
375 self.contents.quantity()
378 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
379 /// transient pubkey.
381 /// [`paths`]: Self::paths
382 pub fn payer_id(&self) -> PublicKey {
383 self.contents.payer_id()
386 /// Payer provided note to include in the invoice.
387 pub fn payer_note(&self) -> Option<PrintableString> {
388 self.contents.payer_note()
391 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
392 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
394 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
395 /// time is used for the `created_at` parameter.
397 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
399 /// [`Duration`]: core::time::Duration
400 #[cfg(feature = "std")]
402 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
403 signing_pubkey: PublicKey,
404 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
405 let created_at = std::time::SystemTime::now()
406 .duration_since(std::time::SystemTime::UNIX_EPOCH)
407 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
409 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
412 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
414 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
415 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
416 /// where [`std::time::SystemTime`] is not available.
418 /// The caller is expected to remember the preimage of `payment_hash` in order to
419 /// claim a payment for the invoice.
421 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
422 /// offer, which does have a `signing_pubkey`.
424 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
425 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
426 /// a preference. Note, however, that any privacy is lost if a public node id is used for
427 /// `signing_pubkey`.
429 /// Errors if the request contains unknown required features.
431 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
433 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
434 pub fn respond_with_no_std(
435 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
436 signing_pubkey: PublicKey, created_at: Duration
437 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
438 if self.features().requires_unknown_bits() {
439 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
442 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
445 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
446 /// derived signing keys to sign the [`Bolt12Invoice`].
448 /// See [`Refund::respond_with`] for further details.
450 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
452 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
453 #[cfg(feature = "std")]
454 pub fn respond_using_derived_keys<ES: Deref>(
455 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
456 expanded_key: &ExpandedKey, entropy_source: ES
457 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
459 ES::Target: EntropySource,
461 let created_at = std::time::SystemTime::now()
462 .duration_since(std::time::SystemTime::UNIX_EPOCH)
463 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
465 self.respond_using_derived_keys_no_std(
466 payment_paths, payment_hash, created_at, expanded_key, entropy_source
470 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
471 /// derived signing keys to sign the [`Bolt12Invoice`].
473 /// See [`Refund::respond_with_no_std`] for further details.
475 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
477 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
478 pub fn respond_using_derived_keys_no_std<ES: Deref>(
479 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
480 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
481 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
483 ES::Target: EntropySource,
485 if self.features().requires_unknown_bits() {
486 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
489 let nonce = Nonce::from_entropy_source(entropy_source);
490 let keys = signer::derive_keys(nonce, expanded_key);
491 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
495 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
496 self.contents.as_tlv_stream()
500 impl AsRef<[u8]> for Refund {
501 fn as_ref(&self) -> &[u8] {
506 impl RefundContents {
507 pub fn description(&self) -> PrintableString {
508 PrintableString(&self.description)
511 pub fn absolute_expiry(&self) -> Option<Duration> {
515 #[cfg(feature = "std")]
516 pub(super) fn is_expired(&self) -> bool {
517 match self.absolute_expiry {
518 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
519 Ok(elapsed) => elapsed > seconds_from_epoch,
526 pub fn issuer(&self) -> Option<PrintableString> {
527 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
530 pub fn paths(&self) -> &[BlindedPath] {
531 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
534 pub(super) fn metadata(&self) -> &[u8] {
535 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
538 pub(super) fn chain(&self) -> ChainHash {
539 self.chain.unwrap_or_else(|| self.implied_chain())
542 pub fn implied_chain(&self) -> ChainHash {
543 ChainHash::using_genesis_block(Network::Bitcoin)
546 pub fn amount_msats(&self) -> u64 {
550 /// Features pertaining to requesting an invoice.
551 pub fn features(&self) -> &InvoiceRequestFeatures {
555 /// The quantity of an item that refund is for.
556 pub fn quantity(&self) -> Option<u64> {
560 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
561 /// transient pubkey.
563 /// [`paths`]: Self::paths
564 pub fn payer_id(&self) -> PublicKey {
568 /// Payer provided note to include in the invoice.
569 pub fn payer_note(&self) -> Option<PrintableString> {
570 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
573 pub(super) fn derives_keys(&self) -> bool {
574 self.payer.0.derives_payer_keys()
577 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
578 let payer = PayerTlvStreamRef {
579 metadata: self.payer.0.as_bytes(),
582 let offer = OfferTlvStreamRef {
587 description: Some(&self.description),
589 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
590 paths: self.paths.as_ref(),
591 issuer: self.issuer.as_ref(),
597 if self.features == InvoiceRequestFeatures::empty() { None }
598 else { Some(&self.features) }
601 let invoice_request = InvoiceRequestTlvStreamRef {
602 chain: self.chain.as_ref(),
603 amount: Some(self.amount_msats),
605 quantity: self.quantity,
606 payer_id: Some(&self.payer_id),
607 payer_note: self.payer_note.as_ref(),
610 (payer, offer, invoice_request)
614 impl Writeable for Refund {
615 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
616 WithoutLength(&self.bytes).write(writer)
620 impl Writeable for RefundContents {
621 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
622 self.as_tlv_stream().write(writer)
626 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
628 type RefundTlvStreamRef<'a> = (
629 PayerTlvStreamRef<'a>,
630 OfferTlvStreamRef<'a>,
631 InvoiceRequestTlvStreamRef<'a>,
634 impl SeekReadable for RefundTlvStream {
635 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
636 let payer = SeekReadable::read(r)?;
637 let offer = SeekReadable::read(r)?;
638 let invoice_request = SeekReadable::read(r)?;
640 Ok((payer, offer, invoice_request))
644 impl Bech32Encode for Refund {
645 const BECH32_HRP: &'static str = "lnr";
648 impl FromStr for Refund {
649 type Err = Bolt12ParseError;
651 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
652 Refund::from_bech32_str(s)
656 impl TryFrom<Vec<u8>> for Refund {
657 type Error = Bolt12ParseError;
659 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
660 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
661 let ParsedMessage { bytes, tlv_stream } = refund;
662 let contents = RefundContents::try_from(tlv_stream)?;
664 Ok(Refund { bytes, contents })
668 impl TryFrom<RefundTlvStream> for RefundContents {
669 type Error = Bolt12SemanticError;
671 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
673 PayerTlvStream { metadata: payer_metadata },
675 chains, metadata, currency, amount: offer_amount, description,
676 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
678 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
681 let payer = match payer_metadata {
682 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
683 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
686 if metadata.is_some() {
687 return Err(Bolt12SemanticError::UnexpectedMetadata);
690 if chains.is_some() {
691 return Err(Bolt12SemanticError::UnexpectedChain);
694 if currency.is_some() || offer_amount.is_some() {
695 return Err(Bolt12SemanticError::UnexpectedAmount);
698 let description = match description {
699 None => return Err(Bolt12SemanticError::MissingDescription),
700 Some(description) => description,
703 if offer_features.is_some() {
704 return Err(Bolt12SemanticError::UnexpectedFeatures);
707 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
709 if quantity_max.is_some() {
710 return Err(Bolt12SemanticError::UnexpectedQuantity);
713 if node_id.is_some() {
714 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
717 let amount_msats = match amount {
718 None => return Err(Bolt12SemanticError::MissingAmount),
719 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
720 return Err(Bolt12SemanticError::InvalidAmount);
722 Some(amount_msats) => amount_msats,
725 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
727 let payer_id = match payer_id {
728 None => return Err(Bolt12SemanticError::MissingPayerId),
729 Some(payer_id) => payer_id,
733 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
734 quantity, payer_id, payer_note,
739 impl core::fmt::Display for Refund {
740 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
741 self.fmt_bech32_str(f)
747 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
749 use bitcoin::blockdata::constants::ChainHash;
750 use bitcoin::network::constants::Network;
751 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
752 use core::convert::TryFrom;
753 use core::time::Duration;
754 use crate::blinded_path::{BlindedHop, BlindedPath};
755 use crate::sign::KeyMaterial;
756 use crate::ln::channelmanager::PaymentId;
757 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
758 use crate::ln::inbound_payment::ExpandedKey;
759 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
760 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
761 use crate::offers::offer::OfferTlvStreamRef;
762 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
763 use crate::offers::payer::PayerTlvStreamRef;
764 use crate::offers::test_utils::*;
765 use crate::util::ser::{BigSize, Writeable};
766 use crate::util::string::PrintableString;
769 fn to_bytes(&self) -> Vec<u8>;
772 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
773 fn to_bytes(&self) -> Vec<u8> {
774 let mut buffer = Vec::new();
775 self.write(&mut buffer).unwrap();
781 fn builds_refund_with_defaults() {
782 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
785 let mut buffer = Vec::new();
786 refund.write(&mut buffer).unwrap();
788 assert_eq!(refund.bytes, buffer.as_slice());
789 assert_eq!(refund.payer_metadata(), &[1; 32]);
790 assert_eq!(refund.description(), PrintableString("foo"));
791 assert_eq!(refund.absolute_expiry(), None);
792 #[cfg(feature = "std")]
793 assert!(!refund.is_expired());
794 assert_eq!(refund.paths(), &[]);
795 assert_eq!(refund.issuer(), None);
796 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
797 assert_eq!(refund.amount_msats(), 1000);
798 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
799 assert_eq!(refund.payer_id(), payer_pubkey());
800 assert_eq!(refund.payer_note(), None);
803 refund.as_tlv_stream(),
805 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
811 description: Some(&String::from("foo")),
813 absolute_expiry: None,
819 InvoiceRequestTlvStreamRef {
824 payer_id: Some(&payer_pubkey()),
830 if let Err(e) = Refund::try_from(buffer) {
831 panic!("error parsing refund: {:?}", e);
836 fn fails_building_refund_with_invalid_amount() {
837 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
838 Ok(_) => panic!("expected error"),
839 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
844 fn builds_refund_with_metadata_derived() {
845 let desc = "foo".to_string();
846 let node_id = payer_pubkey();
847 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
848 let entropy = FixedEntropy {};
849 let secp_ctx = Secp256k1::new();
850 let payment_id = PaymentId([1; 32]);
852 let refund = RefundBuilder
853 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
856 assert_eq!(refund.payer_id(), node_id);
858 // Fails verification with altered fields
860 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
863 .sign(recipient_sign).unwrap();
864 match invoice.verify(&expanded_key, &secp_ctx) {
865 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
866 Err(()) => panic!("verification failed"),
869 let mut tlv_stream = refund.as_tlv_stream();
870 tlv_stream.2.amount = Some(2000);
872 let mut encoded_refund = Vec::new();
873 tlv_stream.write(&mut encoded_refund).unwrap();
875 let invoice = Refund::try_from(encoded_refund).unwrap()
876 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
879 .sign(recipient_sign).unwrap();
880 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
882 // Fails verification with altered metadata
883 let mut tlv_stream = refund.as_tlv_stream();
884 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
885 tlv_stream.0.metadata = Some(&metadata);
887 let mut encoded_refund = Vec::new();
888 tlv_stream.write(&mut encoded_refund).unwrap();
890 let invoice = Refund::try_from(encoded_refund).unwrap()
891 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
894 .sign(recipient_sign).unwrap();
895 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
899 fn builds_refund_with_derived_payer_id() {
900 let desc = "foo".to_string();
901 let node_id = payer_pubkey();
902 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
903 let entropy = FixedEntropy {};
904 let secp_ctx = Secp256k1::new();
905 let payment_id = PaymentId([1; 32]);
907 let blinded_path = BlindedPath {
908 introduction_node_id: pubkey(40),
909 blinding_point: pubkey(41),
911 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
912 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
916 let refund = RefundBuilder
917 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
921 assert_ne!(refund.payer_id(), node_id);
924 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
927 .sign(recipient_sign).unwrap();
928 match invoice.verify(&expanded_key, &secp_ctx) {
929 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
930 Err(()) => panic!("verification failed"),
933 // Fails verification with altered fields
934 let mut tlv_stream = refund.as_tlv_stream();
935 tlv_stream.2.amount = Some(2000);
937 let mut encoded_refund = Vec::new();
938 tlv_stream.write(&mut encoded_refund).unwrap();
940 let invoice = Refund::try_from(encoded_refund).unwrap()
941 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
944 .sign(recipient_sign).unwrap();
945 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
947 // Fails verification with altered payer_id
948 let mut tlv_stream = refund.as_tlv_stream();
949 let payer_id = pubkey(1);
950 tlv_stream.2.payer_id = Some(&payer_id);
952 let mut encoded_refund = Vec::new();
953 tlv_stream.write(&mut encoded_refund).unwrap();
955 let invoice = Refund::try_from(encoded_refund).unwrap()
956 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
959 .sign(recipient_sign).unwrap();
960 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
964 fn builds_refund_with_absolute_expiry() {
965 let future_expiry = Duration::from_secs(u64::max_value());
966 let past_expiry = Duration::from_secs(0);
968 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
969 .absolute_expiry(future_expiry)
972 let (_, tlv_stream, _) = refund.as_tlv_stream();
973 #[cfg(feature = "std")]
974 assert!(!refund.is_expired());
975 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
976 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
978 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
979 .absolute_expiry(future_expiry)
980 .absolute_expiry(past_expiry)
983 let (_, tlv_stream, _) = refund.as_tlv_stream();
984 #[cfg(feature = "std")]
985 assert!(refund.is_expired());
986 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
987 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
991 fn builds_refund_with_paths() {
994 introduction_node_id: pubkey(40),
995 blinding_point: pubkey(41),
997 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
998 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1002 introduction_node_id: pubkey(40),
1003 blinding_point: pubkey(41),
1005 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1006 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1011 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1012 .path(paths[0].clone())
1013 .path(paths[1].clone())
1016 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1017 assert_eq!(refund.paths(), paths.as_slice());
1018 assert_eq!(refund.payer_id(), pubkey(42));
1019 assert_ne!(pubkey(42), pubkey(44));
1020 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1021 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1025 fn builds_refund_with_issuer() {
1026 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1027 .issuer("bar".into())
1030 let (_, tlv_stream, _) = refund.as_tlv_stream();
1031 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1032 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1034 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1035 .issuer("bar".into())
1036 .issuer("baz".into())
1039 let (_, tlv_stream, _) = refund.as_tlv_stream();
1040 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1041 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1045 fn builds_refund_with_chain() {
1046 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1047 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1049 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1050 .chain(Network::Bitcoin)
1052 let (_, _, tlv_stream) = refund.as_tlv_stream();
1053 assert_eq!(refund.chain(), mainnet);
1054 assert_eq!(tlv_stream.chain, None);
1056 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1057 .chain(Network::Testnet)
1059 let (_, _, tlv_stream) = refund.as_tlv_stream();
1060 assert_eq!(refund.chain(), testnet);
1061 assert_eq!(tlv_stream.chain, Some(&testnet));
1063 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1064 .chain(Network::Regtest)
1065 .chain(Network::Testnet)
1067 let (_, _, tlv_stream) = refund.as_tlv_stream();
1068 assert_eq!(refund.chain(), testnet);
1069 assert_eq!(tlv_stream.chain, Some(&testnet));
1073 fn builds_refund_with_quantity() {
1074 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1077 let (_, _, tlv_stream) = refund.as_tlv_stream();
1078 assert_eq!(refund.quantity(), Some(10));
1079 assert_eq!(tlv_stream.quantity, Some(10));
1081 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1085 let (_, _, tlv_stream) = refund.as_tlv_stream();
1086 assert_eq!(refund.quantity(), Some(1));
1087 assert_eq!(tlv_stream.quantity, Some(1));
1091 fn builds_refund_with_payer_note() {
1092 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1093 .payer_note("bar".into())
1095 let (_, _, tlv_stream) = refund.as_tlv_stream();
1096 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1097 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1099 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1100 .payer_note("bar".into())
1101 .payer_note("baz".into())
1103 let (_, _, tlv_stream) = refund.as_tlv_stream();
1104 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1105 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1109 fn fails_responding_with_unknown_required_features() {
1110 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1111 .features_unchecked(InvoiceRequestFeatures::unknown())
1113 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1115 Ok(_) => panic!("expected error"),
1116 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1121 fn parses_refund_with_metadata() {
1122 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1124 if let Err(e) = refund.to_string().parse::<Refund>() {
1125 panic!("error parsing refund: {:?}", e);
1128 let mut tlv_stream = refund.as_tlv_stream();
1129 tlv_stream.0.metadata = None;
1131 match Refund::try_from(tlv_stream.to_bytes()) {
1132 Ok(_) => panic!("expected error"),
1134 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1140 fn parses_refund_with_description() {
1141 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1143 if let Err(e) = refund.to_string().parse::<Refund>() {
1144 panic!("error parsing refund: {:?}", e);
1147 let mut tlv_stream = refund.as_tlv_stream();
1148 tlv_stream.1.description = None;
1150 match Refund::try_from(tlv_stream.to_bytes()) {
1151 Ok(_) => panic!("expected error"),
1153 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1159 fn parses_refund_with_amount() {
1160 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1162 if let Err(e) = refund.to_string().parse::<Refund>() {
1163 panic!("error parsing refund: {:?}", e);
1166 let mut tlv_stream = refund.as_tlv_stream();
1167 tlv_stream.2.amount = None;
1169 match Refund::try_from(tlv_stream.to_bytes()) {
1170 Ok(_) => panic!("expected error"),
1172 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1176 let mut tlv_stream = refund.as_tlv_stream();
1177 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1179 match Refund::try_from(tlv_stream.to_bytes()) {
1180 Ok(_) => panic!("expected error"),
1182 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1188 fn parses_refund_with_payer_id() {
1189 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1191 if let Err(e) = refund.to_string().parse::<Refund>() {
1192 panic!("error parsing refund: {:?}", e);
1195 let mut tlv_stream = refund.as_tlv_stream();
1196 tlv_stream.2.payer_id = None;
1198 match Refund::try_from(tlv_stream.to_bytes()) {
1199 Ok(_) => panic!("expected error"),
1201 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1207 fn parses_refund_with_optional_fields() {
1208 let past_expiry = Duration::from_secs(0);
1211 introduction_node_id: pubkey(40),
1212 blinding_point: pubkey(41),
1214 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1215 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1219 introduction_node_id: pubkey(40),
1220 blinding_point: pubkey(41),
1222 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1223 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1228 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1229 .absolute_expiry(past_expiry)
1230 .issuer("bar".into())
1231 .path(paths[0].clone())
1232 .path(paths[1].clone())
1233 .chain(Network::Testnet)
1234 .features_unchecked(InvoiceRequestFeatures::unknown())
1236 .payer_note("baz".into())
1239 match refund.to_string().parse::<Refund>() {
1241 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1242 #[cfg(feature = "std")]
1243 assert!(refund.is_expired());
1244 assert_eq!(refund.paths(), &paths[..]);
1245 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1246 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1247 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1248 assert_eq!(refund.quantity(), Some(10));
1249 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1251 Err(e) => panic!("error parsing refund: {:?}", e),
1256 fn fails_parsing_refund_with_unexpected_fields() {
1257 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1259 if let Err(e) = refund.to_string().parse::<Refund>() {
1260 panic!("error parsing refund: {:?}", e);
1263 let metadata = vec![42; 32];
1264 let mut tlv_stream = refund.as_tlv_stream();
1265 tlv_stream.1.metadata = Some(&metadata);
1267 match Refund::try_from(tlv_stream.to_bytes()) {
1268 Ok(_) => panic!("expected error"),
1270 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1274 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1275 let mut tlv_stream = refund.as_tlv_stream();
1276 tlv_stream.1.chains = Some(&chains);
1278 match Refund::try_from(tlv_stream.to_bytes()) {
1279 Ok(_) => panic!("expected error"),
1281 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1285 let mut tlv_stream = refund.as_tlv_stream();
1286 tlv_stream.1.currency = Some(&b"USD");
1287 tlv_stream.1.amount = Some(1000);
1289 match Refund::try_from(tlv_stream.to_bytes()) {
1290 Ok(_) => panic!("expected error"),
1292 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1296 let features = OfferFeatures::unknown();
1297 let mut tlv_stream = refund.as_tlv_stream();
1298 tlv_stream.1.features = Some(&features);
1300 match Refund::try_from(tlv_stream.to_bytes()) {
1301 Ok(_) => panic!("expected error"),
1303 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1307 let mut tlv_stream = refund.as_tlv_stream();
1308 tlv_stream.1.quantity_max = Some(10);
1310 match Refund::try_from(tlv_stream.to_bytes()) {
1311 Ok(_) => panic!("expected error"),
1313 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1317 let node_id = payer_pubkey();
1318 let mut tlv_stream = refund.as_tlv_stream();
1319 tlv_stream.1.node_id = Some(&node_id);
1321 match Refund::try_from(tlv_stream.to_bytes()) {
1322 Ok(_) => panic!("expected error"),
1324 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1330 fn fails_parsing_refund_with_extra_tlv_records() {
1331 let secp_ctx = Secp256k1::new();
1332 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1333 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1336 let mut encoded_refund = Vec::new();
1337 refund.write(&mut encoded_refund).unwrap();
1338 BigSize(1002).write(&mut encoded_refund).unwrap();
1339 BigSize(32).write(&mut encoded_refund).unwrap();
1340 [42u8; 32].write(&mut encoded_refund).unwrap();
1342 match Refund::try_from(encoded_refund) {
1343 Ok(_) => panic!("expected error"),
1344 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),