1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for refunds.
12 //! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
13 //! directly to the customer. The recipient responds with a [`Bolt12Invoice`] to be paid.
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
17 //! [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
18 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
19 //! [`Offer`]: crate::offers::offer::Offer
24 //! extern crate bitcoin;
25 //! extern crate core;
26 //! extern crate lightning;
28 //! use core::convert::TryFrom;
29 //! use core::time::Duration;
31 //! use bitcoin::network::constants::Network;
32 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
33 //! use lightning::offers::parse::Bolt12ParseError;
34 //! use lightning::offers::refund::{Refund, RefundBuilder};
35 //! use lightning::util::ser::{Readable, Writeable};
37 //! # use lightning::blinded_path::BlindedPath;
38 //! # #[cfg(feature = "std")]
39 //! # use std::time::SystemTime;
41 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
42 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
44 //! # #[cfg(feature = "std")]
45 //! # fn build() -> Result<(), Bolt12ParseError> {
46 //! let secp_ctx = Secp256k1::new();
47 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
48 //! let pubkey = PublicKey::from(keys);
50 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
51 //! let refund = RefundBuilder::new("coffee, large".to_string(), vec![1; 32], pubkey, 20_000)?
52 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
53 //! .issuer("Foo Bar".to_string())
54 //! .path(create_blinded_path())
55 //! .path(create_another_blinded_path())
56 //! .chain(Network::Bitcoin)
57 //! .payer_note("refund for order #12345".to_string())
60 //! // Encode as a bech32 string for use in a QR code.
61 //! let encoded_refund = refund.to_string();
63 //! // Parse from a bech32 string after scanning from a QR code.
64 //! let refund = encoded_refund.parse::<Refund>()?;
66 //! // Encode refund as raw bytes.
67 //! let mut bytes = Vec::new();
68 //! refund.write(&mut bytes).unwrap();
70 //! // Decode raw bytes into an refund.
71 //! let refund = Refund::try_from(bytes)?;
78 //! If constructing a [`Refund`] for use with a [`ChannelManager`], use
79 //! [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
81 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
82 //! [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
84 use bitcoin::blockdata::constants::ChainHash;
85 use bitcoin::network::constants::Network;
86 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
87 use core::convert::TryFrom;
88 use core::hash::{Hash, Hasher};
90 use core::str::FromStr;
91 use core::time::Duration;
92 use crate::sign::EntropySource;
94 use crate::blinded_path::BlindedPath;
95 use crate::ln::PaymentHash;
96 use crate::ln::channelmanager::PaymentId;
97 use crate::ln::features::InvoiceRequestFeatures;
98 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
99 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
100 use crate::offers::invoice::{BlindedPayInfo, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder};
101 use crate::offers::invoice_request::{InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
102 use crate::offers::offer::{OfferTlvStream, OfferTlvStreamRef};
103 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
104 use crate::offers::payer::{PayerContents, PayerTlvStream, PayerTlvStreamRef};
105 use crate::offers::signer::{Metadata, MetadataMaterial, self};
106 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
107 use crate::util::string::PrintableString;
109 use crate::prelude::*;
111 #[cfg(feature = "std")]
112 use std::time::SystemTime;
114 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Refund ~~~~~";
116 /// Builds a [`Refund`] for the "offer for money" flow.
118 /// See [module-level documentation] for usage.
120 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
122 /// [module-level documentation]: self
123 pub struct RefundBuilder<'a, T: secp256k1::Signing> {
124 refund: RefundContents,
125 secp_ctx: Option<&'a Secp256k1<T>>,
128 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
129 /// Creates a new builder for a refund using the [`Refund::payer_id`] for the public node id to
130 /// send to if no [`Refund::paths`] are set. Otherwise, it may be a transient pubkey.
132 /// Additionally, sets the required [`Refund::description`], [`Refund::payer_metadata`], and
133 /// [`Refund::amount_msats`].
137 /// If constructing a [`Refund`] for use with a [`ChannelManager`], use
138 /// [`ChannelManager::create_refund_builder`] instead of [`RefundBuilder::new`].
140 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
141 /// [`ChannelManager::create_refund_builder`]: crate::ln::channelmanager::ChannelManager::create_refund_builder
143 description: String, metadata: Vec<u8>, payer_id: PublicKey, amount_msats: u64
144 ) -> Result<Self, Bolt12SemanticError> {
145 if amount_msats > MAX_VALUE_MSAT {
146 return Err(Bolt12SemanticError::InvalidAmount);
149 let metadata = Metadata::Bytes(metadata);
151 refund: RefundContents {
152 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
153 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
154 quantity: None, payer_id, payer_note: None,
161 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
162 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
163 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
164 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
165 /// provided `node_id` is used for the payer id.
167 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
168 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
170 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
171 /// one invoice will be paid for the refund and that payments can be uniquely identified.
173 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
174 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
175 pub fn deriving_payer_id<ES: Deref>(
176 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
177 secp_ctx: &'a Secp256k1<T>, amount_msats: u64, payment_id: PaymentId
178 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
179 if amount_msats > MAX_VALUE_MSAT {
180 return Err(Bolt12SemanticError::InvalidAmount);
183 let nonce = Nonce::from_entropy_source(entropy_source);
184 let payment_id = Some(payment_id);
185 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
186 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
188 refund: RefundContents {
189 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
190 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
191 quantity: None, payer_id: node_id, payer_note: None,
193 secp_ctx: Some(secp_ctx),
197 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
198 /// already passed is valid and can be checked for using [`Refund::is_expired`].
200 /// Successive calls to this method will override the previous setting.
201 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
202 self.refund.absolute_expiry = Some(absolute_expiry);
206 /// Sets the [`Refund::issuer`].
208 /// Successive calls to this method will override the previous setting.
209 pub fn issuer(mut self, issuer: String) -> Self {
210 self.refund.issuer = Some(issuer);
214 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
215 /// by private channels or if [`Refund::payer_id`] is not a public node id.
217 /// Successive calls to this method will add another blinded path. Caller is responsible for not
218 /// adding duplicate paths.
219 pub fn path(mut self, path: BlindedPath) -> Self {
220 self.refund.paths.get_or_insert_with(Vec::new).push(path);
224 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
225 /// called, [`Network::Bitcoin`] is assumed.
227 /// Successive calls to this method will override the previous setting.
228 pub fn chain(self, network: Network) -> Self {
229 self.chain_hash(ChainHash::using_genesis_block(network))
232 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
233 /// [`Network::Bitcoin`] is assumed.
235 /// Successive calls to this method will override the previous setting.
236 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Self {
237 self.refund.chain = Some(chain);
241 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
242 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
243 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
245 /// Successive calls to this method will override the previous setting.
247 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
248 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
249 /// [`Offer`]: crate::offers::offer::Offer
250 pub fn quantity(mut self, quantity: u64) -> Self {
251 self.refund.quantity = Some(quantity);
255 /// Sets the [`Refund::payer_note`].
257 /// Successive calls to this method will override the previous setting.
258 pub fn payer_note(mut self, payer_note: String) -> Self {
259 self.refund.payer_note = Some(payer_note);
263 /// Builds a [`Refund`] after checking for valid semantics.
264 pub fn build(mut self) -> Result<Refund, Bolt12SemanticError> {
265 if self.refund.chain() == self.refund.implied_chain() {
266 self.refund.chain = None;
269 // Create the metadata for stateless verification of a Bolt12Invoice.
270 if self.refund.payer.0.has_derivation_material() {
271 let mut metadata = core::mem::take(&mut self.refund.payer.0);
273 if self.refund.paths.is_none() {
274 metadata = metadata.without_keys();
277 let mut tlv_stream = self.refund.as_tlv_stream();
278 tlv_stream.0.metadata = None;
279 if metadata.derives_payer_keys() {
280 tlv_stream.2.payer_id = None;
283 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
284 metadata = derived_metadata;
285 if let Some(keys) = keys {
286 self.refund.payer_id = keys.public_key();
289 self.refund.payer.0 = metadata;
292 let mut bytes = Vec::new();
293 self.refund.write(&mut bytes).unwrap();
295 Ok(Refund { bytes, contents: self.refund })
300 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
301 pub(crate) fn clear_paths(mut self) -> Self {
302 self.refund.paths = None;
306 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
307 self.refund.features = features;
312 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
314 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
315 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
318 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
319 /// [`Offer`]: crate::offers::offer::Offer
320 #[derive(Clone, Debug)]
322 pub(super) bytes: Vec<u8>,
323 pub(super) contents: RefundContents,
326 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
328 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
329 #[derive(Clone, Debug)]
330 #[cfg_attr(test, derive(PartialEq))]
331 pub(super) struct RefundContents {
332 payer: PayerContents,
335 absolute_expiry: Option<Duration>,
336 issuer: Option<String>,
337 paths: Option<Vec<BlindedPath>>,
338 // invoice_request fields
339 chain: Option<ChainHash>,
341 features: InvoiceRequestFeatures,
342 quantity: Option<u64>,
344 payer_note: Option<String>,
348 /// A complete description of the purpose of the refund. Intended to be displayed to the user
349 /// but with the caveat that it has not been verified in any way.
350 pub fn description(&self) -> PrintableString {
351 self.contents.description()
354 /// Duration since the Unix epoch when an invoice should no longer be sent.
356 /// If `None`, the refund does not expire.
357 pub fn absolute_expiry(&self) -> Option<Duration> {
358 self.contents.absolute_expiry()
361 /// Whether the refund has expired.
362 #[cfg(feature = "std")]
363 pub fn is_expired(&self) -> bool {
364 self.contents.is_expired()
367 /// Whether the refund has expired given the duration since the Unix epoch.
368 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
369 self.contents.is_expired_no_std(duration_since_epoch)
372 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
373 /// displayed to the user but with the caveat that it has not been verified in any way.
374 pub fn issuer(&self) -> Option<PrintableString> {
375 self.contents.issuer()
378 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
379 /// privacy by obfuscating its node id.
380 pub fn paths(&self) -> &[BlindedPath] {
381 self.contents.paths()
384 /// An unpredictable series of bytes, typically containing information about the derivation of
387 /// [`payer_id`]: Self::payer_id
388 pub fn payer_metadata(&self) -> &[u8] {
389 self.contents.metadata()
392 /// A chain that the refund is valid for.
393 pub fn chain(&self) -> ChainHash {
394 self.contents.chain()
397 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
399 /// [`chain`]: Self::chain
400 pub fn amount_msats(&self) -> u64 {
401 self.contents.amount_msats()
404 /// Features pertaining to requesting an invoice.
405 pub fn features(&self) -> &InvoiceRequestFeatures {
406 &self.contents.features()
409 /// The quantity of an item that refund is for.
410 pub fn quantity(&self) -> Option<u64> {
411 self.contents.quantity()
414 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
415 /// transient pubkey.
417 /// [`paths`]: Self::paths
418 pub fn payer_id(&self) -> PublicKey {
419 self.contents.payer_id()
422 /// Payer provided note to include in the invoice.
423 pub fn payer_note(&self) -> Option<PrintableString> {
424 self.contents.payer_note()
427 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
428 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
430 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
431 /// time is used for the `created_at` parameter.
433 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
435 /// [`Duration`]: core::time::Duration
436 #[cfg(feature = "std")]
438 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
439 signing_pubkey: PublicKey,
440 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
441 let created_at = std::time::SystemTime::now()
442 .duration_since(std::time::SystemTime::UNIX_EPOCH)
443 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
445 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
448 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
450 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
451 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
452 /// where [`std::time::SystemTime`] is not available.
454 /// The caller is expected to remember the preimage of `payment_hash` in order to
455 /// claim a payment for the invoice.
457 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
458 /// offer, which does have a `signing_pubkey`.
460 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
461 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
462 /// a preference. Note, however, that any privacy is lost if a public node id is used for
463 /// `signing_pubkey`.
465 /// Errors if the request contains unknown required features.
467 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
469 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
470 pub fn respond_with_no_std(
471 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
472 signing_pubkey: PublicKey, created_at: Duration
473 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
474 if self.features().requires_unknown_bits() {
475 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
478 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
481 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
482 /// derived signing keys to sign the [`Bolt12Invoice`].
484 /// See [`Refund::respond_with`] for further details.
486 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
488 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
489 #[cfg(feature = "std")]
490 pub fn respond_using_derived_keys<ES: Deref>(
491 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
492 expanded_key: &ExpandedKey, entropy_source: ES
493 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
495 ES::Target: EntropySource,
497 let created_at = std::time::SystemTime::now()
498 .duration_since(std::time::SystemTime::UNIX_EPOCH)
499 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
501 self.respond_using_derived_keys_no_std(
502 payment_paths, payment_hash, created_at, expanded_key, entropy_source
506 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
507 /// derived signing keys to sign the [`Bolt12Invoice`].
509 /// See [`Refund::respond_with_no_std`] for further details.
511 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
513 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
514 pub fn respond_using_derived_keys_no_std<ES: Deref>(
515 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
516 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
517 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
519 ES::Target: EntropySource,
521 if self.features().requires_unknown_bits() {
522 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
525 let nonce = Nonce::from_entropy_source(entropy_source);
526 let keys = signer::derive_keys(nonce, expanded_key);
527 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
531 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
532 self.contents.as_tlv_stream()
536 impl AsRef<[u8]> for Refund {
537 fn as_ref(&self) -> &[u8] {
542 impl PartialEq for Refund {
543 fn eq(&self, other: &Self) -> bool {
544 self.bytes.eq(&other.bytes)
548 impl Eq for Refund {}
550 impl Hash for Refund {
551 fn hash<H: Hasher>(&self, state: &mut H) {
552 self.bytes.hash(state);
556 impl RefundContents {
557 pub fn description(&self) -> PrintableString {
558 PrintableString(&self.description)
561 pub fn absolute_expiry(&self) -> Option<Duration> {
565 #[cfg(feature = "std")]
566 pub(super) fn is_expired(&self) -> bool {
567 SystemTime::UNIX_EPOCH
569 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
573 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
575 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
579 pub fn issuer(&self) -> Option<PrintableString> {
580 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
583 pub fn paths(&self) -> &[BlindedPath] {
584 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
587 pub(super) fn metadata(&self) -> &[u8] {
588 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
591 pub(super) fn chain(&self) -> ChainHash {
592 self.chain.unwrap_or_else(|| self.implied_chain())
595 pub fn implied_chain(&self) -> ChainHash {
596 ChainHash::using_genesis_block(Network::Bitcoin)
599 pub fn amount_msats(&self) -> u64 {
603 /// Features pertaining to requesting an invoice.
604 pub fn features(&self) -> &InvoiceRequestFeatures {
608 /// The quantity of an item that refund is for.
609 pub fn quantity(&self) -> Option<u64> {
613 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
614 /// transient pubkey.
616 /// [`paths`]: Self::paths
617 pub fn payer_id(&self) -> PublicKey {
621 /// Payer provided note to include in the invoice.
622 pub fn payer_note(&self) -> Option<PrintableString> {
623 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
626 pub(super) fn derives_keys(&self) -> bool {
627 self.payer.0.derives_payer_keys()
630 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
631 let payer = PayerTlvStreamRef {
632 metadata: self.payer.0.as_bytes(),
635 let offer = OfferTlvStreamRef {
640 description: Some(&self.description),
642 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
643 paths: self.paths.as_ref(),
644 issuer: self.issuer.as_ref(),
650 if self.features == InvoiceRequestFeatures::empty() { None }
651 else { Some(&self.features) }
654 let invoice_request = InvoiceRequestTlvStreamRef {
655 chain: self.chain.as_ref(),
656 amount: Some(self.amount_msats),
658 quantity: self.quantity,
659 payer_id: Some(&self.payer_id),
660 payer_note: self.payer_note.as_ref(),
663 (payer, offer, invoice_request)
667 impl Writeable for Refund {
668 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
669 WithoutLength(&self.bytes).write(writer)
673 impl Writeable for RefundContents {
674 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
675 self.as_tlv_stream().write(writer)
679 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
681 type RefundTlvStreamRef<'a> = (
682 PayerTlvStreamRef<'a>,
683 OfferTlvStreamRef<'a>,
684 InvoiceRequestTlvStreamRef<'a>,
687 impl SeekReadable for RefundTlvStream {
688 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
689 let payer = SeekReadable::read(r)?;
690 let offer = SeekReadable::read(r)?;
691 let invoice_request = SeekReadable::read(r)?;
693 Ok((payer, offer, invoice_request))
697 impl Bech32Encode for Refund {
698 const BECH32_HRP: &'static str = "lnr";
701 impl FromStr for Refund {
702 type Err = Bolt12ParseError;
704 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
705 Refund::from_bech32_str(s)
709 impl TryFrom<Vec<u8>> for Refund {
710 type Error = Bolt12ParseError;
712 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
713 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
714 let ParsedMessage { bytes, tlv_stream } = refund;
715 let contents = RefundContents::try_from(tlv_stream)?;
717 Ok(Refund { bytes, contents })
721 impl TryFrom<RefundTlvStream> for RefundContents {
722 type Error = Bolt12SemanticError;
724 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
726 PayerTlvStream { metadata: payer_metadata },
728 chains, metadata, currency, amount: offer_amount, description,
729 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
731 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
734 let payer = match payer_metadata {
735 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
736 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
739 if metadata.is_some() {
740 return Err(Bolt12SemanticError::UnexpectedMetadata);
743 if chains.is_some() {
744 return Err(Bolt12SemanticError::UnexpectedChain);
747 if currency.is_some() || offer_amount.is_some() {
748 return Err(Bolt12SemanticError::UnexpectedAmount);
751 let description = match description {
752 None => return Err(Bolt12SemanticError::MissingDescription),
753 Some(description) => description,
756 if offer_features.is_some() {
757 return Err(Bolt12SemanticError::UnexpectedFeatures);
760 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
762 if quantity_max.is_some() {
763 return Err(Bolt12SemanticError::UnexpectedQuantity);
766 if node_id.is_some() {
767 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
770 let amount_msats = match amount {
771 None => return Err(Bolt12SemanticError::MissingAmount),
772 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
773 return Err(Bolt12SemanticError::InvalidAmount);
775 Some(amount_msats) => amount_msats,
778 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
780 let payer_id = match payer_id {
781 None => return Err(Bolt12SemanticError::MissingPayerId),
782 Some(payer_id) => payer_id,
786 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
787 quantity, payer_id, payer_note,
792 impl core::fmt::Display for Refund {
793 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
794 self.fmt_bech32_str(f)
800 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
802 use bitcoin::blockdata::constants::ChainHash;
803 use bitcoin::network::constants::Network;
804 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
805 use core::convert::TryFrom;
806 use core::time::Duration;
807 use crate::blinded_path::{BlindedHop, BlindedPath};
808 use crate::sign::KeyMaterial;
809 use crate::ln::channelmanager::PaymentId;
810 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
811 use crate::ln::inbound_payment::ExpandedKey;
812 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
813 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
814 use crate::offers::offer::OfferTlvStreamRef;
815 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
816 use crate::offers::payer::PayerTlvStreamRef;
817 use crate::offers::test_utils::*;
818 use crate::util::ser::{BigSize, Writeable};
819 use crate::util::string::PrintableString;
822 fn to_bytes(&self) -> Vec<u8>;
825 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
826 fn to_bytes(&self) -> Vec<u8> {
827 let mut buffer = Vec::new();
828 self.write(&mut buffer).unwrap();
834 fn builds_refund_with_defaults() {
835 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
838 let mut buffer = Vec::new();
839 refund.write(&mut buffer).unwrap();
841 assert_eq!(refund.bytes, buffer.as_slice());
842 assert_eq!(refund.payer_metadata(), &[1; 32]);
843 assert_eq!(refund.description(), PrintableString("foo"));
844 assert_eq!(refund.absolute_expiry(), None);
845 #[cfg(feature = "std")]
846 assert!(!refund.is_expired());
847 assert_eq!(refund.paths(), &[]);
848 assert_eq!(refund.issuer(), None);
849 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
850 assert_eq!(refund.amount_msats(), 1000);
851 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
852 assert_eq!(refund.payer_id(), payer_pubkey());
853 assert_eq!(refund.payer_note(), None);
856 refund.as_tlv_stream(),
858 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
864 description: Some(&String::from("foo")),
866 absolute_expiry: None,
872 InvoiceRequestTlvStreamRef {
877 payer_id: Some(&payer_pubkey()),
883 if let Err(e) = Refund::try_from(buffer) {
884 panic!("error parsing refund: {:?}", e);
889 fn fails_building_refund_with_invalid_amount() {
890 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
891 Ok(_) => panic!("expected error"),
892 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
897 fn builds_refund_with_metadata_derived() {
898 let desc = "foo".to_string();
899 let node_id = payer_pubkey();
900 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
901 let entropy = FixedEntropy {};
902 let secp_ctx = Secp256k1::new();
903 let payment_id = PaymentId([1; 32]);
905 let refund = RefundBuilder
906 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
909 assert_eq!(refund.payer_id(), node_id);
911 // Fails verification with altered fields
913 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
916 .sign(recipient_sign).unwrap();
917 match invoice.verify(&expanded_key, &secp_ctx) {
918 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
919 Err(()) => panic!("verification failed"),
922 let mut tlv_stream = refund.as_tlv_stream();
923 tlv_stream.2.amount = Some(2000);
925 let mut encoded_refund = Vec::new();
926 tlv_stream.write(&mut encoded_refund).unwrap();
928 let invoice = Refund::try_from(encoded_refund).unwrap()
929 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
932 .sign(recipient_sign).unwrap();
933 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
935 // Fails verification with altered metadata
936 let mut tlv_stream = refund.as_tlv_stream();
937 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
938 tlv_stream.0.metadata = Some(&metadata);
940 let mut encoded_refund = Vec::new();
941 tlv_stream.write(&mut encoded_refund).unwrap();
943 let invoice = Refund::try_from(encoded_refund).unwrap()
944 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
947 .sign(recipient_sign).unwrap();
948 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
952 fn builds_refund_with_derived_payer_id() {
953 let desc = "foo".to_string();
954 let node_id = payer_pubkey();
955 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
956 let entropy = FixedEntropy {};
957 let secp_ctx = Secp256k1::new();
958 let payment_id = PaymentId([1; 32]);
960 let blinded_path = BlindedPath {
961 introduction_node_id: pubkey(40),
962 blinding_point: pubkey(41),
964 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
965 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
969 let refund = RefundBuilder
970 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
974 assert_ne!(refund.payer_id(), node_id);
977 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
980 .sign(recipient_sign).unwrap();
981 match invoice.verify(&expanded_key, &secp_ctx) {
982 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
983 Err(()) => panic!("verification failed"),
986 // Fails verification with altered fields
987 let mut tlv_stream = refund.as_tlv_stream();
988 tlv_stream.2.amount = Some(2000);
990 let mut encoded_refund = Vec::new();
991 tlv_stream.write(&mut encoded_refund).unwrap();
993 let invoice = Refund::try_from(encoded_refund).unwrap()
994 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
997 .sign(recipient_sign).unwrap();
998 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1000 // Fails verification with altered payer_id
1001 let mut tlv_stream = refund.as_tlv_stream();
1002 let payer_id = pubkey(1);
1003 tlv_stream.2.payer_id = Some(&payer_id);
1005 let mut encoded_refund = Vec::new();
1006 tlv_stream.write(&mut encoded_refund).unwrap();
1008 let invoice = Refund::try_from(encoded_refund).unwrap()
1009 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1012 .sign(recipient_sign).unwrap();
1013 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1017 fn builds_refund_with_absolute_expiry() {
1018 let future_expiry = Duration::from_secs(u64::max_value());
1019 let past_expiry = Duration::from_secs(0);
1020 let now = future_expiry - Duration::from_secs(1_000);
1022 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1023 .absolute_expiry(future_expiry)
1026 let (_, tlv_stream, _) = refund.as_tlv_stream();
1027 #[cfg(feature = "std")]
1028 assert!(!refund.is_expired());
1029 assert!(!refund.is_expired_no_std(now));
1030 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1031 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1033 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1034 .absolute_expiry(future_expiry)
1035 .absolute_expiry(past_expiry)
1038 let (_, tlv_stream, _) = refund.as_tlv_stream();
1039 #[cfg(feature = "std")]
1040 assert!(refund.is_expired());
1041 assert!(refund.is_expired_no_std(now));
1042 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1043 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1047 fn builds_refund_with_paths() {
1050 introduction_node_id: pubkey(40),
1051 blinding_point: pubkey(41),
1053 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1054 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1058 introduction_node_id: pubkey(40),
1059 blinding_point: pubkey(41),
1061 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1062 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1067 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1068 .path(paths[0].clone())
1069 .path(paths[1].clone())
1072 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1073 assert_eq!(refund.paths(), paths.as_slice());
1074 assert_eq!(refund.payer_id(), pubkey(42));
1075 assert_ne!(pubkey(42), pubkey(44));
1076 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1077 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1081 fn builds_refund_with_issuer() {
1082 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1083 .issuer("bar".into())
1086 let (_, tlv_stream, _) = refund.as_tlv_stream();
1087 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1088 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1090 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1091 .issuer("bar".into())
1092 .issuer("baz".into())
1095 let (_, tlv_stream, _) = refund.as_tlv_stream();
1096 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1097 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1101 fn builds_refund_with_chain() {
1102 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1103 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1105 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1106 .chain(Network::Bitcoin)
1108 let (_, _, tlv_stream) = refund.as_tlv_stream();
1109 assert_eq!(refund.chain(), mainnet);
1110 assert_eq!(tlv_stream.chain, None);
1112 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1113 .chain(Network::Testnet)
1115 let (_, _, tlv_stream) = refund.as_tlv_stream();
1116 assert_eq!(refund.chain(), testnet);
1117 assert_eq!(tlv_stream.chain, Some(&testnet));
1119 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1120 .chain(Network::Regtest)
1121 .chain(Network::Testnet)
1123 let (_, _, tlv_stream) = refund.as_tlv_stream();
1124 assert_eq!(refund.chain(), testnet);
1125 assert_eq!(tlv_stream.chain, Some(&testnet));
1129 fn builds_refund_with_quantity() {
1130 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1133 let (_, _, tlv_stream) = refund.as_tlv_stream();
1134 assert_eq!(refund.quantity(), Some(10));
1135 assert_eq!(tlv_stream.quantity, Some(10));
1137 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1141 let (_, _, tlv_stream) = refund.as_tlv_stream();
1142 assert_eq!(refund.quantity(), Some(1));
1143 assert_eq!(tlv_stream.quantity, Some(1));
1147 fn builds_refund_with_payer_note() {
1148 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1149 .payer_note("bar".into())
1151 let (_, _, tlv_stream) = refund.as_tlv_stream();
1152 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1153 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1155 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1156 .payer_note("bar".into())
1157 .payer_note("baz".into())
1159 let (_, _, tlv_stream) = refund.as_tlv_stream();
1160 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1161 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1165 fn fails_responding_with_unknown_required_features() {
1166 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1167 .features_unchecked(InvoiceRequestFeatures::unknown())
1169 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1171 Ok(_) => panic!("expected error"),
1172 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1177 fn parses_refund_with_metadata() {
1178 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1180 if let Err(e) = refund.to_string().parse::<Refund>() {
1181 panic!("error parsing refund: {:?}", e);
1184 let mut tlv_stream = refund.as_tlv_stream();
1185 tlv_stream.0.metadata = None;
1187 match Refund::try_from(tlv_stream.to_bytes()) {
1188 Ok(_) => panic!("expected error"),
1190 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1196 fn parses_refund_with_description() {
1197 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1199 if let Err(e) = refund.to_string().parse::<Refund>() {
1200 panic!("error parsing refund: {:?}", e);
1203 let mut tlv_stream = refund.as_tlv_stream();
1204 tlv_stream.1.description = None;
1206 match Refund::try_from(tlv_stream.to_bytes()) {
1207 Ok(_) => panic!("expected error"),
1209 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1215 fn parses_refund_with_amount() {
1216 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1218 if let Err(e) = refund.to_string().parse::<Refund>() {
1219 panic!("error parsing refund: {:?}", e);
1222 let mut tlv_stream = refund.as_tlv_stream();
1223 tlv_stream.2.amount = None;
1225 match Refund::try_from(tlv_stream.to_bytes()) {
1226 Ok(_) => panic!("expected error"),
1228 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1232 let mut tlv_stream = refund.as_tlv_stream();
1233 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1235 match Refund::try_from(tlv_stream.to_bytes()) {
1236 Ok(_) => panic!("expected error"),
1238 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1244 fn parses_refund_with_payer_id() {
1245 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1247 if let Err(e) = refund.to_string().parse::<Refund>() {
1248 panic!("error parsing refund: {:?}", e);
1251 let mut tlv_stream = refund.as_tlv_stream();
1252 tlv_stream.2.payer_id = None;
1254 match Refund::try_from(tlv_stream.to_bytes()) {
1255 Ok(_) => panic!("expected error"),
1257 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1263 fn parses_refund_with_optional_fields() {
1264 let past_expiry = Duration::from_secs(0);
1267 introduction_node_id: pubkey(40),
1268 blinding_point: pubkey(41),
1270 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1271 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1275 introduction_node_id: pubkey(40),
1276 blinding_point: pubkey(41),
1278 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1279 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1284 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1285 .absolute_expiry(past_expiry)
1286 .issuer("bar".into())
1287 .path(paths[0].clone())
1288 .path(paths[1].clone())
1289 .chain(Network::Testnet)
1290 .features_unchecked(InvoiceRequestFeatures::unknown())
1292 .payer_note("baz".into())
1295 match refund.to_string().parse::<Refund>() {
1297 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1298 #[cfg(feature = "std")]
1299 assert!(refund.is_expired());
1300 assert_eq!(refund.paths(), &paths[..]);
1301 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1302 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1303 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1304 assert_eq!(refund.quantity(), Some(10));
1305 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1307 Err(e) => panic!("error parsing refund: {:?}", e),
1312 fn fails_parsing_refund_with_unexpected_fields() {
1313 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1315 if let Err(e) = refund.to_string().parse::<Refund>() {
1316 panic!("error parsing refund: {:?}", e);
1319 let metadata = vec![42; 32];
1320 let mut tlv_stream = refund.as_tlv_stream();
1321 tlv_stream.1.metadata = Some(&metadata);
1323 match Refund::try_from(tlv_stream.to_bytes()) {
1324 Ok(_) => panic!("expected error"),
1326 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1330 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1331 let mut tlv_stream = refund.as_tlv_stream();
1332 tlv_stream.1.chains = Some(&chains);
1334 match Refund::try_from(tlv_stream.to_bytes()) {
1335 Ok(_) => panic!("expected error"),
1337 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1341 let mut tlv_stream = refund.as_tlv_stream();
1342 tlv_stream.1.currency = Some(&b"USD");
1343 tlv_stream.1.amount = Some(1000);
1345 match Refund::try_from(tlv_stream.to_bytes()) {
1346 Ok(_) => panic!("expected error"),
1348 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1352 let features = OfferFeatures::unknown();
1353 let mut tlv_stream = refund.as_tlv_stream();
1354 tlv_stream.1.features = Some(&features);
1356 match Refund::try_from(tlv_stream.to_bytes()) {
1357 Ok(_) => panic!("expected error"),
1359 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1363 let mut tlv_stream = refund.as_tlv_stream();
1364 tlv_stream.1.quantity_max = Some(10);
1366 match Refund::try_from(tlv_stream.to_bytes()) {
1367 Ok(_) => panic!("expected error"),
1369 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1373 let node_id = payer_pubkey();
1374 let mut tlv_stream = refund.as_tlv_stream();
1375 tlv_stream.1.node_id = Some(&node_id);
1377 match Refund::try_from(tlv_stream.to_bytes()) {
1378 Ok(_) => panic!("expected error"),
1380 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1386 fn fails_parsing_refund_with_extra_tlv_records() {
1387 let secp_ctx = Secp256k1::new();
1388 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1389 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1392 let mut encoded_refund = Vec::new();
1393 refund.write(&mut encoded_refund).unwrap();
1394 BigSize(1002).write(&mut encoded_refund).unwrap();
1395 BigSize(32).write(&mut encoded_refund).unwrap();
1396 [42u8; 32].write(&mut encoded_refund).unwrap();
1398 match Refund::try_from(encoded_refund) {
1399 Ok(_) => panic!("expected error"),
1400 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),