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)]
321 pub(super) bytes: Vec<u8>,
322 pub(super) contents: RefundContents,
325 /// The contents of a [`Refund`], which may be shared with an [`Bolt12Invoice`].
327 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
328 #[derive(Clone, Debug)]
329 #[cfg_attr(test, derive(PartialEq))]
330 pub(super) struct RefundContents {
331 payer: PayerContents,
334 absolute_expiry: Option<Duration>,
335 issuer: Option<String>,
336 paths: Option<Vec<BlindedPath>>,
337 // invoice_request fields
338 chain: Option<ChainHash>,
340 features: InvoiceRequestFeatures,
341 quantity: Option<u64>,
343 payer_note: Option<String>,
347 /// A complete description of the purpose of the refund. Intended to be displayed to the user
348 /// but with the caveat that it has not been verified in any way.
349 pub fn description(&self) -> PrintableString {
350 self.contents.description()
353 /// Duration since the Unix epoch when an invoice should no longer be sent.
355 /// If `None`, the refund does not expire.
356 pub fn absolute_expiry(&self) -> Option<Duration> {
357 self.contents.absolute_expiry()
360 /// Whether the refund has expired.
361 #[cfg(feature = "std")]
362 pub fn is_expired(&self) -> bool {
363 self.contents.is_expired()
366 /// Whether the refund has expired given the duration since the Unix epoch.
367 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
368 self.contents.is_expired_no_std(duration_since_epoch)
371 /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
372 /// displayed to the user but with the caveat that it has not been verified in any way.
373 pub fn issuer(&self) -> Option<PrintableString> {
374 self.contents.issuer()
377 /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
378 /// privacy by obfuscating its node id.
379 pub fn paths(&self) -> &[BlindedPath] {
380 self.contents.paths()
383 /// An unpredictable series of bytes, typically containing information about the derivation of
386 /// [`payer_id`]: Self::payer_id
387 pub fn payer_metadata(&self) -> &[u8] {
388 self.contents.metadata()
391 /// A chain that the refund is valid for.
392 pub fn chain(&self) -> ChainHash {
393 self.contents.chain()
396 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
398 /// [`chain`]: Self::chain
399 pub fn amount_msats(&self) -> u64 {
400 self.contents.amount_msats()
403 /// Features pertaining to requesting an invoice.
404 pub fn features(&self) -> &InvoiceRequestFeatures {
405 &self.contents.features()
408 /// The quantity of an item that refund is for.
409 pub fn quantity(&self) -> Option<u64> {
410 self.contents.quantity()
413 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
414 /// transient pubkey.
416 /// [`paths`]: Self::paths
417 pub fn payer_id(&self) -> PublicKey {
418 self.contents.payer_id()
421 /// Payer provided note to include in the invoice.
422 pub fn payer_note(&self) -> Option<PrintableString> {
423 self.contents.payer_note()
426 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields and using the
427 /// [`Duration`] since [`std::time::SystemTime::UNIX_EPOCH`] as the creation time.
429 /// See [`Refund::respond_with_no_std`] for further details where the aforementioned creation
430 /// time is used for the `created_at` parameter.
432 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
434 /// [`Duration`]: core::time::Duration
435 #[cfg(feature = "std")]
437 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
438 signing_pubkey: PublicKey,
439 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
440 let created_at = std::time::SystemTime::now()
441 .duration_since(std::time::SystemTime::UNIX_EPOCH)
442 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
444 self.respond_with_no_std(payment_paths, payment_hash, signing_pubkey, created_at)
447 /// Creates an [`InvoiceBuilder`] for the refund with the given required fields.
449 /// Unless [`InvoiceBuilder::relative_expiry`] is set, the invoice will expire two hours after
450 /// `created_at`, which is used to set [`Bolt12Invoice::created_at`]. Useful for `no-std` builds
451 /// where [`std::time::SystemTime`] is not available.
453 /// The caller is expected to remember the preimage of `payment_hash` in order to
454 /// claim a payment for the invoice.
456 /// The `signing_pubkey` is required to sign the invoice since refunds are not in response to an
457 /// offer, which does have a `signing_pubkey`.
459 /// The `payment_paths` parameter is useful for maintaining the payment recipient's privacy. It
460 /// must contain one or more elements ordered from most-preferred to least-preferred, if there's
461 /// a preference. Note, however, that any privacy is lost if a public node id is used for
462 /// `signing_pubkey`.
464 /// Errors if the request contains unknown required features.
466 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
468 /// [`Bolt12Invoice::created_at`]: crate::offers::invoice::Bolt12Invoice::created_at
469 pub fn respond_with_no_std(
470 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
471 signing_pubkey: PublicKey, created_at: Duration
472 ) -> Result<InvoiceBuilder<ExplicitSigningPubkey>, Bolt12SemanticError> {
473 if self.features().requires_unknown_bits() {
474 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
477 InvoiceBuilder::for_refund(self, payment_paths, created_at, payment_hash, signing_pubkey)
480 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
481 /// derived signing keys to sign the [`Bolt12Invoice`].
483 /// See [`Refund::respond_with`] for further details.
485 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
487 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
488 #[cfg(feature = "std")]
489 pub fn respond_using_derived_keys<ES: Deref>(
490 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
491 expanded_key: &ExpandedKey, entropy_source: ES
492 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
494 ES::Target: EntropySource,
496 let created_at = std::time::SystemTime::now()
497 .duration_since(std::time::SystemTime::UNIX_EPOCH)
498 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
500 self.respond_using_derived_keys_no_std(
501 payment_paths, payment_hash, created_at, expanded_key, entropy_source
505 /// Creates an [`InvoiceBuilder`] for the refund using the given required fields and that uses
506 /// derived signing keys to sign the [`Bolt12Invoice`].
508 /// See [`Refund::respond_with_no_std`] for further details.
510 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
512 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
513 pub fn respond_using_derived_keys_no_std<ES: Deref>(
514 &self, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>, payment_hash: PaymentHash,
515 created_at: core::time::Duration, expanded_key: &ExpandedKey, entropy_source: ES
516 ) -> Result<InvoiceBuilder<DerivedSigningPubkey>, Bolt12SemanticError>
518 ES::Target: EntropySource,
520 if self.features().requires_unknown_bits() {
521 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
524 let nonce = Nonce::from_entropy_source(entropy_source);
525 let keys = signer::derive_keys(nonce, expanded_key);
526 InvoiceBuilder::for_refund_using_keys(self, payment_paths, created_at, payment_hash, keys)
530 fn as_tlv_stream(&self) -> RefundTlvStreamRef {
531 self.contents.as_tlv_stream()
535 impl AsRef<[u8]> for Refund {
536 fn as_ref(&self) -> &[u8] {
541 impl PartialEq for Refund {
542 fn eq(&self, other: &Self) -> bool {
543 self.bytes.eq(&other.bytes)
547 impl Eq for Refund {}
549 impl RefundContents {
550 pub fn description(&self) -> PrintableString {
551 PrintableString(&self.description)
554 pub fn absolute_expiry(&self) -> Option<Duration> {
558 #[cfg(feature = "std")]
559 pub(super) fn is_expired(&self) -> bool {
560 SystemTime::UNIX_EPOCH
562 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
566 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
568 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
572 pub fn issuer(&self) -> Option<PrintableString> {
573 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
576 pub fn paths(&self) -> &[BlindedPath] {
577 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
580 pub(super) fn metadata(&self) -> &[u8] {
581 self.payer.0.as_bytes().map(|bytes| bytes.as_slice()).unwrap_or(&[])
584 pub(super) fn chain(&self) -> ChainHash {
585 self.chain.unwrap_or_else(|| self.implied_chain())
588 pub fn implied_chain(&self) -> ChainHash {
589 ChainHash::using_genesis_block(Network::Bitcoin)
592 pub fn amount_msats(&self) -> u64 {
596 /// Features pertaining to requesting an invoice.
597 pub fn features(&self) -> &InvoiceRequestFeatures {
601 /// The quantity of an item that refund is for.
602 pub fn quantity(&self) -> Option<u64> {
606 /// A public node id to send to in the case where there are no [`paths`]. Otherwise, a possibly
607 /// transient pubkey.
609 /// [`paths`]: Self::paths
610 pub fn payer_id(&self) -> PublicKey {
614 /// Payer provided note to include in the invoice.
615 pub fn payer_note(&self) -> Option<PrintableString> {
616 self.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
619 pub(super) fn derives_keys(&self) -> bool {
620 self.payer.0.derives_payer_keys()
623 pub(super) fn as_tlv_stream(&self) -> RefundTlvStreamRef {
624 let payer = PayerTlvStreamRef {
625 metadata: self.payer.0.as_bytes(),
628 let offer = OfferTlvStreamRef {
633 description: Some(&self.description),
635 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
636 paths: self.paths.as_ref(),
637 issuer: self.issuer.as_ref(),
643 if self.features == InvoiceRequestFeatures::empty() { None }
644 else { Some(&self.features) }
647 let invoice_request = InvoiceRequestTlvStreamRef {
648 chain: self.chain.as_ref(),
649 amount: Some(self.amount_msats),
651 quantity: self.quantity,
652 payer_id: Some(&self.payer_id),
653 payer_note: self.payer_note.as_ref(),
656 (payer, offer, invoice_request)
660 impl Writeable for Refund {
661 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
662 WithoutLength(&self.bytes).write(writer)
666 impl Writeable for RefundContents {
667 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
668 self.as_tlv_stream().write(writer)
672 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
674 type RefundTlvStreamRef<'a> = (
675 PayerTlvStreamRef<'a>,
676 OfferTlvStreamRef<'a>,
677 InvoiceRequestTlvStreamRef<'a>,
680 impl SeekReadable for RefundTlvStream {
681 fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
682 let payer = SeekReadable::read(r)?;
683 let offer = SeekReadable::read(r)?;
684 let invoice_request = SeekReadable::read(r)?;
686 Ok((payer, offer, invoice_request))
690 impl Bech32Encode for Refund {
691 const BECH32_HRP: &'static str = "lnr";
694 impl FromStr for Refund {
695 type Err = Bolt12ParseError;
697 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
698 Refund::from_bech32_str(s)
702 impl TryFrom<Vec<u8>> for Refund {
703 type Error = Bolt12ParseError;
705 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
706 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
707 let ParsedMessage { bytes, tlv_stream } = refund;
708 let contents = RefundContents::try_from(tlv_stream)?;
710 Ok(Refund { bytes, contents })
714 impl TryFrom<RefundTlvStream> for RefundContents {
715 type Error = Bolt12SemanticError;
717 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
719 PayerTlvStream { metadata: payer_metadata },
721 chains, metadata, currency, amount: offer_amount, description,
722 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
724 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
727 let payer = match payer_metadata {
728 None => return Err(Bolt12SemanticError::MissingPayerMetadata),
729 Some(metadata) => PayerContents(Metadata::Bytes(metadata)),
732 if metadata.is_some() {
733 return Err(Bolt12SemanticError::UnexpectedMetadata);
736 if chains.is_some() {
737 return Err(Bolt12SemanticError::UnexpectedChain);
740 if currency.is_some() || offer_amount.is_some() {
741 return Err(Bolt12SemanticError::UnexpectedAmount);
744 let description = match description {
745 None => return Err(Bolt12SemanticError::MissingDescription),
746 Some(description) => description,
749 if offer_features.is_some() {
750 return Err(Bolt12SemanticError::UnexpectedFeatures);
753 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
755 if quantity_max.is_some() {
756 return Err(Bolt12SemanticError::UnexpectedQuantity);
759 if node_id.is_some() {
760 return Err(Bolt12SemanticError::UnexpectedSigningPubkey);
763 let amount_msats = match amount {
764 None => return Err(Bolt12SemanticError::MissingAmount),
765 Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
766 return Err(Bolt12SemanticError::InvalidAmount);
768 Some(amount_msats) => amount_msats,
771 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
773 let payer_id = match payer_id {
774 None => return Err(Bolt12SemanticError::MissingPayerId),
775 Some(payer_id) => payer_id,
779 payer, description, absolute_expiry, issuer, paths, chain, amount_msats, features,
780 quantity, payer_id, payer_note,
785 impl core::fmt::Display for Refund {
786 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
787 self.fmt_bech32_str(f)
793 use super::{Refund, RefundBuilder, RefundTlvStreamRef};
795 use bitcoin::blockdata::constants::ChainHash;
796 use bitcoin::network::constants::Network;
797 use bitcoin::secp256k1::{KeyPair, Secp256k1, SecretKey};
798 use core::convert::TryFrom;
799 use core::time::Duration;
800 use crate::blinded_path::{BlindedHop, BlindedPath};
801 use crate::sign::KeyMaterial;
802 use crate::ln::channelmanager::PaymentId;
803 use crate::ln::features::{InvoiceRequestFeatures, OfferFeatures};
804 use crate::ln::inbound_payment::ExpandedKey;
805 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
806 use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
807 use crate::offers::offer::OfferTlvStreamRef;
808 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
809 use crate::offers::payer::PayerTlvStreamRef;
810 use crate::offers::test_utils::*;
811 use crate::util::ser::{BigSize, Writeable};
812 use crate::util::string::PrintableString;
815 fn to_bytes(&self) -> Vec<u8>;
818 impl<'a> ToBytes for RefundTlvStreamRef<'a> {
819 fn to_bytes(&self) -> Vec<u8> {
820 let mut buffer = Vec::new();
821 self.write(&mut buffer).unwrap();
827 fn builds_refund_with_defaults() {
828 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
831 let mut buffer = Vec::new();
832 refund.write(&mut buffer).unwrap();
834 assert_eq!(refund.bytes, buffer.as_slice());
835 assert_eq!(refund.payer_metadata(), &[1; 32]);
836 assert_eq!(refund.description(), PrintableString("foo"));
837 assert_eq!(refund.absolute_expiry(), None);
838 #[cfg(feature = "std")]
839 assert!(!refund.is_expired());
840 assert_eq!(refund.paths(), &[]);
841 assert_eq!(refund.issuer(), None);
842 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Bitcoin));
843 assert_eq!(refund.amount_msats(), 1000);
844 assert_eq!(refund.features(), &InvoiceRequestFeatures::empty());
845 assert_eq!(refund.payer_id(), payer_pubkey());
846 assert_eq!(refund.payer_note(), None);
849 refund.as_tlv_stream(),
851 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
857 description: Some(&String::from("foo")),
859 absolute_expiry: None,
865 InvoiceRequestTlvStreamRef {
870 payer_id: Some(&payer_pubkey()),
876 if let Err(e) = Refund::try_from(buffer) {
877 panic!("error parsing refund: {:?}", e);
882 fn fails_building_refund_with_invalid_amount() {
883 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), MAX_VALUE_MSAT + 1) {
884 Ok(_) => panic!("expected error"),
885 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
890 fn builds_refund_with_metadata_derived() {
891 let desc = "foo".to_string();
892 let node_id = payer_pubkey();
893 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
894 let entropy = FixedEntropy {};
895 let secp_ctx = Secp256k1::new();
896 let payment_id = PaymentId([1; 32]);
898 let refund = RefundBuilder
899 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
902 assert_eq!(refund.payer_id(), node_id);
904 // Fails verification with altered fields
906 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
909 .sign(recipient_sign).unwrap();
910 match invoice.verify(&expanded_key, &secp_ctx) {
911 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
912 Err(()) => panic!("verification failed"),
915 let mut tlv_stream = refund.as_tlv_stream();
916 tlv_stream.2.amount = Some(2000);
918 let mut encoded_refund = Vec::new();
919 tlv_stream.write(&mut encoded_refund).unwrap();
921 let invoice = Refund::try_from(encoded_refund).unwrap()
922 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
925 .sign(recipient_sign).unwrap();
926 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
928 // Fails verification with altered metadata
929 let mut tlv_stream = refund.as_tlv_stream();
930 let metadata = tlv_stream.0.metadata.unwrap().iter().copied().rev().collect();
931 tlv_stream.0.metadata = Some(&metadata);
933 let mut encoded_refund = Vec::new();
934 tlv_stream.write(&mut encoded_refund).unwrap();
936 let invoice = Refund::try_from(encoded_refund).unwrap()
937 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
940 .sign(recipient_sign).unwrap();
941 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
945 fn builds_refund_with_derived_payer_id() {
946 let desc = "foo".to_string();
947 let node_id = payer_pubkey();
948 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
949 let entropy = FixedEntropy {};
950 let secp_ctx = Secp256k1::new();
951 let payment_id = PaymentId([1; 32]);
953 let blinded_path = BlindedPath {
954 introduction_node_id: pubkey(40),
955 blinding_point: pubkey(41),
957 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
958 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
962 let refund = RefundBuilder
963 ::deriving_payer_id(desc, node_id, &expanded_key, &entropy, &secp_ctx, 1000, payment_id)
967 assert_ne!(refund.payer_id(), node_id);
970 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
973 .sign(recipient_sign).unwrap();
974 match invoice.verify(&expanded_key, &secp_ctx) {
975 Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
976 Err(()) => panic!("verification failed"),
979 // Fails verification with altered fields
980 let mut tlv_stream = refund.as_tlv_stream();
981 tlv_stream.2.amount = Some(2000);
983 let mut encoded_refund = Vec::new();
984 tlv_stream.write(&mut encoded_refund).unwrap();
986 let invoice = Refund::try_from(encoded_refund).unwrap()
987 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
990 .sign(recipient_sign).unwrap();
991 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
993 // Fails verification with altered payer_id
994 let mut tlv_stream = refund.as_tlv_stream();
995 let payer_id = pubkey(1);
996 tlv_stream.2.payer_id = Some(&payer_id);
998 let mut encoded_refund = Vec::new();
999 tlv_stream.write(&mut encoded_refund).unwrap();
1001 let invoice = Refund::try_from(encoded_refund).unwrap()
1002 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1005 .sign(recipient_sign).unwrap();
1006 assert!(invoice.verify(&expanded_key, &secp_ctx).is_err());
1010 fn builds_refund_with_absolute_expiry() {
1011 let future_expiry = Duration::from_secs(u64::max_value());
1012 let past_expiry = Duration::from_secs(0);
1013 let now = future_expiry - Duration::from_secs(1_000);
1015 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1016 .absolute_expiry(future_expiry)
1019 let (_, tlv_stream, _) = refund.as_tlv_stream();
1020 #[cfg(feature = "std")]
1021 assert!(!refund.is_expired());
1022 assert!(!refund.is_expired_no_std(now));
1023 assert_eq!(refund.absolute_expiry(), Some(future_expiry));
1024 assert_eq!(tlv_stream.absolute_expiry, Some(future_expiry.as_secs()));
1026 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1027 .absolute_expiry(future_expiry)
1028 .absolute_expiry(past_expiry)
1031 let (_, tlv_stream, _) = refund.as_tlv_stream();
1032 #[cfg(feature = "std")]
1033 assert!(refund.is_expired());
1034 assert!(refund.is_expired_no_std(now));
1035 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1036 assert_eq!(tlv_stream.absolute_expiry, Some(past_expiry.as_secs()));
1040 fn builds_refund_with_paths() {
1043 introduction_node_id: pubkey(40),
1044 blinding_point: pubkey(41),
1046 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1047 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1051 introduction_node_id: pubkey(40),
1052 blinding_point: pubkey(41),
1054 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1055 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1060 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1061 .path(paths[0].clone())
1062 .path(paths[1].clone())
1065 let (_, offer_tlv_stream, invoice_request_tlv_stream) = refund.as_tlv_stream();
1066 assert_eq!(refund.paths(), paths.as_slice());
1067 assert_eq!(refund.payer_id(), pubkey(42));
1068 assert_ne!(pubkey(42), pubkey(44));
1069 assert_eq!(offer_tlv_stream.paths, Some(&paths));
1070 assert_eq!(invoice_request_tlv_stream.payer_id, Some(&pubkey(42)));
1074 fn builds_refund_with_issuer() {
1075 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1076 .issuer("bar".into())
1079 let (_, tlv_stream, _) = refund.as_tlv_stream();
1080 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1081 assert_eq!(tlv_stream.issuer, Some(&String::from("bar")));
1083 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1084 .issuer("bar".into())
1085 .issuer("baz".into())
1088 let (_, tlv_stream, _) = refund.as_tlv_stream();
1089 assert_eq!(refund.issuer(), Some(PrintableString("baz")));
1090 assert_eq!(tlv_stream.issuer, Some(&String::from("baz")));
1094 fn builds_refund_with_chain() {
1095 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1096 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1098 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1099 .chain(Network::Bitcoin)
1101 let (_, _, tlv_stream) = refund.as_tlv_stream();
1102 assert_eq!(refund.chain(), mainnet);
1103 assert_eq!(tlv_stream.chain, None);
1105 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1106 .chain(Network::Testnet)
1108 let (_, _, tlv_stream) = refund.as_tlv_stream();
1109 assert_eq!(refund.chain(), testnet);
1110 assert_eq!(tlv_stream.chain, Some(&testnet));
1112 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1113 .chain(Network::Regtest)
1114 .chain(Network::Testnet)
1116 let (_, _, tlv_stream) = refund.as_tlv_stream();
1117 assert_eq!(refund.chain(), testnet);
1118 assert_eq!(tlv_stream.chain, Some(&testnet));
1122 fn builds_refund_with_quantity() {
1123 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1126 let (_, _, tlv_stream) = refund.as_tlv_stream();
1127 assert_eq!(refund.quantity(), Some(10));
1128 assert_eq!(tlv_stream.quantity, Some(10));
1130 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1134 let (_, _, tlv_stream) = refund.as_tlv_stream();
1135 assert_eq!(refund.quantity(), Some(1));
1136 assert_eq!(tlv_stream.quantity, Some(1));
1140 fn builds_refund_with_payer_note() {
1141 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1142 .payer_note("bar".into())
1144 let (_, _, tlv_stream) = refund.as_tlv_stream();
1145 assert_eq!(refund.payer_note(), Some(PrintableString("bar")));
1146 assert_eq!(tlv_stream.payer_note, Some(&String::from("bar")));
1148 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1149 .payer_note("bar".into())
1150 .payer_note("baz".into())
1152 let (_, _, tlv_stream) = refund.as_tlv_stream();
1153 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1154 assert_eq!(tlv_stream.payer_note, Some(&String::from("baz")));
1158 fn fails_responding_with_unknown_required_features() {
1159 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1160 .features_unchecked(InvoiceRequestFeatures::unknown())
1162 .respond_with_no_std(payment_paths(), payment_hash(), recipient_pubkey(), now())
1164 Ok(_) => panic!("expected error"),
1165 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1170 fn parses_refund_with_metadata() {
1171 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1173 if let Err(e) = refund.to_string().parse::<Refund>() {
1174 panic!("error parsing refund: {:?}", e);
1177 let mut tlv_stream = refund.as_tlv_stream();
1178 tlv_stream.0.metadata = None;
1180 match Refund::try_from(tlv_stream.to_bytes()) {
1181 Ok(_) => panic!("expected error"),
1183 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerMetadata));
1189 fn parses_refund_with_description() {
1190 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1192 if let Err(e) = refund.to_string().parse::<Refund>() {
1193 panic!("error parsing refund: {:?}", e);
1196 let mut tlv_stream = refund.as_tlv_stream();
1197 tlv_stream.1.description = None;
1199 match Refund::try_from(tlv_stream.to_bytes()) {
1200 Ok(_) => panic!("expected error"),
1202 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1208 fn parses_refund_with_amount() {
1209 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1211 if let Err(e) = refund.to_string().parse::<Refund>() {
1212 panic!("error parsing refund: {:?}", e);
1215 let mut tlv_stream = refund.as_tlv_stream();
1216 tlv_stream.2.amount = None;
1218 match Refund::try_from(tlv_stream.to_bytes()) {
1219 Ok(_) => panic!("expected error"),
1221 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount));
1225 let mut tlv_stream = refund.as_tlv_stream();
1226 tlv_stream.2.amount = Some(MAX_VALUE_MSAT + 1);
1228 match Refund::try_from(tlv_stream.to_bytes()) {
1229 Ok(_) => panic!("expected error"),
1231 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount));
1237 fn parses_refund_with_payer_id() {
1238 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1240 if let Err(e) = refund.to_string().parse::<Refund>() {
1241 panic!("error parsing refund: {:?}", e);
1244 let mut tlv_stream = refund.as_tlv_stream();
1245 tlv_stream.2.payer_id = None;
1247 match Refund::try_from(tlv_stream.to_bytes()) {
1248 Ok(_) => panic!("expected error"),
1250 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPayerId));
1256 fn parses_refund_with_optional_fields() {
1257 let past_expiry = Duration::from_secs(0);
1260 introduction_node_id: pubkey(40),
1261 blinding_point: pubkey(41),
1263 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1264 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1268 introduction_node_id: pubkey(40),
1269 blinding_point: pubkey(41),
1271 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1272 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1277 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1278 .absolute_expiry(past_expiry)
1279 .issuer("bar".into())
1280 .path(paths[0].clone())
1281 .path(paths[1].clone())
1282 .chain(Network::Testnet)
1283 .features_unchecked(InvoiceRequestFeatures::unknown())
1285 .payer_note("baz".into())
1288 match refund.to_string().parse::<Refund>() {
1290 assert_eq!(refund.absolute_expiry(), Some(past_expiry));
1291 #[cfg(feature = "std")]
1292 assert!(refund.is_expired());
1293 assert_eq!(refund.paths(), &paths[..]);
1294 assert_eq!(refund.issuer(), Some(PrintableString("bar")));
1295 assert_eq!(refund.chain(), ChainHash::using_genesis_block(Network::Testnet));
1296 assert_eq!(refund.features(), &InvoiceRequestFeatures::unknown());
1297 assert_eq!(refund.quantity(), Some(10));
1298 assert_eq!(refund.payer_note(), Some(PrintableString("baz")));
1300 Err(e) => panic!("error parsing refund: {:?}", e),
1305 fn fails_parsing_refund_with_unexpected_fields() {
1306 let refund = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1308 if let Err(e) = refund.to_string().parse::<Refund>() {
1309 panic!("error parsing refund: {:?}", e);
1312 let metadata = vec![42; 32];
1313 let mut tlv_stream = refund.as_tlv_stream();
1314 tlv_stream.1.metadata = Some(&metadata);
1316 match Refund::try_from(tlv_stream.to_bytes()) {
1317 Ok(_) => panic!("expected error"),
1319 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedMetadata));
1323 let chains = vec![ChainHash::using_genesis_block(Network::Testnet)];
1324 let mut tlv_stream = refund.as_tlv_stream();
1325 tlv_stream.1.chains = Some(&chains);
1327 match Refund::try_from(tlv_stream.to_bytes()) {
1328 Ok(_) => panic!("expected error"),
1330 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedChain));
1334 let mut tlv_stream = refund.as_tlv_stream();
1335 tlv_stream.1.currency = Some(&b"USD");
1336 tlv_stream.1.amount = Some(1000);
1338 match Refund::try_from(tlv_stream.to_bytes()) {
1339 Ok(_) => panic!("expected error"),
1341 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedAmount));
1345 let features = OfferFeatures::unknown();
1346 let mut tlv_stream = refund.as_tlv_stream();
1347 tlv_stream.1.features = Some(&features);
1349 match Refund::try_from(tlv_stream.to_bytes()) {
1350 Ok(_) => panic!("expected error"),
1352 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedFeatures));
1356 let mut tlv_stream = refund.as_tlv_stream();
1357 tlv_stream.1.quantity_max = Some(10);
1359 match Refund::try_from(tlv_stream.to_bytes()) {
1360 Ok(_) => panic!("expected error"),
1362 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedQuantity));
1366 let node_id = payer_pubkey();
1367 let mut tlv_stream = refund.as_tlv_stream();
1368 tlv_stream.1.node_id = Some(&node_id);
1370 match Refund::try_from(tlv_stream.to_bytes()) {
1371 Ok(_) => panic!("expected error"),
1373 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::UnexpectedSigningPubkey));
1379 fn fails_parsing_refund_with_extra_tlv_records() {
1380 let secp_ctx = Secp256k1::new();
1381 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1382 let refund = RefundBuilder::new("foo".into(), vec![1; 32], keys.public_key(), 1000).unwrap()
1385 let mut encoded_refund = Vec::new();
1386 refund.write(&mut encoded_refund).unwrap();
1387 BigSize(1002).write(&mut encoded_refund).unwrap();
1388 BigSize(32).write(&mut encoded_refund).unwrap();
1389 [42u8; 32].write(&mut encoded_refund).unwrap();
1391 match Refund::try_from(encoded_refund) {
1392 Ok(_) => panic!("expected error"),
1393 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),