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("coffee, large".to_string(), pubkey)
47 //! .amount_msats(20_000)
48 //! .supported_quantity(Quantity::Unbounded)
49 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //! .issuer("Foo Bar".to_string())
51 //! .path(create_blinded_path())
52 //! .path(create_another_blinded_path())
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
79 use bitcoin::blockdata::constants::ChainHash;
80 use bitcoin::network::constants::Network;
81 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
82 use core::hash::{Hash, Hasher};
83 use core::num::NonZeroU64;
85 use core::str::FromStr;
86 use core::time::Duration;
87 use crate::sign::EntropySource;
89 use crate::blinded_path::BlindedPath;
90 use crate::ln::channelmanager::PaymentId;
91 use crate::ln::features::OfferFeatures;
92 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
93 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
94 use crate::offers::merkle::{TaggedHash, TlvStream};
95 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
96 use crate::offers::signer::{Metadata, MetadataMaterial, self};
97 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
98 use crate::util::string::PrintableString;
100 #[cfg(not(c_bindings))]
102 crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder},
106 crate::offers::invoice_request::{InvoiceRequestWithDerivedPayerIdBuilder, InvoiceRequestWithExplicitPayerIdBuilder},
109 #[allow(unused_imports)]
110 use crate::prelude::*;
112 #[cfg(feature = "std")]
113 use std::time::SystemTime;
115 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
117 /// An identifier for an [`Offer`] built using [`DerivedMetadata`].
118 #[derive(Clone, Copy, Debug, PartialEq)]
119 pub struct OfferId(pub [u8; 32]);
122 const ID_TAG: &'static str = "LDK Offer ID";
124 fn from_valid_offer_tlv_stream(bytes: &[u8]) -> Self {
125 let tagged_hash = TaggedHash::new(Self::ID_TAG, &bytes);
126 Self(tagged_hash.to_bytes())
130 impl Writeable for OfferId {
131 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
136 impl Readable for OfferId {
137 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
138 Ok(OfferId(Readable::read(r)?))
142 /// Builds an [`Offer`] for the "offer to be paid" flow.
144 /// See [module-level documentation] for usage.
146 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
148 /// [module-level documentation]: self
149 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
150 offer: OfferContents,
151 metadata_strategy: core::marker::PhantomData<M>,
152 secp_ctx: Option<&'a Secp256k1<T>>,
155 /// Builds an [`Offer`] for the "offer to be paid" flow.
157 /// See [module-level documentation] for usage.
159 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
161 /// [module-level documentation]: self
163 pub struct OfferWithExplicitMetadataBuilder<'a> {
164 offer: OfferContents,
165 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
166 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
169 /// Builds an [`Offer`] for the "offer to be paid" flow.
171 /// See [module-level documentation] for usage.
173 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
175 /// [module-level documentation]: self
177 pub struct OfferWithDerivedMetadataBuilder<'a> {
178 offer: OfferContents,
179 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
180 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
183 /// Indicates how [`Offer::metadata`] may be set.
185 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
186 pub trait MetadataStrategy {}
188 /// [`Offer::metadata`] may be explicitly set or left empty.
190 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
191 pub struct ExplicitMetadata {}
193 /// [`Offer::metadata`] will be derived.
195 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
196 pub struct DerivedMetadata {}
198 impl MetadataStrategy for ExplicitMetadata {}
200 impl MetadataStrategy for DerivedMetadata {}
202 macro_rules! offer_explicit_metadata_builder_methods { (
203 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
205 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
206 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
207 /// while the offer is valid.
209 /// Use a different pubkey per offer to avoid correlating offers.
213 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
214 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
216 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
217 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
218 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
220 offer: OfferContents {
221 chains: None, metadata: None, amount: None, description,
222 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
223 supported_quantity: Quantity::One, signing_pubkey,
225 metadata_strategy: core::marker::PhantomData,
230 /// Sets the [`Offer::metadata`] to the given bytes.
232 /// Successive calls to this method will override the previous setting.
233 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
234 $self.offer.metadata = Some(Metadata::Bytes(metadata));
239 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
240 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
241 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
242 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
243 /// provided `node_id` is used for the signing pubkey.
245 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
246 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
249 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
250 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
251 pub fn deriving_signing_pubkey<ES: Deref>(
252 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
253 secp_ctx: &'a Secp256k1<$secp_context>
254 ) -> Self where ES::Target: EntropySource {
255 let nonce = Nonce::from_entropy_source(entropy_source);
256 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
257 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
259 offer: OfferContents {
260 chains: None, metadata: Some(metadata), amount: None, description,
261 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
262 supported_quantity: Quantity::One, signing_pubkey: node_id,
264 metadata_strategy: core::marker::PhantomData,
265 secp_ctx: Some(secp_ctx),
270 macro_rules! offer_builder_methods { (
271 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
273 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
274 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
276 /// See [`Offer::chains`] on how this relates to the payment currency.
278 /// Successive calls to this method will add another chain hash.
279 pub fn chain($self: $self_type, network: Network) -> $return_type {
280 $self.chain_hash(ChainHash::using_genesis_block(network))
283 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
284 /// [`Network::Bitcoin`] is assumed to be the only one supported.
286 /// See [`Offer::chains`] on how this relates to the payment currency.
288 /// Successive calls to this method will add another chain hash.
289 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
290 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
291 if !chains.contains(&chain) {
298 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
300 /// Successive calls to this method will override the previous setting.
301 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
302 $self.amount(Amount::Bitcoin { amount_msats })
305 /// Sets the [`Offer::amount`].
307 /// Successive calls to this method will override the previous setting.
308 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
309 $self.offer.amount = Some(amount);
313 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
314 /// already passed is valid and can be checked for using [`Offer::is_expired`].
316 /// Successive calls to this method will override the previous setting.
317 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
318 $self.offer.absolute_expiry = Some(absolute_expiry);
322 /// Sets the [`Offer::issuer`].
324 /// Successive calls to this method will override the previous setting.
325 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
326 $self.offer.issuer = Some(issuer);
330 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
331 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
333 /// Successive calls to this method will add another blinded path. Caller is responsible for not
334 /// adding duplicate paths.
335 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
336 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
340 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
341 /// [`Quantity::One`].
343 /// Successive calls to this method will override the previous setting.
344 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
345 $self.offer.supported_quantity = quantity;
349 /// Builds an [`Offer`] from the builder's settings.
350 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
351 match $self.offer.amount {
352 Some(Amount::Bitcoin { amount_msats }) => {
353 if amount_msats > MAX_VALUE_MSAT {
354 return Err(Bolt12SemanticError::InvalidAmount);
357 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
361 if let Some(chains) = &$self.offer.chains {
362 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
363 $self.offer.chains = None;
367 Ok($self.build_without_checks())
370 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
371 // Create the metadata for stateless verification of an InvoiceRequest.
372 if let Some(mut metadata) = $self.offer.metadata.take() {
373 if metadata.has_derivation_material() {
374 if $self.offer.paths.is_none() {
375 metadata = metadata.without_keys();
378 let mut tlv_stream = $self.offer.as_tlv_stream();
379 debug_assert_eq!(tlv_stream.metadata, None);
380 tlv_stream.metadata = None;
381 if metadata.derives_recipient_keys() {
382 tlv_stream.node_id = None;
385 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
386 metadata = derived_metadata;
387 if let Some(keys) = keys {
388 $self.offer.signing_pubkey = keys.public_key();
392 $self.offer.metadata = Some(metadata);
395 let mut bytes = Vec::new();
396 $self.offer.write(&mut bytes).unwrap();
398 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
402 #[cfg(not(c_bindings))]
403 contents: $self.offer,
405 contents: $self.offer.clone(),
412 macro_rules! offer_builder_test_methods { (
413 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
415 #[cfg_attr(c_bindings, allow(dead_code))]
416 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
417 $self.offer.features = features;
421 #[cfg_attr(c_bindings, allow(dead_code))]
422 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
423 $self.offer.chains = None;
427 #[cfg_attr(c_bindings, allow(dead_code))]
428 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
429 $self.offer.paths = None;
433 #[cfg_attr(c_bindings, allow(dead_code))]
434 pub(super) fn build_unchecked($self: $self_type) -> Offer {
435 $self.build_without_checks()
439 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
440 offer_builder_methods!(self, Self, Self, self, mut);
443 offer_builder_test_methods!(self, Self, Self, self, mut);
446 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
447 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
450 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
451 offer_derived_metadata_builder_methods!(T);
454 #[cfg(all(c_bindings, not(test)))]
455 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
456 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
457 offer_builder_methods!(self, &mut Self, (), ());
460 #[cfg(all(c_bindings, test))]
461 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
462 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
463 offer_builder_methods!(self, &mut Self, &mut Self, self);
464 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
467 #[cfg(all(c_bindings, not(test)))]
468 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
469 offer_derived_metadata_builder_methods!(secp256k1::All);
470 offer_builder_methods!(self, &mut Self, (), ());
473 #[cfg(all(c_bindings, test))]
474 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
475 offer_derived_metadata_builder_methods!(secp256k1::All);
476 offer_builder_methods!(self, &mut Self, &mut Self, self);
477 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
481 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
482 for OfferWithDerivedMetadataBuilder<'a> {
483 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
484 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
486 Self { offer, metadata_strategy, secp_ctx }
491 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
492 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
493 fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
494 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
496 Self { offer, metadata_strategy, secp_ctx }
500 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
502 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
503 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
504 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
506 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
509 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
511 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
512 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
513 #[derive(Clone, Debug)]
515 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
517 pub(super) bytes: Vec<u8>,
518 pub(super) contents: OfferContents,
522 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
523 /// [`Bolt12Invoice`].
525 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
526 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
527 #[derive(Clone, Debug)]
528 #[cfg_attr(test, derive(PartialEq))]
529 pub(super) struct OfferContents {
530 chains: Option<Vec<ChainHash>>,
531 metadata: Option<Metadata>,
532 amount: Option<Amount>,
534 features: OfferFeatures,
535 absolute_expiry: Option<Duration>,
536 issuer: Option<String>,
537 paths: Option<Vec<BlindedPath>>,
538 supported_quantity: Quantity,
539 signing_pubkey: PublicKey,
542 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
543 // TODO: Return a slice once ChainHash has constants.
544 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
545 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
546 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
547 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
548 /// for the selected chain.
549 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
553 // TODO: Link to corresponding method in `InvoiceRequest`.
554 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
555 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
556 pub fn metadata(&$self) -> Option<&Vec<u8>> {
560 /// The minimum amount required for a successful payment of a single item.
561 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
565 /// A complete description of the purpose of the payment. Intended to be displayed to the user
566 /// but with the caveat that it has not been verified in any way.
567 pub fn description(&$self) -> $crate::util::string::PrintableString {
568 $contents.description()
571 /// Features pertaining to the offer.
572 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
573 &$contents.features()
576 /// Duration since the Unix epoch when an invoice should no longer be requested.
578 /// If `None`, the offer does not expire.
579 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
580 $contents.absolute_expiry()
583 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
584 /// displayed to the user but with the caveat that it has not been verified in any way.
585 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
589 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
590 /// recipient privacy by obfuscating its node id.
591 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
595 /// The quantity of items supported.
596 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
597 $contents.supported_quantity()
600 /// The public key used by the recipient to sign invoices.
601 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
602 $contents.signing_pubkey()
607 offer_accessors!(self, self.contents);
609 /// Returns the id of the offer.
610 pub fn id(&self) -> OfferId {
614 pub(super) fn implied_chain(&self) -> ChainHash {
615 self.contents.implied_chain()
618 /// Returns whether the given chain is supported by the offer.
619 pub fn supports_chain(&self, chain: ChainHash) -> bool {
620 self.contents.supports_chain(chain)
623 /// Whether the offer has expired.
624 #[cfg(feature = "std")]
625 pub fn is_expired(&self) -> bool {
626 self.contents.is_expired()
629 /// Whether the offer has expired given the duration since the Unix epoch.
630 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
631 self.contents.is_expired_no_std(duration_since_epoch)
634 /// Returns whether the given quantity is valid for the offer.
635 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
636 self.contents.is_valid_quantity(quantity)
639 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
641 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
642 pub fn expects_quantity(&self) -> bool {
643 self.contents.expects_quantity()
647 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
648 /// Similar to [`Offer::request_invoice`] except it:
649 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
651 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
652 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
653 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
654 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
655 /// be used when sending the payment for the requested invoice.
657 /// Useful to protect the sender's privacy.
659 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
660 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
661 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
662 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
663 pub fn request_invoice_deriving_payer_id<
665 #[cfg(not(c_bindings))]
666 T: secp256k1::Signing
668 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
669 #[cfg(not(c_bindings))]
670 secp_ctx: &'b Secp256k1<T>,
672 secp_ctx: &'b Secp256k1<secp256k1::All>,
673 payment_id: PaymentId
674 ) -> Result<$builder, Bolt12SemanticError>
676 ES::Target: EntropySource,
678 if $self.offer_features().requires_unknown_bits() {
679 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
682 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
686 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
687 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
688 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
690 /// Useful for recurring payments using the same `payer_id` with different invoices.
692 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
693 pub fn request_invoice_deriving_metadata<ES: Deref>(
694 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
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_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
707 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
708 /// which will be reflected in the `Bolt12Invoice` response.
710 /// The `metadata` is useful for including information about the derivation of `payer_id` such
711 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
712 /// hashing in the signature calculation.
714 /// This should not leak any information such as by using a simple BIP-32 derivation path.
715 /// Otherwise, payments may be correlated.
717 /// Errors if the offer contains unknown required features.
719 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
720 pub fn request_invoice(
721 &$self, metadata: Vec<u8>, payer_id: PublicKey
722 ) -> Result<$builder, Bolt12SemanticError> {
723 if $self.offer_features().requires_unknown_bits() {
724 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
727 Ok(<$builder>::new($self, metadata, payer_id))
731 #[cfg(not(c_bindings))]
733 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
734 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
739 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
740 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
745 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
746 self.contents.as_tlv_stream()
750 impl AsRef<[u8]> for Offer {
751 fn as_ref(&self) -> &[u8] {
756 impl PartialEq for Offer {
757 fn eq(&self, other: &Self) -> bool {
758 self.bytes.eq(&other.bytes)
764 impl Hash for Offer {
765 fn hash<H: Hasher>(&self, state: &mut H) {
766 self.bytes.hash(state);
771 pub fn chains(&self) -> Vec<ChainHash> {
772 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
775 pub fn implied_chain(&self) -> ChainHash {
776 ChainHash::using_genesis_block(Network::Bitcoin)
779 pub fn supports_chain(&self, chain: ChainHash) -> bool {
780 self.chains().contains(&chain)
783 pub fn metadata(&self) -> Option<&Vec<u8>> {
784 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
787 pub fn amount(&self) -> Option<&Amount> {
791 pub fn description(&self) -> PrintableString {
792 PrintableString(&self.description)
795 pub fn features(&self) -> &OfferFeatures {
799 pub fn absolute_expiry(&self) -> Option<Duration> {
803 #[cfg(feature = "std")]
804 pub(super) fn is_expired(&self) -> bool {
805 SystemTime::UNIX_EPOCH
807 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
811 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
813 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
817 pub fn issuer(&self) -> Option<PrintableString> {
818 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
821 pub fn paths(&self) -> &[BlindedPath] {
822 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
825 pub(super) fn check_amount_msats_for_quantity(
826 &self, amount_msats: Option<u64>, quantity: Option<u64>
827 ) -> Result<(), Bolt12SemanticError> {
828 let offer_amount_msats = match self.amount {
830 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
831 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
834 if !self.expects_quantity() || quantity.is_some() {
835 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
836 .ok_or(Bolt12SemanticError::InvalidAmount)?;
837 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
839 if amount_msats < expected_amount_msats {
840 return Err(Bolt12SemanticError::InsufficientAmount);
843 if amount_msats > MAX_VALUE_MSAT {
844 return Err(Bolt12SemanticError::InvalidAmount);
851 pub fn supported_quantity(&self) -> Quantity {
852 self.supported_quantity
855 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
856 let expects_quantity = self.expects_quantity();
858 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
859 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
860 Some(quantity) if !self.is_valid_quantity(quantity) => {
861 Err(Bolt12SemanticError::InvalidQuantity)
867 fn is_valid_quantity(&self, quantity: u64) -> bool {
868 match self.supported_quantity {
869 Quantity::Bounded(n) => quantity <= n.get(),
870 Quantity::Unbounded => quantity > 0,
871 Quantity::One => quantity == 1,
875 fn expects_quantity(&self) -> bool {
876 match self.supported_quantity {
877 Quantity::Bounded(_) => true,
878 Quantity::Unbounded => true,
879 Quantity::One => false,
883 pub(super) fn signing_pubkey(&self) -> PublicKey {
887 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
888 pub(super) fn verify<T: secp256k1::Signing>(
889 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
890 ) -> Result<Option<KeyPair>, ()> {
891 match self.metadata() {
893 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
894 match record.r#type {
895 OFFER_METADATA_TYPE => false,
896 OFFER_NODE_ID_TYPE => {
897 !self.metadata.as_ref().unwrap().derives_recipient_keys()
902 signer::verify_recipient_metadata(
903 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
910 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
911 let (currency, amount) = match &self.amount {
912 None => (None, None),
913 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
914 Some(Amount::Currency { iso4217_code, amount }) => (
915 Some(iso4217_code), Some(*amount)
920 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
924 chains: self.chains.as_ref(),
925 metadata: self.metadata(),
928 description: Some(&self.description),
930 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
931 paths: self.paths.as_ref(),
932 issuer: self.issuer.as_ref(),
933 quantity_max: self.supported_quantity.to_tlv_record(),
934 node_id: Some(&self.signing_pubkey),
939 impl Writeable for Offer {
940 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
941 WithoutLength(&self.bytes).write(writer)
945 impl Writeable for OfferContents {
946 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
947 self.as_tlv_stream().write(writer)
951 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
952 /// another currency.
953 #[derive(Clone, Debug, PartialEq)]
955 /// An amount of bitcoin.
957 /// The amount in millisatoshi.
960 /// An amount of currency specified using ISO 4712.
962 /// The currency that the amount is denominated in.
963 iso4217_code: CurrencyCode,
964 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
969 /// An ISO 4712 three-letter currency code (e.g., USD).
970 pub type CurrencyCode = [u8; 3];
972 /// Quantity of items supported by an [`Offer`].
973 #[derive(Clone, Copy, Debug, PartialEq)]
975 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
976 /// but is limited (e.g., because of per customer or inventory limits).
978 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
981 /// One or more items. Use when more than one item can be requested without any limit.
983 /// Only one item. Use when only a single item can be requested.
988 fn to_tlv_record(&self) -> Option<u64> {
990 Quantity::Bounded(n) => Some(n.get()),
991 Quantity::Unbounded => Some(0),
992 Quantity::One => None,
997 /// Valid type range for offer TLV records.
998 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
1000 /// TLV record type for [`Offer::metadata`].
1001 const OFFER_METADATA_TYPE: u64 = 4;
1003 /// TLV record type for [`Offer::signing_pubkey`].
1004 const OFFER_NODE_ID_TYPE: u64 = 22;
1006 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
1007 (2, chains: (Vec<ChainHash>, WithoutLength)),
1008 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1009 (6, currency: CurrencyCode),
1010 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
1011 (10, description: (String, WithoutLength)),
1012 (12, features: (OfferFeatures, WithoutLength)),
1013 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
1014 (16, paths: (Vec<BlindedPath>, WithoutLength)),
1015 (18, issuer: (String, WithoutLength)),
1016 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
1017 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
1020 impl Bech32Encode for Offer {
1021 const BECH32_HRP: &'static str = "lno";
1024 impl FromStr for Offer {
1025 type Err = Bolt12ParseError;
1027 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
1028 Self::from_bech32_str(s)
1032 impl TryFrom<Vec<u8>> for Offer {
1033 type Error = Bolt12ParseError;
1035 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1036 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1037 let ParsedMessage { bytes, tlv_stream } = offer;
1038 let contents = OfferContents::try_from(tlv_stream)?;
1039 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
1041 Ok(Offer { bytes, contents, id })
1045 impl TryFrom<OfferTlvStream> for OfferContents {
1046 type Error = Bolt12SemanticError;
1048 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1049 let OfferTlvStream {
1050 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1051 issuer, quantity_max, node_id,
1054 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1056 let amount = match (currency, amount) {
1057 (None, None) => None,
1058 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1059 return Err(Bolt12SemanticError::InvalidAmount);
1061 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1062 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1063 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1066 let description = match description {
1067 None => return Err(Bolt12SemanticError::MissingDescription),
1068 Some(description) => description,
1071 let features = features.unwrap_or_else(OfferFeatures::empty);
1073 let absolute_expiry = absolute_expiry
1074 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1076 let supported_quantity = match quantity_max {
1077 None => Quantity::One,
1078 Some(0) => Quantity::Unbounded,
1079 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1082 let signing_pubkey = match node_id {
1083 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1084 Some(node_id) => node_id,
1088 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1089 supported_quantity, signing_pubkey,
1094 impl core::fmt::Display for Offer {
1095 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1096 self.fmt_bech32_str(f)
1102 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1103 #[cfg(not(c_bindings))]
1105 super::OfferBuilder,
1109 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1112 use bitcoin::blockdata::constants::ChainHash;
1113 use bitcoin::network::constants::Network;
1114 use bitcoin::secp256k1::Secp256k1;
1115 use core::num::NonZeroU64;
1116 use core::time::Duration;
1117 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1118 use crate::sign::KeyMaterial;
1119 use crate::ln::features::OfferFeatures;
1120 use crate::ln::inbound_payment::ExpandedKey;
1121 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1122 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1123 use crate::offers::test_utils::*;
1124 use crate::util::ser::{BigSize, Writeable};
1125 use crate::util::string::PrintableString;
1128 fn builds_offer_with_defaults() {
1129 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1131 let mut buffer = Vec::new();
1132 offer.write(&mut buffer).unwrap();
1134 assert_eq!(offer.bytes, buffer.as_slice());
1135 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1136 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1137 assert_eq!(offer.metadata(), None);
1138 assert_eq!(offer.amount(), None);
1139 assert_eq!(offer.description(), PrintableString("foo"));
1140 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1141 assert_eq!(offer.absolute_expiry(), None);
1142 #[cfg(feature = "std")]
1143 assert!(!offer.is_expired());
1144 assert_eq!(offer.paths(), &[]);
1145 assert_eq!(offer.issuer(), None);
1146 assert_eq!(offer.supported_quantity(), Quantity::One);
1147 assert_eq!(offer.signing_pubkey(), pubkey(42));
1150 offer.as_tlv_stream(),
1156 description: Some(&String::from("foo")),
1158 absolute_expiry: None,
1162 node_id: Some(&pubkey(42)),
1166 if let Err(e) = Offer::try_from(buffer) {
1167 panic!("error parsing offer: {:?}", e);
1172 fn builds_offer_with_chains() {
1173 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1174 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1176 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1177 .chain(Network::Bitcoin)
1180 assert!(offer.supports_chain(mainnet));
1181 assert_eq!(offer.chains(), vec![mainnet]);
1182 assert_eq!(offer.as_tlv_stream().chains, None);
1184 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1185 .chain(Network::Testnet)
1188 assert!(offer.supports_chain(testnet));
1189 assert_eq!(offer.chains(), vec![testnet]);
1190 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1192 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1193 .chain(Network::Testnet)
1194 .chain(Network::Testnet)
1197 assert!(offer.supports_chain(testnet));
1198 assert_eq!(offer.chains(), vec![testnet]);
1199 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1201 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1202 .chain(Network::Bitcoin)
1203 .chain(Network::Testnet)
1206 assert!(offer.supports_chain(mainnet));
1207 assert!(offer.supports_chain(testnet));
1208 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1209 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1213 fn builds_offer_with_metadata() {
1214 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1215 .metadata(vec![42; 32]).unwrap()
1218 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1219 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1221 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1222 .metadata(vec![42; 32]).unwrap()
1223 .metadata(vec![43; 32]).unwrap()
1226 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1227 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1231 fn builds_offer_with_metadata_derived() {
1232 let desc = "foo".to_string();
1233 let node_id = recipient_pubkey();
1234 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1235 let entropy = FixedEntropy {};
1236 let secp_ctx = Secp256k1::new();
1239 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1240 let offer = OfferBuilder
1241 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1244 assert_eq!(offer.signing_pubkey(), node_id);
1246 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248 .sign(payer_sign).unwrap();
1249 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1251 // Fails verification with altered offer field
1252 let mut tlv_stream = offer.as_tlv_stream();
1253 tlv_stream.amount = Some(100);
1255 let mut encoded_offer = Vec::new();
1256 tlv_stream.write(&mut encoded_offer).unwrap();
1258 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1259 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1261 .sign(payer_sign).unwrap();
1262 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1264 // Fails verification with altered metadata
1265 let mut tlv_stream = offer.as_tlv_stream();
1266 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1267 tlv_stream.metadata = Some(&metadata);
1269 let mut encoded_offer = Vec::new();
1270 tlv_stream.write(&mut encoded_offer).unwrap();
1272 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1273 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1275 .sign(payer_sign).unwrap();
1276 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1280 fn builds_offer_with_derived_signing_pubkey() {
1281 let desc = "foo".to_string();
1282 let node_id = recipient_pubkey();
1283 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1284 let entropy = FixedEntropy {};
1285 let secp_ctx = Secp256k1::new();
1287 let blinded_path = BlindedPath {
1288 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1289 blinding_point: pubkey(41),
1291 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1292 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1297 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1298 let offer = OfferBuilder
1299 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1303 assert_ne!(offer.signing_pubkey(), node_id);
1305 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1307 .sign(payer_sign).unwrap();
1308 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1310 // Fails verification with altered offer field
1311 let mut tlv_stream = offer.as_tlv_stream();
1312 tlv_stream.amount = Some(100);
1314 let mut encoded_offer = Vec::new();
1315 tlv_stream.write(&mut encoded_offer).unwrap();
1317 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1318 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1320 .sign(payer_sign).unwrap();
1321 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1323 // Fails verification with altered signing pubkey
1324 let mut tlv_stream = offer.as_tlv_stream();
1325 let signing_pubkey = pubkey(1);
1326 tlv_stream.node_id = Some(&signing_pubkey);
1328 let mut encoded_offer = Vec::new();
1329 tlv_stream.write(&mut encoded_offer).unwrap();
1331 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1332 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1334 .sign(payer_sign).unwrap();
1335 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1339 fn builds_offer_with_amount() {
1340 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1341 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1343 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1347 let tlv_stream = offer.as_tlv_stream();
1348 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1349 assert_eq!(tlv_stream.amount, Some(1000));
1350 assert_eq!(tlv_stream.currency, None);
1352 #[cfg(not(c_bindings))]
1353 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1354 .amount(currency_amount.clone());
1356 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1358 builder.amount(currency_amount.clone());
1359 let tlv_stream = builder.offer.as_tlv_stream();
1360 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1361 assert_eq!(tlv_stream.amount, Some(10));
1362 assert_eq!(tlv_stream.currency, Some(b"USD"));
1363 match builder.build() {
1364 Ok(_) => panic!("expected error"),
1365 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1368 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1369 .amount(currency_amount.clone())
1370 .amount(bitcoin_amount.clone())
1373 let tlv_stream = offer.as_tlv_stream();
1374 assert_eq!(tlv_stream.amount, Some(1000));
1375 assert_eq!(tlv_stream.currency, None);
1377 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1378 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1379 Ok(_) => panic!("expected error"),
1380 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1385 fn builds_offer_with_features() {
1386 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1387 .features_unchecked(OfferFeatures::unknown())
1390 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1391 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1393 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1394 .features_unchecked(OfferFeatures::unknown())
1395 .features_unchecked(OfferFeatures::empty())
1398 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1399 assert_eq!(offer.as_tlv_stream().features, None);
1403 fn builds_offer_with_absolute_expiry() {
1404 let future_expiry = Duration::from_secs(u64::max_value());
1405 let past_expiry = Duration::from_secs(0);
1406 let now = future_expiry - Duration::from_secs(1_000);
1408 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1409 .absolute_expiry(future_expiry)
1412 #[cfg(feature = "std")]
1413 assert!(!offer.is_expired());
1414 assert!(!offer.is_expired_no_std(now));
1415 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1416 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1418 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1419 .absolute_expiry(future_expiry)
1420 .absolute_expiry(past_expiry)
1423 #[cfg(feature = "std")]
1424 assert!(offer.is_expired());
1425 assert!(offer.is_expired_no_std(now));
1426 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1427 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1431 fn builds_offer_with_paths() {
1434 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1435 blinding_point: pubkey(41),
1437 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1438 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1442 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1443 blinding_point: pubkey(41),
1445 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1446 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1451 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1452 .path(paths[0].clone())
1453 .path(paths[1].clone())
1456 let tlv_stream = offer.as_tlv_stream();
1457 assert_eq!(offer.paths(), paths.as_slice());
1458 assert_eq!(offer.signing_pubkey(), pubkey(42));
1459 assert_ne!(pubkey(42), pubkey(44));
1460 assert_eq!(tlv_stream.paths, Some(&paths));
1461 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1465 fn builds_offer_with_issuer() {
1466 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1467 .issuer("bar".into())
1470 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1471 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1473 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1474 .issuer("bar".into())
1475 .issuer("baz".into())
1478 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1479 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1483 fn builds_offer_with_supported_quantity() {
1484 let one = NonZeroU64::new(1).unwrap();
1485 let ten = NonZeroU64::new(10).unwrap();
1487 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1488 .supported_quantity(Quantity::One)
1491 let tlv_stream = offer.as_tlv_stream();
1492 assert_eq!(offer.supported_quantity(), Quantity::One);
1493 assert_eq!(tlv_stream.quantity_max, None);
1495 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1496 .supported_quantity(Quantity::Unbounded)
1499 let tlv_stream = offer.as_tlv_stream();
1500 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1501 assert_eq!(tlv_stream.quantity_max, Some(0));
1503 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1504 .supported_quantity(Quantity::Bounded(ten))
1507 let tlv_stream = offer.as_tlv_stream();
1508 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1509 assert_eq!(tlv_stream.quantity_max, Some(10));
1511 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1512 .supported_quantity(Quantity::Bounded(one))
1515 let tlv_stream = offer.as_tlv_stream();
1516 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1517 assert_eq!(tlv_stream.quantity_max, Some(1));
1519 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1520 .supported_quantity(Quantity::Bounded(ten))
1521 .supported_quantity(Quantity::One)
1524 let tlv_stream = offer.as_tlv_stream();
1525 assert_eq!(offer.supported_quantity(), Quantity::One);
1526 assert_eq!(tlv_stream.quantity_max, None);
1530 fn fails_requesting_invoice_with_unknown_required_features() {
1531 match OfferBuilder::new("foo".into(), pubkey(42))
1532 .features_unchecked(OfferFeatures::unknown())
1534 .request_invoice(vec![1; 32], pubkey(43))
1536 Ok(_) => panic!("expected error"),
1537 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1542 fn parses_offer_with_chains() {
1543 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1544 .chain(Network::Bitcoin)
1545 .chain(Network::Testnet)
1548 if let Err(e) = offer.to_string().parse::<Offer>() {
1549 panic!("error parsing offer: {:?}", e);
1554 fn parses_offer_with_amount() {
1555 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1556 .amount(Amount::Bitcoin { amount_msats: 1000 })
1559 if let Err(e) = offer.to_string().parse::<Offer>() {
1560 panic!("error parsing offer: {:?}", e);
1563 let mut tlv_stream = offer.as_tlv_stream();
1564 tlv_stream.amount = Some(1000);
1565 tlv_stream.currency = Some(b"USD");
1567 let mut encoded_offer = Vec::new();
1568 tlv_stream.write(&mut encoded_offer).unwrap();
1570 if let Err(e) = Offer::try_from(encoded_offer) {
1571 panic!("error parsing offer: {:?}", e);
1574 let mut tlv_stream = offer.as_tlv_stream();
1575 tlv_stream.amount = None;
1576 tlv_stream.currency = Some(b"USD");
1578 let mut encoded_offer = Vec::new();
1579 tlv_stream.write(&mut encoded_offer).unwrap();
1581 match Offer::try_from(encoded_offer) {
1582 Ok(_) => panic!("expected error"),
1583 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1586 let mut tlv_stream = offer.as_tlv_stream();
1587 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1588 tlv_stream.currency = None;
1590 let mut encoded_offer = Vec::new();
1591 tlv_stream.write(&mut encoded_offer).unwrap();
1593 match Offer::try_from(encoded_offer) {
1594 Ok(_) => panic!("expected error"),
1595 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1600 fn parses_offer_with_description() {
1601 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1602 if let Err(e) = offer.to_string().parse::<Offer>() {
1603 panic!("error parsing offer: {:?}", e);
1606 let mut tlv_stream = offer.as_tlv_stream();
1607 tlv_stream.description = None;
1609 let mut encoded_offer = Vec::new();
1610 tlv_stream.write(&mut encoded_offer).unwrap();
1612 match Offer::try_from(encoded_offer) {
1613 Ok(_) => panic!("expected error"),
1615 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1621 fn parses_offer_with_paths() {
1622 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1624 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1625 blinding_point: pubkey(41),
1627 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1628 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1632 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1633 blinding_point: pubkey(41),
1635 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1636 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1641 if let Err(e) = offer.to_string().parse::<Offer>() {
1642 panic!("error parsing offer: {:?}", e);
1645 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1646 builder.offer.paths = Some(vec![]);
1648 let offer = builder.build().unwrap();
1649 if let Err(e) = offer.to_string().parse::<Offer>() {
1650 panic!("error parsing offer: {:?}", e);
1655 fn parses_offer_with_quantity() {
1656 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1657 .supported_quantity(Quantity::One)
1660 if let Err(e) = offer.to_string().parse::<Offer>() {
1661 panic!("error parsing offer: {:?}", e);
1664 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1665 .supported_quantity(Quantity::Unbounded)
1668 if let Err(e) = offer.to_string().parse::<Offer>() {
1669 panic!("error parsing offer: {:?}", e);
1672 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1673 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1676 if let Err(e) = offer.to_string().parse::<Offer>() {
1677 panic!("error parsing offer: {:?}", e);
1680 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1681 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1684 if let Err(e) = offer.to_string().parse::<Offer>() {
1685 panic!("error parsing offer: {:?}", e);
1690 fn parses_offer_with_node_id() {
1691 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1692 if let Err(e) = offer.to_string().parse::<Offer>() {
1693 panic!("error parsing offer: {:?}", e);
1696 let mut tlv_stream = offer.as_tlv_stream();
1697 tlv_stream.node_id = None;
1699 let mut encoded_offer = Vec::new();
1700 tlv_stream.write(&mut encoded_offer).unwrap();
1702 match Offer::try_from(encoded_offer) {
1703 Ok(_) => panic!("expected error"),
1705 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1711 fn fails_parsing_offer_with_extra_tlv_records() {
1712 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1714 let mut encoded_offer = Vec::new();
1715 offer.write(&mut encoded_offer).unwrap();
1716 BigSize(80).write(&mut encoded_offer).unwrap();
1717 BigSize(32).write(&mut encoded_offer).unwrap();
1718 [42u8; 32].write(&mut encoded_offer).unwrap();
1720 match Offer::try_from(encoded_offer) {
1721 Ok(_) => panic!("expected error"),
1722 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1729 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1730 use crate::ln::msgs::DecodeError;
1733 fn parses_bech32_encoded_offers() {
1735 // Minimal bolt12 offer
1736 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1739 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1741 // for bitcoin (redundant)
1742 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1744 // for bitcoin or liquidv1
1745 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1748 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1751 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1754 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1757 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1760 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1763 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1765 // with unlimited (or unknown) quantity
1766 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1768 // with single quantity (weird but valid)
1769 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1772 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1774 // with blinded path via Bob (0x424242...), blinding 020202...
1775 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1777 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1778 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1780 // unknown odd field
1781 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1783 for encoded_offer in &offers {
1784 if let Err(e) = encoded_offer.parse::<Offer>() {
1785 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1791 fn fails_parsing_bech32_encoded_offers() {
1792 // Malformed: fields out of order
1794 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1795 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1798 // Malformed: unknown even TLV type 78
1800 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1801 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1806 "lno1".parse::<Offer>(),
1807 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1810 // Malformed: truncated at type
1812 "lno1pg".parse::<Offer>(),
1813 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1816 // Malformed: truncated in length
1818 "lno1pt7s".parse::<Offer>(),
1819 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1822 // Malformed: truncated after length
1824 "lno1pgpq".parse::<Offer>(),
1825 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1828 // Malformed: truncated in description
1830 "lno1pgpyz".parse::<Offer>(),
1831 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1834 // Malformed: invalid offer_chains length
1836 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1837 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1840 // Malformed: truncated currency UTF-8
1842 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1843 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1846 // Malformed: invalid currency UTF-8
1848 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1849 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1852 // Malformed: truncated description UTF-8
1854 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1855 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1858 // Malformed: invalid description UTF-8
1860 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1861 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1864 // Malformed: truncated offer_paths
1866 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1867 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1870 // Malformed: zero num_hops in blinded_path
1872 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1873 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1876 // Malformed: truncated onionmsg_hop in blinded_path
1878 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1879 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1882 // Malformed: bad first_node_id in blinded_path
1884 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1885 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1888 // Malformed: bad blinding in blinded_path
1890 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1891 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1894 // Malformed: bad blinded_node_id in onionmsg_hop
1896 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1897 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1900 // Malformed: truncated issuer UTF-8
1902 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1903 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1906 // Malformed: invalid issuer UTF-8
1908 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1909 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1912 // Malformed: invalid offer_node_id
1914 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1915 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1918 // Contains type >= 80
1920 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1921 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1924 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1925 // Contains unknown feature 22
1927 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1930 // Missing offer_description
1932 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1933 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1936 // Missing offer_node_id"
1938 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1939 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),