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 impl<'a> RefundBuilder<'a, secp256k1::SignOnly> {
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 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
161 /// Similar to [`RefundBuilder::new`] except, if [`RefundBuilder::path`] is called, the payer id
162 /// is derived from the given [`ExpandedKey`] and nonce. This provides sender privacy by using a
163 /// different payer id for each refund, assuming a different nonce is used. Otherwise, the
164 /// provided `node_id` is used for the payer id.
166 /// Also, sets the metadata when [`RefundBuilder::build`] is called such that it can be used to
167 /// verify that an [`InvoiceRequest`] was produced for the refund given an [`ExpandedKey`].
169 /// The `payment_id` is encrypted in the metadata and should be unique. This ensures that only
170 /// one invoice will be paid for the refund and that payments can be uniquely identified.
172 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
173 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
174 pub fn deriving_payer_id<ES: Deref>(
175 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
176 secp_ctx: &'a Secp256k1<T>, amount_msats: u64, payment_id: PaymentId
177 ) -> Result<Self, Bolt12SemanticError> where ES::Target: EntropySource {
178 if amount_msats > MAX_VALUE_MSAT {
179 return Err(Bolt12SemanticError::InvalidAmount);
182 let nonce = Nonce::from_entropy_source(entropy_source);
183 let payment_id = Some(payment_id);
184 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, payment_id);
185 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
187 refund: RefundContents {
188 payer: PayerContents(metadata), description, absolute_expiry: None, issuer: None,
189 paths: None, chain: None, amount_msats, features: InvoiceRequestFeatures::empty(),
190 quantity: None, payer_id: node_id, payer_note: None,
192 secp_ctx: Some(secp_ctx),
196 /// Sets the [`Refund::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
197 /// already passed is valid and can be checked for using [`Refund::is_expired`].
199 /// Successive calls to this method will override the previous setting.
200 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
201 self.refund.absolute_expiry = Some(absolute_expiry);
205 /// Sets the [`Refund::issuer`].
207 /// Successive calls to this method will override the previous setting.
208 pub fn issuer(mut self, issuer: String) -> Self {
209 self.refund.issuer = Some(issuer);
213 /// Adds a blinded path to [`Refund::paths`]. Must include at least one path if only connected
214 /// by private channels or if [`Refund::payer_id`] is not a public node id.
216 /// Successive calls to this method will add another blinded path. Caller is responsible for not
217 /// adding duplicate paths.
218 pub fn path(mut self, path: BlindedPath) -> Self {
219 self.refund.paths.get_or_insert_with(Vec::new).push(path);
223 /// Sets the [`Refund::chain`] of the given [`Network`] for paying an invoice. If not
224 /// called, [`Network::Bitcoin`] is assumed.
226 /// Successive calls to this method will override the previous setting.
227 pub fn chain(self, network: Network) -> Self {
228 self.chain_hash(ChainHash::using_genesis_block(network))
231 /// Sets the [`Refund::chain`] of the given [`ChainHash`] for paying an invoice. If not called,
232 /// [`Network::Bitcoin`] is assumed.
234 /// Successive calls to this method will override the previous setting.
235 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Self {
236 self.refund.chain = Some(chain);
240 /// Sets [`Refund::quantity`] of items. This is purely for informational purposes. It is useful
241 /// when the refund pertains to a [`Bolt12Invoice`] that paid for more than one item from an
242 /// [`Offer`] as specified by [`InvoiceRequest::quantity`].
244 /// Successive calls to this method will override the previous setting.
246 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
247 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
248 /// [`Offer`]: crate::offers::offer::Offer
249 pub fn quantity(mut self, quantity: u64) -> Self {
250 self.refund.quantity = Some(quantity);
254 /// Sets the [`Refund::payer_note`].
256 /// Successive calls to this method will override the previous setting.
257 pub fn payer_note(mut self, payer_note: String) -> Self {
258 self.refund.payer_note = Some(payer_note);
262 /// Builds a [`Refund`] after checking for valid semantics.
263 pub fn build(mut self) -> Result<Refund, Bolt12SemanticError> {
264 if self.refund.chain() == self.refund.implied_chain() {
265 self.refund.chain = None;
268 // Create the metadata for stateless verification of a Bolt12Invoice.
269 if self.refund.payer.0.has_derivation_material() {
270 let mut metadata = core::mem::take(&mut self.refund.payer.0);
272 if self.refund.paths.is_none() {
273 metadata = metadata.without_keys();
276 let mut tlv_stream = self.refund.as_tlv_stream();
277 tlv_stream.0.metadata = None;
278 if metadata.derives_payer_keys() {
279 tlv_stream.2.payer_id = None;
282 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
283 metadata = derived_metadata;
284 if let Some(keys) = keys {
285 self.refund.payer_id = keys.public_key();
288 self.refund.payer.0 = metadata;
291 let mut bytes = Vec::new();
292 self.refund.write(&mut bytes).unwrap();
294 Ok(Refund { bytes, contents: self.refund })
299 impl<'a, T: secp256k1::Signing> RefundBuilder<'a, T> {
300 pub(crate) fn clear_paths(mut self) -> Self {
301 self.refund.paths = None;
305 fn features_unchecked(mut self, features: InvoiceRequestFeatures) -> Self {
306 self.refund.features = features;
311 /// A `Refund` is a request to send an [`Bolt12Invoice`] without a preceding [`Offer`].
313 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
314 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
317 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
318 /// [`Offer`]: crate::offers::offer::Offer
319 #[derive(Clone, Debug)]
320 #[cfg_attr(test, derive(PartialEq))]
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 RefundContents {
543 pub fn description(&self) -> PrintableString {
544 PrintableString(&self.description)
547 pub fn absolute_expiry(&self) -> Option<Duration> {
551 #[cfg(feature = "std")]
552 pub(super) fn is_expired(&self) -> bool {
553 SystemTime::UNIX_EPOCH
555 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
559 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
561 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
565 pub fn issuer(&self) -> Option<PrintableString> {
566 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
569 pub fn paths(&self) -> &[BlindedPath] {
570 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
573 pub(super) fn metadata(&self) -> &[u8] {
574 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
577 pub(super) fn chain(&self) -> ChainHash {
578 self.chain.unwrap_or_else(|| self.implied_chain())
581 pub fn implied_chain(&self) -> ChainHash {
582 ChainHash::using_genesis_block(Network::Bitcoin)
585 pub fn amount_msats(&self) -> u64 {
589 /// Features pertaining to requesting an invoice.
590 pub fn features(&self) -> &InvoiceRequestFeatures {
594 /// The quantity of an item that refund is for.
595 pub fn quantity(&self) -> Option<u64> {
599 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
600 /// transient pubkey.
602 /// [`paths`]: Self::paths
603 pub fn payer_id(&self) -> PublicKey {
607 /// Payer provided note to include in the invoice.
608 pub fn payer_note(&self) -> Option<PrintableString> {
609 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
612 pub(super) fn derives_keys(&self) -> bool {
613 self.payer.0.derives_payer_keys()
616 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
617 let payer = PayerTlvStreamRef {
618 metadata: self.payer.0.as_bytes(),
621 let offer = OfferTlvStreamRef {
626 description: Some(&self.description),
628 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
629 paths: self.paths.as_ref(),
630 issuer: self.issuer.as_ref(),
636 if self.features == InvoiceRequestFeatures::empty() { None }
637 else { Some(&self.features) }
640 let invoice_request = InvoiceRequestTlvStreamRef {
641 chain: self.chain.as_ref(),
642 amount: Some(self.amount_msats),
644 quantity: self.quantity,
645 payer_id: Some(&self.payer_id),
646 payer_note: self.payer_note.as_ref(),
649 (payer, offer, invoice_request)
653 impl Writeable for Refund {
654 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
655 WithoutLength(&self.bytes).write(writer)
659 impl Writeable for RefundContents {
660 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
661 self.as_tlv_stream().write(writer)
665 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
667 type RefundTlvStreamRef<'a> = (
668 PayerTlvStreamRef<'a>,
669 OfferTlvStreamRef<'a>,
670 InvoiceRequestTlvStreamRef<'a>,
673 impl SeekReadable for RefundTlvStream {
674 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
675 let payer = SeekReadable::read(r)?;
676 let offer = SeekReadable::read(r)?;
677 let invoice_request = SeekReadable::read(r)?;
679 Ok((payer, offer, invoice_request))
683 impl Bech32Encode for Refund {
684 const BECH32_HRP: &'static str = "lnr";
687 impl FromStr for Refund {
688 type Err = Bolt12ParseError;
690 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
691 Refund::from_bech32_str(s)
695 impl TryFrom<Vec<u8>> for Refund {
696 type Error = Bolt12ParseError;
698 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
699 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
700 let ParsedMessage { bytes, tlv_stream } = refund;
701 let contents = RefundContents::try_from(tlv_stream)?;
703 Ok(Refund { bytes, contents })
707 impl TryFrom<RefundTlvStream> for RefundContents {
708 type Error = Bolt12SemanticError;
710 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
712 PayerTlvStream { metadata: payer_metadata },
714 chains, metadata, currency, amount: offer_amount, description,
715 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
717 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
720 let payer = match payer_metadata {
721 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
722 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
725 if metadata.is_some() {
726 return Err(Bolt12SemanticError::UnexpectedMetadata);
729 if chains.is_some() {
730 return Err(Bolt12SemanticError::UnexpectedChain);
733 if currency.is_some() || offer_amount.is_some() {
734 return Err(Bolt12SemanticError::UnexpectedAmount);
737 let description = match description {
738 None => return Err(Bolt12SemanticError::MissingDescription),
739 Some(description) => description,
742 if offer_features.is_some() {
743 return Err(Bolt12SemanticError::UnexpectedFeatures);
746 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
748 if quantity_max.is_some() {
749 return Err(Bolt12SemanticError::UnexpectedQuantity);
752 if node_id.is_some() {
753 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
756 let amount_msats = match amount {
757 None => return Err(Bolt12SemanticError::MissingAmount),
758 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
759 return Err(Bolt12SemanticError::InvalidAmount);
761 Some(amount_msats) => amount_msats,
764 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
766 let payer_id = match payer_id {
767 None => return Err(Bolt12SemanticError::MissingPayerId),
768 Some(payer_id) => payer_id,
772 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
773 quantity, payer_id, payer_note,
778 impl core::fmt::Display for Refund {
779 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
780 self.fmt_bech32_str(f)
786 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
788 use bitcoin::blockdata::constants::ChainHash;
789 use bitcoin::network::constants::Network;
790 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
791 use core::convert::TryFrom;
792 use core::time::Duration;
793 use crate::blinded_path::{BlindedHop, BlindedPath};
794 use crate::sign::KeyMaterial;
795 use crate::ln::channelmanager::PaymentId;
796 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
797 use crate::ln::inbound_payment::ExpandedKey;
798 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
799 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
800 use crate::offers::offer::OfferTlvStreamRef;
801 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
802 use crate::offers::payer::PayerTlvStreamRef;
803 use crate::offers::test_utils::*;
804 use crate::util::ser::{BigSize, Writeable};
805 use crate::util::string::PrintableString;
808 fn to_bytes(&self) -> Vec<u8>;
811 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
812 fn to_bytes(&self) -> Vec<u8> {
813 let mut buffer = Vec::new();
814 self.write(&mut buffer).unwrap();
820 fn builds_refund_with_defaults() {
821 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
824 let mut buffer = Vec::new();
825 refund.write(&mut buffer).unwrap();
827 assert_eq!(refund.bytes, buffer.as_slice());
828 assert_eq!(refund.payer_metadata(), &[1; 32]);
829 assert_eq!(refund.description(), PrintableString("foo"));
830 assert_eq!(refund.absolute_expiry(), None);
831 #[cfg(feature = "std")]
832 assert!(!refund.is_expired());
833 assert_eq!(refund.paths(), &[]);
834 assert_eq!(refund.issuer(), None);
835 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
836 assert_eq!(refund.amount_msats(), 1000);
837 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
838 assert_eq!(refund.payer_id(), payer_pubkey());
839 assert_eq!(refund.payer_note(), None);
842 refund.as_tlv_stream(),
844 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
850 description: Some(&String::from("foo")),
852 absolute_expiry: None,
858 InvoiceRequestTlvStreamRef {
863 payer_id: Some(&payer_pubkey()),
869 if let Err(e) = Refund::try_from(buffer) {
870 panic!("error parsing refund: {:?}", e);
875 fn fails_building_refund_with_invalid_amount() {
876 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
877 Ok(_) => panic!("expected error"),
878 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
883 fn builds_refund_with_metadata_derived() {
884 let desc = "foo".to_string();
885 let node_id = payer_pubkey();
886 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
887 let entropy = FixedEntropy {};
888 let secp_ctx = Secp256k1::new();
889 let payment_id = PaymentId([1; 32]);
891 let refund = RefundBuilder
892 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
895 assert_eq!(refund.payer_id(), node_id);
897 // Fails verification with altered fields
899 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
902 .sign(recipient_sign).unwrap();
903 match invoice.verify(&expanded_key, &secp_ctx) {
904 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
905 Err(()) => panic!("verification failed"),
908 let mut tlv_stream = refund.as_tlv_stream();
909 tlv_stream.2.amount = Some(2000);
911 let mut encoded_refund = Vec::new();
912 tlv_stream.write(&mut encoded_refund).unwrap();
914 let invoice = Refund::try_from(encoded_refund).unwrap()
915 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
918 .sign(recipient_sign).unwrap();
919 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
921 // Fails verification with altered metadata
922 let mut tlv_stream = refund.as_tlv_stream();
923 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
924 tlv_stream.0.metadata = Some(&metadata);
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());
938 fn builds_refund_with_derived_payer_id() {
939 let desc = "foo".to_string();
940 let node_id = payer_pubkey();
941 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
942 let entropy = FixedEntropy {};
943 let secp_ctx = Secp256k1::new();
944 let payment_id = PaymentId([1; 32]);
946 let blinded_path = BlindedPath {
947 introduction_node_id: pubkey(40),
948 blinding_point: pubkey(41),
950 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
951 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
955 let refund = RefundBuilder
956 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
960 assert_ne!(refund.payer_id(), node_id);
963 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
966 .sign(recipient_sign).unwrap();
967 match invoice.verify(&expanded_key, &secp_ctx) {
968 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
969 Err(()) => panic!("verification failed"),
972 // Fails verification with altered fields
973 let mut tlv_stream = refund.as_tlv_stream();
974 tlv_stream.2.amount = Some(2000);
976 let mut encoded_refund = Vec::new();
977 tlv_stream.write(&mut encoded_refund).unwrap();
979 let invoice = Refund::try_from(encoded_refund).unwrap()
980 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
983 .sign(recipient_sign).unwrap();
984 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
986 // Fails verification with altered payer_id
987 let mut tlv_stream = refund.as_tlv_stream();
988 let payer_id = pubkey(1);
989 tlv_stream.2.payer_id = Some(&payer_id);
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());
1003 fn builds_refund_with_absolute_expiry() {
1004 let future_expiry = Duration::from_secs(u64::max_value());
1005 let past_expiry = Duration::from_secs(0);
1006 let now = future_expiry - Duration::from_secs(1_000);
1008 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1009 .absolute_expiry(future_expiry)
1012 let (_, tlv_stream, _) = refund.as_tlv_stream();
1013 #[cfg(feature = "std")]
1014 assert!(!refund.is_expired());
1015 assert!(!refund.is_expired_no_std(now));
1016 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1017 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1019 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1020 .absolute_expiry(future_expiry)
1021 .absolute_expiry(past_expiry)
1024 let (_, tlv_stream, _) = refund.as_tlv_stream();
1025 #[cfg(feature = "std")]
1026 assert!(refund.is_expired());
1027 assert!(refund.is_expired_no_std(now));
1028 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1029 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1033 fn builds_refund_with_paths() {
1036 introduction_node_id: pubkey(40),
1037 blinding_point: pubkey(41),
1039 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1040 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1044 introduction_node_id: pubkey(40),
1045 blinding_point: pubkey(41),
1047 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1048 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1053 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1054 .path(paths[0].clone())
1055 .path(paths[1].clone())
1058 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1059 assert_eq!(refund.paths(), paths.as_slice());
1060 assert_eq!(refund.payer_id(), pubkey(42));
1061 assert_ne!(pubkey(42), pubkey(44));
1062 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1063 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1067 fn builds_refund_with_issuer() {
1068 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1069 .issuer("bar".into())
1072 let (_, tlv_stream, _) = refund.as_tlv_stream();
1073 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1074 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1076 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1077 .issuer("bar".into())
1078 .issuer("baz".into())
1081 let (_, tlv_stream, _) = refund.as_tlv_stream();
1082 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1083 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1087 fn builds_refund_with_chain() {
1088 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1089 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1091 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1092 .chain(Network::Bitcoin)
1094 let (_, _, tlv_stream) = refund.as_tlv_stream();
1095 assert_eq!(refund.chain(), mainnet);
1096 assert_eq!(tlv_stream.chain, None);
1098 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1099 .chain(Network::Testnet)
1101 let (_, _, tlv_stream) = refund.as_tlv_stream();
1102 assert_eq!(refund.chain(), testnet);
1103 assert_eq!(tlv_stream.chain, Some(&testnet));
1105 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1106 .chain(Network::Regtest)
1107 .chain(Network::Testnet)
1109 let (_, _, tlv_stream) = refund.as_tlv_stream();
1110 assert_eq!(refund.chain(), testnet);
1111 assert_eq!(tlv_stream.chain, Some(&testnet));
1115 fn builds_refund_with_quantity() {
1116 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1119 let (_, _, tlv_stream) = refund.as_tlv_stream();
1120 assert_eq!(refund.quantity(), Some(10));
1121 assert_eq!(tlv_stream.quantity, Some(10));
1123 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1127 let (_, _, tlv_stream) = refund.as_tlv_stream();
1128 assert_eq!(refund.quantity(), Some(1));
1129 assert_eq!(tlv_stream.quantity, Some(1));
1133 fn builds_refund_with_payer_note() {
1134 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1135 .payer_note("bar".into())
1137 let (_, _, tlv_stream) = refund.as_tlv_stream();
1138 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1139 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1141 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1142 .payer_note("bar".into())
1143 .payer_note("baz".into())
1145 let (_, _, tlv_stream) = refund.as_tlv_stream();
1146 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1147 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1151 fn fails_responding_with_unknown_required_features() {
1152 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1153 .features_unchecked(InvoiceRequestFeatures::unknown())
1155 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1157 Ok(_) => panic!("expected error"),
1158 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1163 fn parses_refund_with_metadata() {
1164 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1166 if let Err(e) = refund.to_string().parse::<Refund>() {
1167 panic!("error parsing refund: {:?}", e);
1170 let mut tlv_stream = refund.as_tlv_stream();
1171 tlv_stream.0.metadata = None;
1173 match Refund::try_from(tlv_stream.to_bytes()) {
1174 Ok(_) => panic!("expected error"),
1176 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1182 fn parses_refund_with_description() {
1183 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1185 if let Err(e) = refund.to_string().parse::<Refund>() {
1186 panic!("error parsing refund: {:?}", e);
1189 let mut tlv_stream = refund.as_tlv_stream();
1190 tlv_stream.1.description = None;
1192 match Refund::try_from(tlv_stream.to_bytes()) {
1193 Ok(_) => panic!("expected error"),
1195 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1201 fn parses_refund_with_amount() {
1202 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1204 if let Err(e) = refund.to_string().parse::<Refund>() {
1205 panic!("error parsing refund: {:?}", e);
1208 let mut tlv_stream = refund.as_tlv_stream();
1209 tlv_stream.2.amount = None;
1211 match Refund::try_from(tlv_stream.to_bytes()) {
1212 Ok(_) => panic!("expected error"),
1214 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1218 let mut tlv_stream = refund.as_tlv_stream();
1219 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1221 match Refund::try_from(tlv_stream.to_bytes()) {
1222 Ok(_) => panic!("expected error"),
1224 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1230 fn parses_refund_with_payer_id() {
1231 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1233 if let Err(e) = refund.to_string().parse::<Refund>() {
1234 panic!("error parsing refund: {:?}", e);
1237 let mut tlv_stream = refund.as_tlv_stream();
1238 tlv_stream.2.payer_id = None;
1240 match Refund::try_from(tlv_stream.to_bytes()) {
1241 Ok(_) => panic!("expected error"),
1243 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1249 fn parses_refund_with_optional_fields() {
1250 let past_expiry = Duration::from_secs(0);
1253 introduction_node_id: pubkey(40),
1254 blinding_point: pubkey(41),
1256 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1257 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1261 introduction_node_id: pubkey(40),
1262 blinding_point: pubkey(41),
1264 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1265 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1270 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1271 .absolute_expiry(past_expiry)
1272 .issuer("bar".into())
1273 .path(paths[0].clone())
1274 .path(paths[1].clone())
1275 .chain(Network::Testnet)
1276 .features_unchecked(InvoiceRequestFeatures::unknown())
1278 .payer_note("baz".into())
1281 match refund.to_string().parse::<Refund>() {
1283 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1284 #[cfg(feature = "std")]
1285 assert!(refund.is_expired());
1286 assert_eq!(refund.paths(), &paths[..]);
1287 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1288 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1289 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1290 assert_eq!(refund.quantity(), Some(10));
1291 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1293 Err(e) => panic!("error parsing refund: {:?}", e),
1298 fn fails_parsing_refund_with_unexpected_fields() {
1299 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1301 if let Err(e) = refund.to_string().parse::<Refund>() {
1302 panic!("error parsing refund: {:?}", e);
1305 let metadata = vec![42; 32];
1306 let mut tlv_stream = refund.as_tlv_stream();
1307 tlv_stream.1.metadata = Some(&metadata);
1309 match Refund::try_from(tlv_stream.to_bytes()) {
1310 Ok(_) => panic!("expected error"),
1312 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1316 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1317 let mut tlv_stream = refund.as_tlv_stream();
1318 tlv_stream.1.chains = Some(&chains);
1320 match Refund::try_from(tlv_stream.to_bytes()) {
1321 Ok(_) => panic!("expected error"),
1323 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1327 let mut tlv_stream = refund.as_tlv_stream();
1328 tlv_stream.1.currency = Some(&b"USD");
1329 tlv_stream.1.amount = Some(1000);
1331 match Refund::try_from(tlv_stream.to_bytes()) {
1332 Ok(_) => panic!("expected error"),
1334 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1338 let features = OfferFeatures::unknown();
1339 let mut tlv_stream = refund.as_tlv_stream();
1340 tlv_stream.1.features = Some(&features);
1342 match Refund::try_from(tlv_stream.to_bytes()) {
1343 Ok(_) => panic!("expected error"),
1345 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1349 let mut tlv_stream = refund.as_tlv_stream();
1350 tlv_stream.1.quantity_max = Some(10);
1352 match Refund::try_from(tlv_stream.to_bytes()) {
1353 Ok(_) => panic!("expected error"),
1355 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1359 let node_id = payer_pubkey();
1360 let mut tlv_stream = refund.as_tlv_stream();
1361 tlv_stream.1.node_id = Some(&node_id);
1363 match Refund::try_from(tlv_stream.to_bytes()) {
1364 Ok(_) => panic!("expected error"),
1366 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1372 fn fails_parsing_refund_with_extra_tlv_records() {
1373 let secp_ctx = Secp256k1::new();
1374 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1375 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1378 let mut encoded_refund = Vec::new();
1379 refund.write(&mut encoded_refund).unwrap();
1380 BigSize(1002).write(&mut encoded_refund).unwrap();
1381 BigSize(32).write(&mut encoded_refund).unwrap();
1382 [42u8; 32].write(&mut encoded_refund).unwrap();
1384 match Refund::try_from(encoded_refund) {
1385 Ok(_) => panic!("expected error"),
1386 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),