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 `offer` messages.
12 //! An [`Offer`] represents an "offer to be paid." It is typically constructed by a merchant and
13 //! published as a QR code to be scanned by a customer. The customer uses the offer to request an
14 //! invoice from the merchant to be paid.
19 //! extern crate bitcoin;
20 //! extern crate core;
21 //! extern crate lightning;
23 //! use core::convert::TryFrom;
24 //! use core::num::NonZeroU64;
25 //! use core::time::Duration;
27 //! use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
29 //! use lightning::offers::parse::Bolt12ParseError;
30 //! use lightning::util::ser::{Readable, Writeable};
32 //! # use lightning::blinded_path::BlindedPath;
33 //! # #[cfg(feature = "std")]
34 //! # use std::time::SystemTime;
36 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
39 //! # #[cfg(feature = "std")]
40 //! # fn build() -> Result<(), Bolt12ParseError> {
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = Keypair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
43 //! let pubkey = PublicKey::from(keys);
45 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
46 //! let offer = OfferBuilder::new(pubkey)
47 //! .description("coffee, large".to_string())
48 //! .amount_msats(20_000)
49 //! .supported_quantity(Quantity::Unbounded)
50 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
51 //! .issuer("Foo Bar".to_string())
52 //! .path(create_blinded_path())
53 //! .path(create_another_blinded_path())
56 //! // Encode as a bech32 string for use in a QR code.
57 //! let encoded_offer = offer.to_string();
59 //! // Parse from a bech32 string after scanning from a QR code.
60 //! let offer = encoded_offer.parse::<Offer>()?;
62 //! // Encode offer as raw bytes.
63 //! let mut bytes = Vec::new();
64 //! offer.write(&mut bytes).unwrap();
66 //! // Decode raw bytes into an offer.
67 //! let offer = Offer::try_from(bytes)?;
74 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
75 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
77 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
78 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
80 use bitcoin::blockdata::constants::ChainHash;
81 use bitcoin::network::Network;
82 use bitcoin::secp256k1::{Keypair, PublicKey, Secp256k1, self};
83 use core::hash::{Hash, Hasher};
84 use core::num::NonZeroU64;
86 use core::str::FromStr;
87 use core::time::Duration;
88 use crate::sign::EntropySource;
90 use crate::blinded_path::BlindedPath;
91 use crate::ln::channelmanager::PaymentId;
92 use crate::ln::features::OfferFeatures;
93 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
94 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
95 use crate::offers::merkle::{TaggedHash, TlvStream};
96 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
97 use crate::offers::signer::{Metadata, MetadataMaterial, self};
98 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
99 use crate::util::string::PrintableString;
101 #[cfg(not(c_bindings))]
103 crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder},
107 crate::offers::invoice_request::{InvoiceRequestWithDerivedPayerIdBuilder, InvoiceRequestWithExplicitPayerIdBuilder},
110 #[allow(unused_imports)]
111 use crate::prelude::*;
113 #[cfg(feature = "std")]
114 use std::time::SystemTime;
116 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
118 /// An identifier for an [`Offer`] built using [`DerivedMetadata`].
119 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
120 pub struct OfferId(pub [u8; 32]);
123 const ID_TAG: &'static str = "LDK Offer ID";
125 fn from_valid_offer_tlv_stream(bytes: &[u8]) -> Self {
126 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(Self::ID_TAG, bytes);
127 Self(tagged_hash.to_bytes())
130 fn from_valid_invreq_tlv_stream(bytes: &[u8]) -> Self {
131 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES);
132 let tagged_hash = TaggedHash::from_tlv_stream(Self::ID_TAG, tlv_stream);
133 Self(tagged_hash.to_bytes())
137 impl Writeable for OfferId {
138 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
143 impl Readable for OfferId {
144 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
145 Ok(OfferId(Readable::read(r)?))
149 /// Builds an [`Offer`] for the "offer to be paid" flow.
151 /// See [module-level documentation] for usage.
153 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
155 /// [module-level documentation]: self
156 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
157 offer: OfferContents,
158 metadata_strategy: core::marker::PhantomData<M>,
159 secp_ctx: Option<&'a Secp256k1<T>>,
162 /// Builds an [`Offer`] for the "offer to be paid" flow.
164 /// See [module-level documentation] for usage.
166 /// [module-level documentation]: self
169 pub struct OfferWithExplicitMetadataBuilder<'a> {
170 offer: OfferContents,
171 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
172 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
175 /// Builds an [`Offer`] for the "offer to be paid" flow.
177 /// See [module-level documentation] for usage.
179 /// [module-level documentation]: self
182 pub struct OfferWithDerivedMetadataBuilder<'a> {
183 offer: OfferContents,
184 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
185 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
188 /// Indicates how [`Offer::metadata`] may be set.
190 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
191 pub trait MetadataStrategy {}
193 /// [`Offer::metadata`] may be explicitly set or left empty.
195 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
196 pub struct ExplicitMetadata {}
198 /// [`Offer::metadata`] will be derived.
200 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
201 pub struct DerivedMetadata {}
203 impl MetadataStrategy for ExplicitMetadata {}
205 impl MetadataStrategy for DerivedMetadata {}
207 macro_rules! offer_explicit_metadata_builder_methods { (
208 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
210 /// Creates a new builder for an offer using the [`Offer::signing_pubkey`] for signing invoices.
211 /// The associated secret key must be remembered while the offer is valid.
213 /// Use a different pubkey per offer to avoid correlating offers.
217 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
218 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
220 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
221 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
222 pub fn new(signing_pubkey: PublicKey) -> Self {
224 offer: OfferContents {
225 chains: None, metadata: None, amount: None, description: None,
226 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
227 supported_quantity: Quantity::One, signing_pubkey: Some(signing_pubkey),
229 metadata_strategy: core::marker::PhantomData,
234 /// Sets the [`Offer::metadata`] to the given bytes.
236 /// Successive calls to this method will override the previous setting.
237 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
238 $self.offer.metadata = Some(Metadata::Bytes(metadata));
243 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
244 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
245 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
246 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
247 /// provided `node_id` is used for the signing pubkey.
249 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
250 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
253 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
254 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
255 pub fn deriving_signing_pubkey<ES: Deref>(
256 node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
257 secp_ctx: &'a Secp256k1<$secp_context>
258 ) -> Self where ES::Target: EntropySource {
259 let nonce = Nonce::from_entropy_source(entropy_source);
260 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
261 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
263 offer: OfferContents {
264 chains: None, metadata: Some(metadata), amount: None, description: None,
265 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
266 supported_quantity: Quantity::One, signing_pubkey: Some(node_id),
268 metadata_strategy: core::marker::PhantomData,
269 secp_ctx: Some(secp_ctx),
274 macro_rules! offer_builder_methods { (
275 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
277 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
278 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
280 /// See [`Offer::chains`] on how this relates to the payment currency.
282 /// Successive calls to this method will add another chain hash.
283 pub fn chain($self: $self_type, network: Network) -> $return_type {
284 $self.chain_hash(ChainHash::using_genesis_block(network))
287 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
288 /// [`Network::Bitcoin`] is assumed to be the only one supported.
290 /// See [`Offer::chains`] on how this relates to the payment currency.
292 /// Successive calls to this method will add another chain hash.
293 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
294 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
295 if !chains.contains(&chain) {
302 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
304 /// Successive calls to this method will override the previous setting.
305 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
306 $self.amount(Amount::Bitcoin { amount_msats })
309 /// Sets the [`Offer::amount`].
311 /// Successive calls to this method will override the previous setting.
312 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
313 $self.offer.amount = Some(amount);
317 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
318 /// already passed is valid and can be checked for using [`Offer::is_expired`].
320 /// Successive calls to this method will override the previous setting.
321 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
322 $self.offer.absolute_expiry = Some(absolute_expiry);
326 /// Sets the [`Offer::description`].
328 /// Successive calls to this method will override the previous setting.
329 pub fn description($($self_mut)* $self: $self_type, description: String) -> $return_type {
330 $self.offer.description = Some(description);
334 /// Sets the [`Offer::issuer`].
336 /// Successive calls to this method will override the previous setting.
337 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
338 $self.offer.issuer = Some(issuer);
342 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
343 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
345 /// Successive calls to this method will add another blinded path. Caller is responsible for not
346 /// adding duplicate paths.
347 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
348 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
352 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
353 /// [`Quantity::One`].
355 /// Successive calls to this method will override the previous setting.
356 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
357 $self.offer.supported_quantity = quantity;
361 /// Builds an [`Offer`] from the builder's settings.
362 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
363 match $self.offer.amount {
364 Some(Amount::Bitcoin { amount_msats }) => {
365 if amount_msats > MAX_VALUE_MSAT {
366 return Err(Bolt12SemanticError::InvalidAmount);
369 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
373 if $self.offer.amount.is_some() && $self.offer.description.is_none() {
374 $self.offer.description = Some(String::new());
377 if let Some(chains) = &$self.offer.chains {
378 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
379 $self.offer.chains = None;
383 Ok($self.build_without_checks())
386 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
387 // Create the metadata for stateless verification of an InvoiceRequest.
388 if let Some(mut metadata) = $self.offer.metadata.take() {
389 if metadata.has_derivation_material() {
390 if $self.offer.paths.is_none() {
391 metadata = metadata.without_keys();
394 let mut tlv_stream = $self.offer.as_tlv_stream();
395 debug_assert_eq!(tlv_stream.metadata, None);
396 tlv_stream.metadata = None;
397 if metadata.derives_recipient_keys() {
398 tlv_stream.node_id = None;
401 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
402 metadata = derived_metadata;
403 if let Some(keys) = keys {
404 $self.offer.signing_pubkey = Some(keys.public_key());
408 $self.offer.metadata = Some(metadata);
411 let mut bytes = Vec::new();
412 $self.offer.write(&mut bytes).unwrap();
414 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
418 #[cfg(not(c_bindings))]
419 contents: $self.offer,
421 contents: $self.offer.clone(),
428 macro_rules! offer_builder_test_methods { (
429 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
431 #[cfg_attr(c_bindings, allow(dead_code))]
432 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
433 $self.offer.features = features;
437 #[cfg_attr(c_bindings, allow(dead_code))]
438 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
439 $self.offer.chains = None;
443 #[cfg_attr(c_bindings, allow(dead_code))]
444 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
445 $self.offer.paths = None;
449 #[cfg_attr(c_bindings, allow(dead_code))]
450 pub(crate) fn clear_signing_pubkey($($self_mut)* $self: $self_type) -> $return_type {
451 $self.offer.signing_pubkey = None;
455 #[cfg_attr(c_bindings, allow(dead_code))]
456 pub(super) fn build_unchecked($self: $self_type) -> Offer {
457 $self.build_without_checks()
461 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
462 offer_builder_methods!(self, Self, Self, self, mut);
465 offer_builder_test_methods!(self, Self, Self, self, mut);
468 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
469 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
472 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
473 offer_derived_metadata_builder_methods!(T);
476 #[cfg(all(c_bindings, not(test)))]
477 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
478 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
479 offer_builder_methods!(self, &mut Self, (), ());
482 #[cfg(all(c_bindings, test))]
483 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
484 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
485 offer_builder_methods!(self, &mut Self, &mut Self, self);
486 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
489 #[cfg(all(c_bindings, not(test)))]
490 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
491 offer_derived_metadata_builder_methods!(secp256k1::All);
492 offer_builder_methods!(self, &mut Self, (), ());
495 #[cfg(all(c_bindings, test))]
496 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
497 offer_derived_metadata_builder_methods!(secp256k1::All);
498 offer_builder_methods!(self, &mut Self, &mut Self, self);
499 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
503 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
504 for OfferWithDerivedMetadataBuilder<'a> {
505 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
506 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
508 Self { offer, metadata_strategy, secp_ctx }
513 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
514 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
515 fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
516 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
518 Self { offer, metadata_strategy, secp_ctx }
522 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
524 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
525 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
526 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
528 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
531 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
533 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
534 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
535 #[derive(Clone, Debug)]
537 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
539 pub(super) bytes: Vec<u8>,
540 pub(super) contents: OfferContents,
544 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
545 /// [`Bolt12Invoice`].
547 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
548 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
549 #[derive(Clone, Debug)]
550 #[cfg_attr(test, derive(PartialEq))]
551 pub(super) struct OfferContents {
552 chains: Option<Vec<ChainHash>>,
553 metadata: Option<Metadata>,
554 amount: Option<Amount>,
555 description: Option<String>,
556 features: OfferFeatures,
557 absolute_expiry: Option<Duration>,
558 issuer: Option<String>,
559 paths: Option<Vec<BlindedPath>>,
560 supported_quantity: Quantity,
561 signing_pubkey: Option<PublicKey>,
564 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
565 // TODO: Return a slice once ChainHash has constants.
566 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
567 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
568 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
569 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
570 /// for the selected chain.
571 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
575 // TODO: Link to corresponding method in `InvoiceRequest`.
576 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
577 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
578 pub fn metadata(&$self) -> Option<&Vec<u8>> {
582 /// The minimum amount required for a successful payment of a single item.
583 pub fn amount(&$self) -> Option<$crate::offers::offer::Amount> {
587 /// A complete description of the purpose of the payment. Intended to be displayed to the user
588 /// but with the caveat that it has not been verified in any way.
589 pub fn description(&$self) -> Option<$crate::util::string::PrintableString> {
590 $contents.description()
593 /// Features pertaining to the offer.
594 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
595 &$contents.features()
598 /// Duration since the Unix epoch when an invoice should no longer be requested.
600 /// If `None`, the offer does not expire.
601 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
602 $contents.absolute_expiry()
605 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
606 /// displayed to the user but with the caveat that it has not been verified in any way.
607 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
611 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
612 /// recipient privacy by obfuscating its node id.
613 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
617 /// The quantity of items supported.
618 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
619 $contents.supported_quantity()
622 /// The public key used by the recipient to sign invoices.
623 pub fn signing_pubkey(&$self) -> Option<bitcoin::secp256k1::PublicKey> {
624 $contents.signing_pubkey()
629 offer_accessors!(self, self.contents);
631 /// Returns the id of the offer.
632 pub fn id(&self) -> OfferId {
636 pub(super) fn implied_chain(&self) -> ChainHash {
637 self.contents.implied_chain()
640 /// Returns whether the given chain is supported by the offer.
641 pub fn supports_chain(&self, chain: ChainHash) -> bool {
642 self.contents.supports_chain(chain)
645 /// Whether the offer has expired.
646 #[cfg(feature = "std")]
647 pub fn is_expired(&self) -> bool {
648 self.contents.is_expired()
651 /// Whether the offer has expired given the duration since the Unix epoch.
652 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
653 self.contents.is_expired_no_std(duration_since_epoch)
656 /// Returns whether the given quantity is valid for the offer.
657 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
658 self.contents.is_valid_quantity(quantity)
661 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
663 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
664 pub fn expects_quantity(&self) -> bool {
665 self.contents.expects_quantity()
669 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
670 /// Similar to [`Offer::request_invoice`] except it:
671 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
673 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
674 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
675 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
676 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
677 /// be used when sending the payment for the requested invoice.
679 /// Useful to protect the sender's privacy.
681 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
682 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
683 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
684 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
685 pub fn request_invoice_deriving_payer_id<
687 #[cfg(not(c_bindings))]
688 T: secp256k1::Signing
690 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
691 #[cfg(not(c_bindings))]
692 secp_ctx: &'b Secp256k1<T>,
694 secp_ctx: &'b Secp256k1<secp256k1::All>,
695 payment_id: PaymentId
696 ) -> Result<$builder, Bolt12SemanticError>
698 ES::Target: EntropySource,
700 if $self.offer_features().requires_unknown_bits() {
701 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
704 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
708 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
709 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
710 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
712 /// Useful for recurring payments using the same `payer_id` with different invoices.
714 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
715 pub fn request_invoice_deriving_metadata<ES: Deref>(
716 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
717 payment_id: PaymentId
718 ) -> Result<$builder, Bolt12SemanticError>
720 ES::Target: EntropySource,
722 if $self.offer_features().requires_unknown_bits() {
723 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
726 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
729 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
730 /// which will be reflected in the `Bolt12Invoice` response.
732 /// The `metadata` is useful for including information about the derivation of `payer_id` such
733 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
734 /// hashing in the signature calculation.
736 /// This should not leak any information such as by using a simple BIP-32 derivation path.
737 /// Otherwise, payments may be correlated.
739 /// Errors if the offer contains unknown required features.
741 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
742 pub fn request_invoice(
743 &$self, metadata: Vec<u8>, payer_id: PublicKey
744 ) -> Result<$builder, Bolt12SemanticError> {
745 if $self.offer_features().requires_unknown_bits() {
746 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
749 Ok(<$builder>::new($self, metadata, payer_id))
753 #[cfg(not(c_bindings))]
755 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
756 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
761 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
762 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
767 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
768 self.contents.as_tlv_stream()
772 impl AsRef<[u8]> for Offer {
773 fn as_ref(&self) -> &[u8] {
778 impl PartialEq for Offer {
779 fn eq(&self, other: &Self) -> bool {
780 self.bytes.eq(&other.bytes)
786 impl Hash for Offer {
787 fn hash<H: Hasher>(&self, state: &mut H) {
788 self.bytes.hash(state);
793 pub fn chains(&self) -> Vec<ChainHash> {
794 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
797 pub fn implied_chain(&self) -> ChainHash {
798 ChainHash::using_genesis_block(Network::Bitcoin)
801 pub fn supports_chain(&self, chain: ChainHash) -> bool {
802 self.chains().contains(&chain)
805 pub fn metadata(&self) -> Option<&Vec<u8>> {
806 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
809 pub fn amount(&self) -> Option<Amount> {
813 pub fn description(&self) -> Option<PrintableString> {
814 self.description.as_ref().map(|description| PrintableString(description))
817 pub fn features(&self) -> &OfferFeatures {
821 pub fn absolute_expiry(&self) -> Option<Duration> {
825 #[cfg(feature = "std")]
826 pub(super) fn is_expired(&self) -> bool {
827 SystemTime::UNIX_EPOCH
829 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
833 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
835 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
839 pub fn issuer(&self) -> Option<PrintableString> {
840 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
843 pub fn paths(&self) -> &[BlindedPath] {
844 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
847 pub(super) fn check_amount_msats_for_quantity(
848 &self, amount_msats: Option<u64>, quantity: Option<u64>
849 ) -> Result<(), Bolt12SemanticError> {
850 let offer_amount_msats = match self.amount {
852 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
853 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
856 if !self.expects_quantity() || quantity.is_some() {
857 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
858 .ok_or(Bolt12SemanticError::InvalidAmount)?;
859 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
861 if amount_msats < expected_amount_msats {
862 return Err(Bolt12SemanticError::InsufficientAmount);
865 if amount_msats > MAX_VALUE_MSAT {
866 return Err(Bolt12SemanticError::InvalidAmount);
873 pub fn supported_quantity(&self) -> Quantity {
874 self.supported_quantity
877 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
878 let expects_quantity = self.expects_quantity();
880 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
881 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
882 Some(quantity) if !self.is_valid_quantity(quantity) => {
883 Err(Bolt12SemanticError::InvalidQuantity)
889 fn is_valid_quantity(&self, quantity: u64) -> bool {
890 match self.supported_quantity {
891 Quantity::Bounded(n) => quantity <= n.get(),
892 Quantity::Unbounded => quantity > 0,
893 Quantity::One => quantity == 1,
897 fn expects_quantity(&self) -> bool {
898 match self.supported_quantity {
899 Quantity::Bounded(_) => true,
900 Quantity::Unbounded => true,
901 Quantity::One => false,
905 pub(super) fn signing_pubkey(&self) -> Option<PublicKey> {
909 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
910 pub(super) fn verify<T: secp256k1::Signing>(
911 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
912 ) -> Result<(OfferId, Option<Keypair>), ()> {
913 match self.metadata() {
915 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
916 match record.r#type {
917 OFFER_METADATA_TYPE => false,
918 OFFER_NODE_ID_TYPE => {
919 !self.metadata.as_ref().unwrap().derives_recipient_keys()
924 let signing_pubkey = match self.signing_pubkey() {
925 Some(signing_pubkey) => signing_pubkey,
926 None => return Err(()),
928 let keys = signer::verify_recipient_metadata(
929 metadata, key, IV_BYTES, signing_pubkey, tlv_stream, secp_ctx
932 let offer_id = OfferId::from_valid_invreq_tlv_stream(bytes);
940 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
941 let (currency, amount) = match &self.amount {
942 None => (None, None),
943 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
944 Some(Amount::Currency { iso4217_code, amount }) => (
945 Some(iso4217_code), Some(*amount)
950 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
954 chains: self.chains.as_ref(),
955 metadata: self.metadata(),
958 description: self.description.as_ref(),
960 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
961 paths: self.paths.as_ref(),
962 issuer: self.issuer.as_ref(),
963 quantity_max: self.supported_quantity.to_tlv_record(),
964 node_id: self.signing_pubkey.as_ref(),
969 impl Readable for Offer {
970 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
971 let bytes: WithoutLength<Vec<u8>> = Readable::read(reader)?;
972 Self::try_from(bytes.0).map_err(|_| DecodeError::InvalidValue)
976 impl Writeable for Offer {
977 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
978 WithoutLength(&self.bytes).write(writer)
982 impl Writeable for OfferContents {
983 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
984 self.as_tlv_stream().write(writer)
988 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
989 /// another currency.
990 #[derive(Clone, Copy, Debug, PartialEq)]
992 /// An amount of bitcoin.
994 /// The amount in millisatoshi.
997 /// An amount of currency specified using ISO 4712.
999 /// The currency that the amount is denominated in.
1000 iso4217_code: CurrencyCode,
1001 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
1006 /// An ISO 4712 three-letter currency code (e.g., USD).
1007 pub type CurrencyCode = [u8; 3];
1009 /// Quantity of items supported by an [`Offer`].
1010 #[derive(Clone, Copy, Debug, PartialEq)]
1012 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
1013 /// but is limited (e.g., because of per customer or inventory limits).
1015 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
1017 Bounded(NonZeroU64),
1018 /// One or more items. Use when more than one item can be requested without any limit.
1020 /// Only one item. Use when only a single item can be requested.
1025 fn to_tlv_record(&self) -> Option<u64> {
1027 Quantity::Bounded(n) => Some(n.get()),
1028 Quantity::Unbounded => Some(0),
1029 Quantity::One => None,
1034 /// Valid type range for offer TLV records.
1035 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
1037 /// TLV record type for [`Offer::metadata`].
1038 const OFFER_METADATA_TYPE: u64 = 4;
1040 /// TLV record type for [`Offer::signing_pubkey`].
1041 const OFFER_NODE_ID_TYPE: u64 = 22;
1043 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
1044 (2, chains: (Vec<ChainHash>, WithoutLength)),
1045 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1046 (6, currency: CurrencyCode),
1047 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
1048 (10, description: (String, WithoutLength)),
1049 (12, features: (OfferFeatures, WithoutLength)),
1050 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
1051 (16, paths: (Vec<BlindedPath>, WithoutLength)),
1052 (18, issuer: (String, WithoutLength)),
1053 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
1054 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
1057 impl Bech32Encode for Offer {
1058 const BECH32_HRP: &'static str = "lno";
1061 impl FromStr for Offer {
1062 type Err = Bolt12ParseError;
1064 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
1065 Self::from_bech32_str(s)
1069 impl TryFrom<Vec<u8>> for Offer {
1070 type Error = Bolt12ParseError;
1072 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1073 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1074 let ParsedMessage { bytes, tlv_stream } = offer;
1075 let contents = OfferContents::try_from(tlv_stream)?;
1076 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
1078 Ok(Offer { bytes, contents, id })
1082 impl TryFrom<OfferTlvStream> for OfferContents {
1083 type Error = Bolt12SemanticError;
1085 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1086 let OfferTlvStream {
1087 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1088 issuer, quantity_max, node_id,
1091 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1093 let amount = match (currency, amount) {
1094 (None, None) => None,
1095 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1096 return Err(Bolt12SemanticError::InvalidAmount);
1098 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1099 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1100 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1103 if amount.is_some() && description.is_none() {
1104 return Err(Bolt12SemanticError::MissingDescription);
1107 let features = features.unwrap_or_else(OfferFeatures::empty);
1109 let absolute_expiry = absolute_expiry
1110 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1112 let supported_quantity = match quantity_max {
1113 None => Quantity::One,
1114 Some(0) => Quantity::Unbounded,
1115 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1118 let (signing_pubkey, paths) = match (node_id, paths) {
1119 (None, None) => return Err(Bolt12SemanticError::MissingSigningPubkey),
1120 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1121 (node_id, paths) => (node_id, paths),
1125 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1126 supported_quantity, signing_pubkey,
1131 impl core::fmt::Display for Offer {
1132 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1133 self.fmt_bech32_str(f)
1139 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1140 #[cfg(not(c_bindings))]
1142 super::OfferBuilder,
1146 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1149 use bitcoin::blockdata::constants::ChainHash;
1150 use bitcoin::network::Network;
1151 use bitcoin::secp256k1::Secp256k1;
1152 use core::num::NonZeroU64;
1153 use core::time::Duration;
1154 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1155 use crate::sign::KeyMaterial;
1156 use crate::ln::features::OfferFeatures;
1157 use crate::ln::inbound_payment::ExpandedKey;
1158 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1159 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1160 use crate::offers::test_utils::*;
1161 use crate::util::ser::{BigSize, Writeable};
1162 use crate::util::string::PrintableString;
1165 fn builds_offer_with_defaults() {
1166 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1168 let mut buffer = Vec::new();
1169 offer.write(&mut buffer).unwrap();
1171 assert_eq!(offer.bytes, buffer.as_slice());
1172 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1173 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1174 assert_eq!(offer.metadata(), None);
1175 assert_eq!(offer.amount(), None);
1176 assert_eq!(offer.description(), None);
1177 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1178 assert_eq!(offer.absolute_expiry(), None);
1179 #[cfg(feature = "std")]
1180 assert!(!offer.is_expired());
1181 assert_eq!(offer.paths(), &[]);
1182 assert_eq!(offer.issuer(), None);
1183 assert_eq!(offer.supported_quantity(), Quantity::One);
1184 assert!(!offer.expects_quantity());
1185 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1188 offer.as_tlv_stream(),
1196 absolute_expiry: None,
1200 node_id: Some(&pubkey(42)),
1204 if let Err(e) = Offer::try_from(buffer) {
1205 panic!("error parsing offer: {:?}", e);
1210 fn builds_offer_with_chains() {
1211 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1212 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1214 let offer = OfferBuilder::new(pubkey(42))
1215 .chain(Network::Bitcoin)
1218 assert!(offer.supports_chain(mainnet));
1219 assert_eq!(offer.chains(), vec![mainnet]);
1220 assert_eq!(offer.as_tlv_stream().chains, None);
1222 let offer = OfferBuilder::new(pubkey(42))
1223 .chain(Network::Testnet)
1226 assert!(offer.supports_chain(testnet));
1227 assert_eq!(offer.chains(), vec![testnet]);
1228 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1230 let offer = OfferBuilder::new(pubkey(42))
1231 .chain(Network::Testnet)
1232 .chain(Network::Testnet)
1235 assert!(offer.supports_chain(testnet));
1236 assert_eq!(offer.chains(), vec![testnet]);
1237 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1239 let offer = OfferBuilder::new(pubkey(42))
1240 .chain(Network::Bitcoin)
1241 .chain(Network::Testnet)
1244 assert!(offer.supports_chain(mainnet));
1245 assert!(offer.supports_chain(testnet));
1246 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1247 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1251 fn builds_offer_with_metadata() {
1252 let offer = OfferBuilder::new(pubkey(42))
1253 .metadata(vec![42; 32]).unwrap()
1256 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1257 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1259 let offer = OfferBuilder::new(pubkey(42))
1260 .metadata(vec![42; 32]).unwrap()
1261 .metadata(vec![43; 32]).unwrap()
1264 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1265 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1269 fn builds_offer_with_metadata_derived() {
1270 let node_id = recipient_pubkey();
1271 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1272 let entropy = FixedEntropy {};
1273 let secp_ctx = Secp256k1::new();
1276 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1277 let offer = OfferBuilder
1278 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1281 assert_eq!(offer.signing_pubkey(), Some(node_id));
1283 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1285 .sign(payer_sign).unwrap();
1286 match invoice_request.verify(&expanded_key, &secp_ctx) {
1287 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1288 Err(_) => panic!("unexpected error"),
1291 // Fails verification with altered offer field
1292 let mut tlv_stream = offer.as_tlv_stream();
1293 tlv_stream.amount = Some(100);
1295 let mut encoded_offer = Vec::new();
1296 tlv_stream.write(&mut encoded_offer).unwrap();
1298 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1299 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1301 .sign(payer_sign).unwrap();
1302 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1304 // Fails verification with altered metadata
1305 let mut tlv_stream = offer.as_tlv_stream();
1306 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1307 tlv_stream.metadata = Some(&metadata);
1309 let mut encoded_offer = Vec::new();
1310 tlv_stream.write(&mut encoded_offer).unwrap();
1312 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1313 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1315 .sign(payer_sign).unwrap();
1316 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1320 fn builds_offer_with_derived_signing_pubkey() {
1321 let node_id = recipient_pubkey();
1322 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1323 let entropy = FixedEntropy {};
1324 let secp_ctx = Secp256k1::new();
1326 let blinded_path = BlindedPath {
1327 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1328 blinding_point: pubkey(41),
1330 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1331 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1336 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1337 let offer = OfferBuilder
1338 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1342 assert_ne!(offer.signing_pubkey(), Some(node_id));
1344 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1346 .sign(payer_sign).unwrap();
1347 match invoice_request.verify(&expanded_key, &secp_ctx) {
1348 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1349 Err(_) => panic!("unexpected error"),
1352 // Fails verification with altered offer field
1353 let mut tlv_stream = offer.as_tlv_stream();
1354 tlv_stream.amount = Some(100);
1356 let mut encoded_offer = Vec::new();
1357 tlv_stream.write(&mut encoded_offer).unwrap();
1359 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1360 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1362 .sign(payer_sign).unwrap();
1363 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1365 // Fails verification with altered signing pubkey
1366 let mut tlv_stream = offer.as_tlv_stream();
1367 let signing_pubkey = pubkey(1);
1368 tlv_stream.node_id = Some(&signing_pubkey);
1370 let mut encoded_offer = Vec::new();
1371 tlv_stream.write(&mut encoded_offer).unwrap();
1373 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1374 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1376 .sign(payer_sign).unwrap();
1377 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1381 fn builds_offer_with_amount() {
1382 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1383 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1385 let offer = OfferBuilder::new(pubkey(42))
1389 let tlv_stream = offer.as_tlv_stream();
1390 assert_eq!(offer.amount(), Some(bitcoin_amount));
1391 assert_eq!(tlv_stream.amount, Some(1000));
1392 assert_eq!(tlv_stream.currency, None);
1394 #[cfg(not(c_bindings))]
1395 let builder = OfferBuilder::new(pubkey(42))
1396 .amount(currency_amount.clone());
1398 let mut builder = OfferBuilder::new(pubkey(42));
1400 builder.amount(currency_amount.clone());
1401 let tlv_stream = builder.offer.as_tlv_stream();
1402 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1403 assert_eq!(tlv_stream.amount, Some(10));
1404 assert_eq!(tlv_stream.currency, Some(b"USD"));
1405 match builder.build() {
1406 Ok(_) => panic!("expected error"),
1407 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1410 let offer = OfferBuilder::new(pubkey(42))
1411 .amount(currency_amount.clone())
1412 .amount(bitcoin_amount.clone())
1415 let tlv_stream = offer.as_tlv_stream();
1416 assert_eq!(tlv_stream.amount, Some(1000));
1417 assert_eq!(tlv_stream.currency, None);
1419 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1420 match OfferBuilder::new(pubkey(42)).amount(invalid_amount).build() {
1421 Ok(_) => panic!("expected error"),
1422 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1427 fn builds_offer_with_description() {
1428 let offer = OfferBuilder::new(pubkey(42))
1429 .description("foo".into())
1432 assert_eq!(offer.description(), Some(PrintableString("foo")));
1433 assert_eq!(offer.as_tlv_stream().description, Some(&String::from("foo")));
1435 let offer = OfferBuilder::new(pubkey(42))
1436 .description("foo".into())
1437 .description("bar".into())
1440 assert_eq!(offer.description(), Some(PrintableString("bar")));
1441 assert_eq!(offer.as_tlv_stream().description, Some(&String::from("bar")));
1443 let offer = OfferBuilder::new(pubkey(42))
1447 assert_eq!(offer.description(), Some(PrintableString("")));
1448 assert_eq!(offer.as_tlv_stream().description, Some(&String::from("")));
1452 fn builds_offer_with_features() {
1453 let offer = OfferBuilder::new(pubkey(42))
1454 .features_unchecked(OfferFeatures::unknown())
1457 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1458 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1460 let offer = OfferBuilder::new(pubkey(42))
1461 .features_unchecked(OfferFeatures::unknown())
1462 .features_unchecked(OfferFeatures::empty())
1465 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1466 assert_eq!(offer.as_tlv_stream().features, None);
1470 fn builds_offer_with_absolute_expiry() {
1471 let future_expiry = Duration::from_secs(u64::max_value());
1472 let past_expiry = Duration::from_secs(0);
1473 let now = future_expiry - Duration::from_secs(1_000);
1475 let offer = OfferBuilder::new(pubkey(42))
1476 .absolute_expiry(future_expiry)
1479 #[cfg(feature = "std")]
1480 assert!(!offer.is_expired());
1481 assert!(!offer.is_expired_no_std(now));
1482 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1483 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1485 let offer = OfferBuilder::new(pubkey(42))
1486 .absolute_expiry(future_expiry)
1487 .absolute_expiry(past_expiry)
1490 #[cfg(feature = "std")]
1491 assert!(offer.is_expired());
1492 assert!(offer.is_expired_no_std(now));
1493 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1494 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1498 fn builds_offer_with_paths() {
1501 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1502 blinding_point: pubkey(41),
1504 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1505 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1509 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1510 blinding_point: pubkey(41),
1512 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1513 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1518 let offer = OfferBuilder::new(pubkey(42))
1519 .path(paths[0].clone())
1520 .path(paths[1].clone())
1523 let tlv_stream = offer.as_tlv_stream();
1524 assert_eq!(offer.paths(), paths.as_slice());
1525 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1526 assert_ne!(pubkey(42), pubkey(44));
1527 assert_eq!(tlv_stream.paths, Some(&paths));
1528 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1532 fn builds_offer_with_issuer() {
1533 let offer = OfferBuilder::new(pubkey(42))
1534 .issuer("foo".into())
1537 assert_eq!(offer.issuer(), Some(PrintableString("foo")));
1538 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("foo")));
1540 let offer = OfferBuilder::new(pubkey(42))
1541 .issuer("foo".into())
1542 .issuer("bar".into())
1545 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1546 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1550 fn builds_offer_with_supported_quantity() {
1551 let one = NonZeroU64::new(1).unwrap();
1552 let ten = NonZeroU64::new(10).unwrap();
1554 let offer = OfferBuilder::new(pubkey(42))
1555 .supported_quantity(Quantity::One)
1558 let tlv_stream = offer.as_tlv_stream();
1559 assert!(!offer.expects_quantity());
1560 assert_eq!(offer.supported_quantity(), Quantity::One);
1561 assert_eq!(tlv_stream.quantity_max, None);
1563 let offer = OfferBuilder::new(pubkey(42))
1564 .supported_quantity(Quantity::Unbounded)
1567 let tlv_stream = offer.as_tlv_stream();
1568 assert!(offer.expects_quantity());
1569 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1570 assert_eq!(tlv_stream.quantity_max, Some(0));
1572 let offer = OfferBuilder::new(pubkey(42))
1573 .supported_quantity(Quantity::Bounded(ten))
1576 let tlv_stream = offer.as_tlv_stream();
1577 assert!(offer.expects_quantity());
1578 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1579 assert_eq!(tlv_stream.quantity_max, Some(10));
1581 let offer = OfferBuilder::new(pubkey(42))
1582 .supported_quantity(Quantity::Bounded(one))
1585 let tlv_stream = offer.as_tlv_stream();
1586 assert!(offer.expects_quantity());
1587 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1588 assert_eq!(tlv_stream.quantity_max, Some(1));
1590 let offer = OfferBuilder::new(pubkey(42))
1591 .supported_quantity(Quantity::Bounded(ten))
1592 .supported_quantity(Quantity::One)
1595 let tlv_stream = offer.as_tlv_stream();
1596 assert!(!offer.expects_quantity());
1597 assert_eq!(offer.supported_quantity(), Quantity::One);
1598 assert_eq!(tlv_stream.quantity_max, None);
1602 fn fails_requesting_invoice_with_unknown_required_features() {
1603 match OfferBuilder::new(pubkey(42))
1604 .features_unchecked(OfferFeatures::unknown())
1606 .request_invoice(vec![1; 32], pubkey(43))
1608 Ok(_) => panic!("expected error"),
1609 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1614 fn parses_offer_with_chains() {
1615 let offer = OfferBuilder::new(pubkey(42))
1616 .chain(Network::Bitcoin)
1617 .chain(Network::Testnet)
1620 if let Err(e) = offer.to_string().parse::<Offer>() {
1621 panic!("error parsing offer: {:?}", e);
1626 fn parses_offer_with_amount() {
1627 let offer = OfferBuilder::new(pubkey(42))
1628 .amount(Amount::Bitcoin { amount_msats: 1000 })
1631 if let Err(e) = offer.to_string().parse::<Offer>() {
1632 panic!("error parsing offer: {:?}", e);
1635 let mut tlv_stream = offer.as_tlv_stream();
1636 tlv_stream.amount = Some(1000);
1637 tlv_stream.currency = Some(b"USD");
1639 let mut encoded_offer = Vec::new();
1640 tlv_stream.write(&mut encoded_offer).unwrap();
1642 if let Err(e) = Offer::try_from(encoded_offer) {
1643 panic!("error parsing offer: {:?}", e);
1646 let mut tlv_stream = offer.as_tlv_stream();
1647 tlv_stream.amount = None;
1648 tlv_stream.currency = Some(b"USD");
1650 let mut encoded_offer = Vec::new();
1651 tlv_stream.write(&mut encoded_offer).unwrap();
1653 match Offer::try_from(encoded_offer) {
1654 Ok(_) => panic!("expected error"),
1655 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1658 let mut tlv_stream = offer.as_tlv_stream();
1659 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1660 tlv_stream.currency = None;
1662 let mut encoded_offer = Vec::new();
1663 tlv_stream.write(&mut encoded_offer).unwrap();
1665 match Offer::try_from(encoded_offer) {
1666 Ok(_) => panic!("expected error"),
1667 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1672 fn parses_offer_with_description() {
1673 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1674 if let Err(e) = offer.to_string().parse::<Offer>() {
1675 panic!("error parsing offer: {:?}", e);
1678 let offer = OfferBuilder::new(pubkey(42))
1679 .description("foo".to_string())
1682 if let Err(e) = offer.to_string().parse::<Offer>() {
1683 panic!("error parsing offer: {:?}", e);
1686 let mut tlv_stream = offer.as_tlv_stream();
1687 tlv_stream.description = None;
1689 let mut encoded_offer = Vec::new();
1690 tlv_stream.write(&mut encoded_offer).unwrap();
1692 match Offer::try_from(encoded_offer) {
1693 Ok(_) => panic!("expected error"),
1695 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1701 fn parses_offer_with_paths() {
1702 let offer = OfferBuilder::new(pubkey(42))
1704 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1705 blinding_point: pubkey(41),
1707 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1708 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1712 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1713 blinding_point: pubkey(41),
1715 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1716 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1721 if let Err(e) = offer.to_string().parse::<Offer>() {
1722 panic!("error parsing offer: {:?}", e);
1725 let offer = OfferBuilder::new(pubkey(42))
1727 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1728 blinding_point: pubkey(41),
1730 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1731 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1734 .clear_signing_pubkey()
1737 if let Err(e) = offer.to_string().parse::<Offer>() {
1738 panic!("error parsing offer: {:?}", e);
1741 let mut builder = OfferBuilder::new(pubkey(42));
1742 builder.offer.paths = Some(vec![]);
1744 let offer = builder.build().unwrap();
1745 match offer.to_string().parse::<Offer>() {
1746 Ok(_) => panic!("expected error"),
1748 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths));
1754 fn parses_offer_with_quantity() {
1755 let offer = OfferBuilder::new(pubkey(42))
1756 .supported_quantity(Quantity::One)
1759 if let Err(e) = offer.to_string().parse::<Offer>() {
1760 panic!("error parsing offer: {:?}", e);
1763 let offer = OfferBuilder::new(pubkey(42))
1764 .supported_quantity(Quantity::Unbounded)
1767 if let Err(e) = offer.to_string().parse::<Offer>() {
1768 panic!("error parsing offer: {:?}", e);
1771 let offer = OfferBuilder::new(pubkey(42))
1772 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1775 if let Err(e) = offer.to_string().parse::<Offer>() {
1776 panic!("error parsing offer: {:?}", e);
1779 let offer = OfferBuilder::new(pubkey(42))
1780 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1783 if let Err(e) = offer.to_string().parse::<Offer>() {
1784 panic!("error parsing offer: {:?}", e);
1789 fn parses_offer_with_node_id() {
1790 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1791 if let Err(e) = offer.to_string().parse::<Offer>() {
1792 panic!("error parsing offer: {:?}", e);
1795 let mut tlv_stream = offer.as_tlv_stream();
1796 tlv_stream.node_id = None;
1798 let mut encoded_offer = Vec::new();
1799 tlv_stream.write(&mut encoded_offer).unwrap();
1801 match Offer::try_from(encoded_offer) {
1802 Ok(_) => panic!("expected error"),
1804 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1810 fn fails_parsing_offer_with_extra_tlv_records() {
1811 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1813 let mut encoded_offer = Vec::new();
1814 offer.write(&mut encoded_offer).unwrap();
1815 BigSize(80).write(&mut encoded_offer).unwrap();
1816 BigSize(32).write(&mut encoded_offer).unwrap();
1817 [42u8; 32].write(&mut encoded_offer).unwrap();
1819 match Offer::try_from(encoded_offer) {
1820 Ok(_) => panic!("expected error"),
1821 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1828 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1829 use crate::ln::msgs::DecodeError;
1832 fn parses_bech32_encoded_offers() {
1834 // Minimal bolt12 offer
1835 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1838 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1840 // for bitcoin (redundant)
1841 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1843 // for bitcoin or liquidv1
1844 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1847 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1850 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1853 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1856 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1859 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1862 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1864 // with unlimited (or unknown) quantity
1865 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1867 // with single quantity (weird but valid)
1868 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1871 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1873 // with blinded path via Bob (0x424242...), blinding 020202...
1874 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1876 // ... and with sciddir introduction node
1877 "lno1pgx9getnwss8vetrw3hhyucs3yqqqqqqqqqqqqp2qgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqyqqqqqqqqqqqqqqqqqqqqqqqqqqqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqgzyg3zyg3zyg3z93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1879 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1880 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1882 // unknown odd field
1883 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1885 for encoded_offer in &offers {
1886 if let Err(e) = encoded_offer.parse::<Offer>() {
1887 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1893 fn fails_parsing_bech32_encoded_offers() {
1894 // Malformed: fields out of order
1896 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1897 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1900 // Malformed: unknown even TLV type 78
1902 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1903 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1908 "lno1".parse::<Offer>(),
1909 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),
1912 // Malformed: truncated at type
1914 "lno1pg".parse::<Offer>(),
1915 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1918 // Malformed: truncated in length
1920 "lno1pt7s".parse::<Offer>(),
1921 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1924 // Malformed: truncated after length
1926 "lno1pgpq".parse::<Offer>(),
1927 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1930 // Malformed: truncated in description
1932 "lno1pgpyz".parse::<Offer>(),
1933 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1936 // Malformed: invalid offer_chains length
1938 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1939 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1942 // Malformed: truncated currency UTF-8
1944 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1945 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1948 // Malformed: invalid currency UTF-8
1950 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1951 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1954 // Malformed: truncated description UTF-8
1956 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1957 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1960 // Malformed: invalid description UTF-8
1962 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1963 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1966 // Malformed: truncated offer_paths
1968 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1969 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1972 // Malformed: zero num_hops in blinded_path
1974 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1975 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1978 // Malformed: truncated onionmsg_hop in blinded_path
1980 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1981 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1984 // Malformed: bad first_node_id in blinded_path
1986 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1987 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1990 // Malformed: bad blinding in blinded_path
1992 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1993 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1996 // Malformed: bad blinded_node_id in onionmsg_hop
1998 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1999 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
2002 // Malformed: truncated issuer UTF-8
2004 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
2005 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2008 // Malformed: invalid issuer UTF-8
2010 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
2011 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2014 // Malformed: invalid offer_node_id
2016 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
2017 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2020 // Contains type >= 80
2022 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
2023 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
2026 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
2027 // Contains unknown feature 22
2029 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
2032 // Missing offer_description
2034 // TODO: Match the spec once it is updated.
2035 "lno1pqpq86qkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>(),
2036 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
2039 // Missing offer_node_id"
2041 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
2042 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),