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::convert::TryFrom;
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::MAX_VALUE_MSAT;
95 use crate::offers::merkle::TlvStream;
96 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
97 use crate::offers::signer::{Metadata, MetadataMaterial, self};
98 use crate::util::ser::{HighZeroBytesDroppedBigSize, 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 /// Builds an [`Offer`] for the "offer to be paid" flow.
120 /// See [module-level documentation] for usage.
122 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
124 /// [module-level documentation]: self
125 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
126 offer: OfferContents,
127 metadata_strategy: core::marker::PhantomData<M>,
128 secp_ctx: Option<&'a Secp256k1<T>>,
131 /// Builds an [`Offer`] for the "offer to be paid" flow.
133 /// See [module-level documentation] for usage.
135 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
137 /// [module-level documentation]: self
139 pub struct OfferWithExplicitMetadataBuilder<'a> {
140 offer: OfferContents,
141 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
142 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
145 /// Builds an [`Offer`] for the "offer to be paid" flow.
147 /// See [module-level documentation] for usage.
149 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
151 /// [module-level documentation]: self
153 pub struct OfferWithDerivedMetadataBuilder<'a> {
154 offer: OfferContents,
155 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
156 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
159 /// Indicates how [`Offer::metadata`] may be set.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub trait MetadataStrategy {}
164 /// [`Offer::metadata`] may be explicitly set or left empty.
166 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
167 pub struct ExplicitMetadata {}
169 /// [`Offer::metadata`] will be derived.
171 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
172 pub struct DerivedMetadata {}
174 impl MetadataStrategy for ExplicitMetadata {}
176 impl MetadataStrategy for DerivedMetadata {}
178 macro_rules! offer_explicit_metadata_builder_methods { (
179 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
181 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
182 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
183 /// while the offer is valid.
185 /// Use a different pubkey per offer to avoid correlating offers.
189 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
190 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
192 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
193 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
194 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
196 offer: OfferContents {
197 chains: None, metadata: None, amount: None, description,
198 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
199 supported_quantity: Quantity::One, signing_pubkey,
201 metadata_strategy: core::marker::PhantomData,
206 /// Sets the [`Offer::metadata`] to the given bytes.
208 /// Successive calls to this method will override the previous setting.
209 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
210 $self.offer.metadata = Some(Metadata::Bytes(metadata));
215 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
216 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
217 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
218 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
219 /// provided `node_id` is used for the signing pubkey.
221 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
222 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
225 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
226 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
227 pub fn deriving_signing_pubkey<ES: Deref>(
228 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
229 secp_ctx: &'a Secp256k1<$secp_context>
230 ) -> Self where ES::Target: EntropySource {
231 let nonce = Nonce::from_entropy_source(entropy_source);
232 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
233 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
235 offer: OfferContents {
236 chains: None, metadata: Some(metadata), amount: None, description,
237 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
238 supported_quantity: Quantity::One, signing_pubkey: node_id,
240 metadata_strategy: core::marker::PhantomData,
241 secp_ctx: Some(secp_ctx),
246 macro_rules! offer_builder_methods { (
247 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
249 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
250 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
252 /// See [`Offer::chains`] on how this relates to the payment currency.
254 /// Successive calls to this method will add another chain hash.
255 pub fn chain($self: $self_type, network: Network) -> $return_type {
256 $self.chain_hash(ChainHash::using_genesis_block(network))
259 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
260 /// [`Network::Bitcoin`] is assumed to be the only one supported.
262 /// See [`Offer::chains`] on how this relates to the payment currency.
264 /// Successive calls to this method will add another chain hash.
265 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
266 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
267 if !chains.contains(&chain) {
274 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
276 /// Successive calls to this method will override the previous setting.
277 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
278 $self.amount(Amount::Bitcoin { amount_msats })
281 /// Sets the [`Offer::amount`].
283 /// Successive calls to this method will override the previous setting.
284 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
285 $self.offer.amount = Some(amount);
289 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
290 /// already passed is valid and can be checked for using [`Offer::is_expired`].
292 /// Successive calls to this method will override the previous setting.
293 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
294 $self.offer.absolute_expiry = Some(absolute_expiry);
298 /// Sets the [`Offer::issuer`].
300 /// Successive calls to this method will override the previous setting.
301 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
302 $self.offer.issuer = Some(issuer);
306 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
307 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
309 /// Successive calls to this method will add another blinded path. Caller is responsible for not
310 /// adding duplicate paths.
311 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
312 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
316 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
317 /// [`Quantity::One`].
319 /// Successive calls to this method will override the previous setting.
320 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
321 $self.offer.supported_quantity = quantity;
325 /// Builds an [`Offer`] from the builder's settings.
326 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
327 match $self.offer.amount {
328 Some(Amount::Bitcoin { amount_msats }) => {
329 if amount_msats > MAX_VALUE_MSAT {
330 return Err(Bolt12SemanticError::InvalidAmount);
333 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
337 if let Some(chains) = &$self.offer.chains {
338 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
339 $self.offer.chains = None;
343 Ok($self.build_without_checks())
346 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
347 // Create the metadata for stateless verification of an InvoiceRequest.
348 if let Some(mut metadata) = $self.offer.metadata.take() {
349 if metadata.has_derivation_material() {
350 if $self.offer.paths.is_none() {
351 metadata = metadata.without_keys();
354 let mut tlv_stream = $self.offer.as_tlv_stream();
355 debug_assert_eq!(tlv_stream.metadata, None);
356 tlv_stream.metadata = None;
357 if metadata.derives_recipient_keys() {
358 tlv_stream.node_id = None;
361 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
362 metadata = derived_metadata;
363 if let Some(keys) = keys {
364 $self.offer.signing_pubkey = keys.public_key();
368 $self.offer.metadata = Some(metadata);
371 let mut bytes = Vec::new();
372 $self.offer.write(&mut bytes).unwrap();
376 #[cfg(not(c_bindings))]
377 contents: $self.offer,
379 contents: $self.offer.clone()
385 macro_rules! offer_builder_test_methods { (
386 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
388 #[cfg_attr(c_bindings, allow(dead_code))]
389 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
390 $self.offer.features = features;
394 #[cfg_attr(c_bindings, allow(dead_code))]
395 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
396 $self.offer.chains = None;
400 #[cfg_attr(c_bindings, allow(dead_code))]
401 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
402 $self.offer.paths = None;
406 #[cfg_attr(c_bindings, allow(dead_code))]
407 pub(super) fn build_unchecked($self: $self_type) -> Offer {
408 $self.build_without_checks()
412 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
413 offer_builder_methods!(self, Self, Self, self, mut);
416 offer_builder_test_methods!(self, Self, Self, self, mut);
419 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
420 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
423 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
424 offer_derived_metadata_builder_methods!(T);
427 #[cfg(all(c_bindings, not(test)))]
428 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
429 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
430 offer_builder_methods!(self, &mut Self, (), ());
433 #[cfg(all(c_bindings, test))]
434 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
435 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
436 offer_builder_methods!(self, &mut Self, &mut Self, self);
437 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
440 #[cfg(all(c_bindings, not(test)))]
441 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
442 offer_derived_metadata_builder_methods!(secp256k1::All);
443 offer_builder_methods!(self, &mut Self, (), ());
446 #[cfg(all(c_bindings, test))]
447 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
448 offer_derived_metadata_builder_methods!(secp256k1::All);
449 offer_builder_methods!(self, &mut Self, &mut Self, self);
450 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
454 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
455 for OfferWithDerivedMetadataBuilder<'a> {
456 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
457 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
459 Self { offer, metadata_strategy, secp_ctx }
463 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
465 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
466 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
467 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
469 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
472 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
474 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
475 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
476 #[derive(Clone, Debug)]
478 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
480 pub(super) bytes: Vec<u8>,
481 pub(super) contents: OfferContents,
484 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
485 /// [`Bolt12Invoice`].
487 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
488 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
489 #[derive(Clone, Debug)]
490 #[cfg_attr(test, derive(PartialEq))]
491 pub(super) struct OfferContents {
492 chains: Option<Vec<ChainHash>>,
493 metadata: Option<Metadata>,
494 amount: Option<Amount>,
496 features: OfferFeatures,
497 absolute_expiry: Option<Duration>,
498 issuer: Option<String>,
499 paths: Option<Vec<BlindedPath>>,
500 supported_quantity: Quantity,
501 signing_pubkey: PublicKey,
504 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
505 // TODO: Return a slice once ChainHash has constants.
506 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
507 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
508 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
509 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
510 /// for the selected chain.
511 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
515 // TODO: Link to corresponding method in `InvoiceRequest`.
516 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
517 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
518 pub fn metadata(&$self) -> Option<&Vec<u8>> {
522 /// The minimum amount required for a successful payment of a single item.
523 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
527 /// A complete description of the purpose of the payment. Intended to be displayed to the user
528 /// but with the caveat that it has not been verified in any way.
529 pub fn description(&$self) -> $crate::util::string::PrintableString {
530 $contents.description()
533 /// Features pertaining to the offer.
534 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
535 &$contents.features()
538 /// Duration since the Unix epoch when an invoice should no longer be requested.
540 /// If `None`, the offer does not expire.
541 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
542 $contents.absolute_expiry()
545 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
546 /// displayed to the user but with the caveat that it has not been verified in any way.
547 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
551 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
552 /// recipient privacy by obfuscating its node id.
553 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
557 /// The quantity of items supported.
558 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
559 $contents.supported_quantity()
562 /// The public key used by the recipient to sign invoices.
563 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
564 $contents.signing_pubkey()
569 offer_accessors!(self, self.contents);
571 pub(super) fn implied_chain(&self) -> ChainHash {
572 self.contents.implied_chain()
575 /// Returns whether the given chain is supported by the offer.
576 pub fn supports_chain(&self, chain: ChainHash) -> bool {
577 self.contents.supports_chain(chain)
580 /// Whether the offer has expired.
581 #[cfg(feature = "std")]
582 pub fn is_expired(&self) -> bool {
583 self.contents.is_expired()
586 /// Whether the offer has expired given the duration since the Unix epoch.
587 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
588 self.contents.is_expired_no_std(duration_since_epoch)
591 /// Returns whether the given quantity is valid for the offer.
592 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
593 self.contents.is_valid_quantity(quantity)
596 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
598 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
599 pub fn expects_quantity(&self) -> bool {
600 self.contents.expects_quantity()
604 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
605 /// Similar to [`Offer::request_invoice`] except it:
606 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
608 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
609 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
610 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
611 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
612 /// be used when sending the payment for the requested invoice.
614 /// Useful to protect the sender's privacy.
616 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
617 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
618 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
619 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
620 pub fn request_invoice_deriving_payer_id<
622 #[cfg(not(c_bindings))]
623 T: secp256k1::Signing
625 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
626 #[cfg(not(c_bindings))]
627 secp_ctx: &'b Secp256k1<T>,
629 secp_ctx: &'b Secp256k1<secp256k1::All>,
630 payment_id: PaymentId
631 ) -> Result<$builder, Bolt12SemanticError>
633 ES::Target: EntropySource,
635 if $self.offer_features().requires_unknown_bits() {
636 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
639 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
643 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
644 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
645 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
647 /// Useful for recurring payments using the same `payer_id` with different invoices.
649 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
650 pub fn request_invoice_deriving_metadata<ES: Deref>(
651 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
652 payment_id: PaymentId
653 ) -> Result<$builder, Bolt12SemanticError>
655 ES::Target: EntropySource,
657 if $self.offer_features().requires_unknown_bits() {
658 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
661 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
664 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
665 /// which will be reflected in the `Bolt12Invoice` response.
667 /// The `metadata` is useful for including information about the derivation of `payer_id` such
668 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
669 /// hashing in the signature calculation.
671 /// This should not leak any information such as by using a simple BIP-32 derivation path.
672 /// Otherwise, payments may be correlated.
674 /// Errors if the offer contains unknown required features.
676 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
677 pub fn request_invoice(
678 &$self, metadata: Vec<u8>, payer_id: PublicKey
679 ) -> Result<$builder, Bolt12SemanticError> {
680 if $self.offer_features().requires_unknown_bits() {
681 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
684 Ok(<$builder>::new($self, metadata, payer_id))
688 #[cfg(not(c_bindings))]
690 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
691 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
696 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
697 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
702 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
703 self.contents.as_tlv_stream()
707 impl AsRef<[u8]> for Offer {
708 fn as_ref(&self) -> &[u8] {
713 impl PartialEq for Offer {
714 fn eq(&self, other: &Self) -> bool {
715 self.bytes.eq(&other.bytes)
721 impl Hash for Offer {
722 fn hash<H: Hasher>(&self, state: &mut H) {
723 self.bytes.hash(state);
728 pub fn chains(&self) -> Vec<ChainHash> {
729 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
732 pub fn implied_chain(&self) -> ChainHash {
733 ChainHash::using_genesis_block(Network::Bitcoin)
736 pub fn supports_chain(&self, chain: ChainHash) -> bool {
737 self.chains().contains(&chain)
740 pub fn metadata(&self) -> Option<&Vec<u8>> {
741 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
744 pub fn amount(&self) -> Option<&Amount> {
748 pub fn description(&self) -> PrintableString {
749 PrintableString(&self.description)
752 pub fn features(&self) -> &OfferFeatures {
756 pub fn absolute_expiry(&self) -> Option<Duration> {
760 #[cfg(feature = "std")]
761 pub(super) fn is_expired(&self) -> bool {
762 SystemTime::UNIX_EPOCH
764 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
768 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
770 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
774 pub fn issuer(&self) -> Option<PrintableString> {
775 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
778 pub fn paths(&self) -> &[BlindedPath] {
779 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
782 pub(super) fn check_amount_msats_for_quantity(
783 &self, amount_msats: Option<u64>, quantity: Option<u64>
784 ) -> Result<(), Bolt12SemanticError> {
785 let offer_amount_msats = match self.amount {
787 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
788 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
791 if !self.expects_quantity() || quantity.is_some() {
792 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
793 .ok_or(Bolt12SemanticError::InvalidAmount)?;
794 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
796 if amount_msats < expected_amount_msats {
797 return Err(Bolt12SemanticError::InsufficientAmount);
800 if amount_msats > MAX_VALUE_MSAT {
801 return Err(Bolt12SemanticError::InvalidAmount);
808 pub fn supported_quantity(&self) -> Quantity {
809 self.supported_quantity
812 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
813 let expects_quantity = self.expects_quantity();
815 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
816 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
817 Some(quantity) if !self.is_valid_quantity(quantity) => {
818 Err(Bolt12SemanticError::InvalidQuantity)
824 fn is_valid_quantity(&self, quantity: u64) -> bool {
825 match self.supported_quantity {
826 Quantity::Bounded(n) => quantity <= n.get(),
827 Quantity::Unbounded => quantity > 0,
828 Quantity::One => quantity == 1,
832 fn expects_quantity(&self) -> bool {
833 match self.supported_quantity {
834 Quantity::Bounded(_) => true,
835 Quantity::Unbounded => true,
836 Quantity::One => false,
840 pub(super) fn signing_pubkey(&self) -> PublicKey {
844 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
845 pub(super) fn verify<T: secp256k1::Signing>(
846 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
847 ) -> Result<Option<KeyPair>, ()> {
848 match self.metadata() {
850 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
851 match record.r#type {
852 OFFER_METADATA_TYPE => false,
853 OFFER_NODE_ID_TYPE => {
854 !self.metadata.as_ref().unwrap().derives_recipient_keys()
859 signer::verify_recipient_metadata(
860 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
867 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
868 let (currency, amount) = match &self.amount {
869 None => (None, None),
870 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
871 Some(Amount::Currency { iso4217_code, amount }) => (
872 Some(iso4217_code), Some(*amount)
877 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
881 chains: self.chains.as_ref(),
882 metadata: self.metadata(),
885 description: Some(&self.description),
887 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
888 paths: self.paths.as_ref(),
889 issuer: self.issuer.as_ref(),
890 quantity_max: self.supported_quantity.to_tlv_record(),
891 node_id: Some(&self.signing_pubkey),
896 impl Writeable for Offer {
897 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
898 WithoutLength(&self.bytes).write(writer)
902 impl Writeable for OfferContents {
903 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
904 self.as_tlv_stream().write(writer)
908 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
909 /// another currency.
910 #[derive(Clone, Debug, PartialEq)]
912 /// An amount of bitcoin.
914 /// The amount in millisatoshi.
917 /// An amount of currency specified using ISO 4712.
919 /// The currency that the amount is denominated in.
920 iso4217_code: CurrencyCode,
921 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
926 /// An ISO 4712 three-letter currency code (e.g., USD).
927 pub type CurrencyCode = [u8; 3];
929 /// Quantity of items supported by an [`Offer`].
930 #[derive(Clone, Copy, Debug, PartialEq)]
932 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
933 /// but is limited (e.g., because of per customer or inventory limits).
935 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
938 /// One or more items. Use when more than one item can be requested without any limit.
940 /// Only one item. Use when only a single item can be requested.
945 fn to_tlv_record(&self) -> Option<u64> {
947 Quantity::Bounded(n) => Some(n.get()),
948 Quantity::Unbounded => Some(0),
949 Quantity::One => None,
954 /// Valid type range for offer TLV records.
955 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
957 /// TLV record type for [`Offer::metadata`].
958 const OFFER_METADATA_TYPE: u64 = 4;
960 /// TLV record type for [`Offer::signing_pubkey`].
961 const OFFER_NODE_ID_TYPE: u64 = 22;
963 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
964 (2, chains: (Vec<ChainHash>, WithoutLength)),
965 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
966 (6, currency: CurrencyCode),
967 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
968 (10, description: (String, WithoutLength)),
969 (12, features: (OfferFeatures, WithoutLength)),
970 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
971 (16, paths: (Vec<BlindedPath>, WithoutLength)),
972 (18, issuer: (String, WithoutLength)),
973 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
974 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
977 impl Bech32Encode for Offer {
978 const BECH32_HRP: &'static str = "lno";
981 impl FromStr for Offer {
982 type Err = Bolt12ParseError;
984 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
985 Self::from_bech32_str(s)
989 impl TryFrom<Vec<u8>> for Offer {
990 type Error = Bolt12ParseError;
992 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
993 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
994 let ParsedMessage { bytes, tlv_stream } = offer;
995 let contents = OfferContents::try_from(tlv_stream)?;
996 Ok(Offer { bytes, contents })
1000 impl TryFrom<OfferTlvStream> for OfferContents {
1001 type Error = Bolt12SemanticError;
1003 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1004 let OfferTlvStream {
1005 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1006 issuer, quantity_max, node_id,
1009 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1011 let amount = match (currency, amount) {
1012 (None, None) => None,
1013 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1014 return Err(Bolt12SemanticError::InvalidAmount);
1016 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1017 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1018 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1021 let description = match description {
1022 None => return Err(Bolt12SemanticError::MissingDescription),
1023 Some(description) => description,
1026 let features = features.unwrap_or_else(OfferFeatures::empty);
1028 let absolute_expiry = absolute_expiry
1029 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1031 let supported_quantity = match quantity_max {
1032 None => Quantity::One,
1033 Some(0) => Quantity::Unbounded,
1034 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1037 let signing_pubkey = match node_id {
1038 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1039 Some(node_id) => node_id,
1043 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1044 supported_quantity, signing_pubkey,
1049 impl core::fmt::Display for Offer {
1050 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1051 self.fmt_bech32_str(f)
1057 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1058 #[cfg(not(c_bindings))]
1060 super::OfferBuilder,
1064 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1067 use bitcoin::blockdata::constants::ChainHash;
1068 use bitcoin::network::constants::Network;
1069 use bitcoin::secp256k1::Secp256k1;
1070 use core::convert::TryFrom;
1071 use core::num::NonZeroU64;
1072 use core::time::Duration;
1073 use crate::blinded_path::{BlindedHop, BlindedPath};
1074 use crate::sign::KeyMaterial;
1075 use crate::ln::features::OfferFeatures;
1076 use crate::ln::inbound_payment::ExpandedKey;
1077 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1078 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1079 use crate::offers::test_utils::*;
1080 use crate::util::ser::{BigSize, Writeable};
1081 use crate::util::string::PrintableString;
1084 fn builds_offer_with_defaults() {
1085 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1087 let mut buffer = Vec::new();
1088 offer.write(&mut buffer).unwrap();
1090 assert_eq!(offer.bytes, buffer.as_slice());
1091 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1092 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1093 assert_eq!(offer.metadata(), None);
1094 assert_eq!(offer.amount(), None);
1095 assert_eq!(offer.description(), PrintableString("foo"));
1096 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1097 assert_eq!(offer.absolute_expiry(), None);
1098 #[cfg(feature = "std")]
1099 assert!(!offer.is_expired());
1100 assert_eq!(offer.paths(), &[]);
1101 assert_eq!(offer.issuer(), None);
1102 assert_eq!(offer.supported_quantity(), Quantity::One);
1103 assert_eq!(offer.signing_pubkey(), pubkey(42));
1106 offer.as_tlv_stream(),
1112 description: Some(&String::from("foo")),
1114 absolute_expiry: None,
1118 node_id: Some(&pubkey(42)),
1122 if let Err(e) = Offer::try_from(buffer) {
1123 panic!("error parsing offer: {:?}", e);
1128 fn builds_offer_with_chains() {
1129 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1130 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1132 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1133 .chain(Network::Bitcoin)
1136 assert!(offer.supports_chain(mainnet));
1137 assert_eq!(offer.chains(), vec![mainnet]);
1138 assert_eq!(offer.as_tlv_stream().chains, None);
1140 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1141 .chain(Network::Testnet)
1144 assert!(offer.supports_chain(testnet));
1145 assert_eq!(offer.chains(), vec![testnet]);
1146 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1148 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1149 .chain(Network::Testnet)
1150 .chain(Network::Testnet)
1153 assert!(offer.supports_chain(testnet));
1154 assert_eq!(offer.chains(), vec![testnet]);
1155 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1157 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1158 .chain(Network::Bitcoin)
1159 .chain(Network::Testnet)
1162 assert!(offer.supports_chain(mainnet));
1163 assert!(offer.supports_chain(testnet));
1164 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1165 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1169 fn builds_offer_with_metadata() {
1170 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1171 .metadata(vec![42; 32]).unwrap()
1174 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1175 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1177 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1178 .metadata(vec![42; 32]).unwrap()
1179 .metadata(vec![43; 32]).unwrap()
1182 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1183 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1187 fn builds_offer_with_metadata_derived() {
1188 let desc = "foo".to_string();
1189 let node_id = recipient_pubkey();
1190 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1191 let entropy = FixedEntropy {};
1192 let secp_ctx = Secp256k1::new();
1195 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1196 let offer = OfferBuilder
1197 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1200 assert_eq!(offer.signing_pubkey(), node_id);
1202 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1204 .sign(payer_sign).unwrap();
1205 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1207 // Fails verification with altered offer field
1208 let mut tlv_stream = offer.as_tlv_stream();
1209 tlv_stream.amount = Some(100);
1211 let mut encoded_offer = Vec::new();
1212 tlv_stream.write(&mut encoded_offer).unwrap();
1214 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1215 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1217 .sign(payer_sign).unwrap();
1218 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1220 // Fails verification with altered metadata
1221 let mut tlv_stream = offer.as_tlv_stream();
1222 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1223 tlv_stream.metadata = Some(&metadata);
1225 let mut encoded_offer = Vec::new();
1226 tlv_stream.write(&mut encoded_offer).unwrap();
1228 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1229 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231 .sign(payer_sign).unwrap();
1232 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1236 fn builds_offer_with_derived_signing_pubkey() {
1237 let desc = "foo".to_string();
1238 let node_id = recipient_pubkey();
1239 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1240 let entropy = FixedEntropy {};
1241 let secp_ctx = Secp256k1::new();
1243 let blinded_path = BlindedPath {
1244 introduction_node_id: pubkey(40),
1245 blinding_point: pubkey(41),
1247 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1248 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1253 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1254 let offer = OfferBuilder
1255 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1259 assert_ne!(offer.signing_pubkey(), node_id);
1261 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1263 .sign(payer_sign).unwrap();
1264 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1266 // Fails verification with altered offer field
1267 let mut tlv_stream = offer.as_tlv_stream();
1268 tlv_stream.amount = Some(100);
1270 let mut encoded_offer = Vec::new();
1271 tlv_stream.write(&mut encoded_offer).unwrap();
1273 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1274 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1276 .sign(payer_sign).unwrap();
1277 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1279 // Fails verification with altered signing pubkey
1280 let mut tlv_stream = offer.as_tlv_stream();
1281 let signing_pubkey = pubkey(1);
1282 tlv_stream.node_id = Some(&signing_pubkey);
1284 let mut encoded_offer = Vec::new();
1285 tlv_stream.write(&mut encoded_offer).unwrap();
1287 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1288 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1290 .sign(payer_sign).unwrap();
1291 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1295 fn builds_offer_with_amount() {
1296 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1297 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1299 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1303 let tlv_stream = offer.as_tlv_stream();
1304 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1305 assert_eq!(tlv_stream.amount, Some(1000));
1306 assert_eq!(tlv_stream.currency, None);
1308 #[cfg(not(c_bindings))]
1309 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1310 .amount(currency_amount.clone());
1312 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1314 builder.amount(currency_amount.clone());
1315 let tlv_stream = builder.offer.as_tlv_stream();
1316 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1317 assert_eq!(tlv_stream.amount, Some(10));
1318 assert_eq!(tlv_stream.currency, Some(b"USD"));
1319 match builder.build() {
1320 Ok(_) => panic!("expected error"),
1321 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1324 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1325 .amount(currency_amount.clone())
1326 .amount(bitcoin_amount.clone())
1329 let tlv_stream = offer.as_tlv_stream();
1330 assert_eq!(tlv_stream.amount, Some(1000));
1331 assert_eq!(tlv_stream.currency, None);
1333 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1334 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1335 Ok(_) => panic!("expected error"),
1336 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1341 fn builds_offer_with_features() {
1342 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1343 .features_unchecked(OfferFeatures::unknown())
1346 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1347 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1349 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1350 .features_unchecked(OfferFeatures::unknown())
1351 .features_unchecked(OfferFeatures::empty())
1354 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1355 assert_eq!(offer.as_tlv_stream().features, None);
1359 fn builds_offer_with_absolute_expiry() {
1360 let future_expiry = Duration::from_secs(u64::max_value());
1361 let past_expiry = Duration::from_secs(0);
1362 let now = future_expiry - Duration::from_secs(1_000);
1364 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1365 .absolute_expiry(future_expiry)
1368 #[cfg(feature = "std")]
1369 assert!(!offer.is_expired());
1370 assert!(!offer.is_expired_no_std(now));
1371 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1372 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1374 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1375 .absolute_expiry(future_expiry)
1376 .absolute_expiry(past_expiry)
1379 #[cfg(feature = "std")]
1380 assert!(offer.is_expired());
1381 assert!(offer.is_expired_no_std(now));
1382 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1383 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1387 fn builds_offer_with_paths() {
1390 introduction_node_id: pubkey(40),
1391 blinding_point: pubkey(41),
1393 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1394 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1398 introduction_node_id: pubkey(40),
1399 blinding_point: pubkey(41),
1401 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1402 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1407 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1408 .path(paths[0].clone())
1409 .path(paths[1].clone())
1412 let tlv_stream = offer.as_tlv_stream();
1413 assert_eq!(offer.paths(), paths.as_slice());
1414 assert_eq!(offer.signing_pubkey(), pubkey(42));
1415 assert_ne!(pubkey(42), pubkey(44));
1416 assert_eq!(tlv_stream.paths, Some(&paths));
1417 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1421 fn builds_offer_with_issuer() {
1422 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1423 .issuer("bar".into())
1426 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1427 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1429 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1430 .issuer("bar".into())
1431 .issuer("baz".into())
1434 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1435 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1439 fn builds_offer_with_supported_quantity() {
1440 let one = NonZeroU64::new(1).unwrap();
1441 let ten = NonZeroU64::new(10).unwrap();
1443 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1444 .supported_quantity(Quantity::One)
1447 let tlv_stream = offer.as_tlv_stream();
1448 assert_eq!(offer.supported_quantity(), Quantity::One);
1449 assert_eq!(tlv_stream.quantity_max, None);
1451 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1452 .supported_quantity(Quantity::Unbounded)
1455 let tlv_stream = offer.as_tlv_stream();
1456 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1457 assert_eq!(tlv_stream.quantity_max, Some(0));
1459 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1460 .supported_quantity(Quantity::Bounded(ten))
1463 let tlv_stream = offer.as_tlv_stream();
1464 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1465 assert_eq!(tlv_stream.quantity_max, Some(10));
1467 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1468 .supported_quantity(Quantity::Bounded(one))
1471 let tlv_stream = offer.as_tlv_stream();
1472 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1473 assert_eq!(tlv_stream.quantity_max, Some(1));
1475 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1476 .supported_quantity(Quantity::Bounded(ten))
1477 .supported_quantity(Quantity::One)
1480 let tlv_stream = offer.as_tlv_stream();
1481 assert_eq!(offer.supported_quantity(), Quantity::One);
1482 assert_eq!(tlv_stream.quantity_max, None);
1486 fn fails_requesting_invoice_with_unknown_required_features() {
1487 match OfferBuilder::new("foo".into(), pubkey(42))
1488 .features_unchecked(OfferFeatures::unknown())
1490 .request_invoice(vec![1; 32], pubkey(43))
1492 Ok(_) => panic!("expected error"),
1493 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1498 fn parses_offer_with_chains() {
1499 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1500 .chain(Network::Bitcoin)
1501 .chain(Network::Testnet)
1504 if let Err(e) = offer.to_string().parse::<Offer>() {
1505 panic!("error parsing offer: {:?}", e);
1510 fn parses_offer_with_amount() {
1511 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1512 .amount(Amount::Bitcoin { amount_msats: 1000 })
1515 if let Err(e) = offer.to_string().parse::<Offer>() {
1516 panic!("error parsing offer: {:?}", e);
1519 let mut tlv_stream = offer.as_tlv_stream();
1520 tlv_stream.amount = Some(1000);
1521 tlv_stream.currency = Some(b"USD");
1523 let mut encoded_offer = Vec::new();
1524 tlv_stream.write(&mut encoded_offer).unwrap();
1526 if let Err(e) = Offer::try_from(encoded_offer) {
1527 panic!("error parsing offer: {:?}", e);
1530 let mut tlv_stream = offer.as_tlv_stream();
1531 tlv_stream.amount = None;
1532 tlv_stream.currency = Some(b"USD");
1534 let mut encoded_offer = Vec::new();
1535 tlv_stream.write(&mut encoded_offer).unwrap();
1537 match Offer::try_from(encoded_offer) {
1538 Ok(_) => panic!("expected error"),
1539 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1542 let mut tlv_stream = offer.as_tlv_stream();
1543 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1544 tlv_stream.currency = None;
1546 let mut encoded_offer = Vec::new();
1547 tlv_stream.write(&mut encoded_offer).unwrap();
1549 match Offer::try_from(encoded_offer) {
1550 Ok(_) => panic!("expected error"),
1551 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1556 fn parses_offer_with_description() {
1557 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1558 if let Err(e) = offer.to_string().parse::<Offer>() {
1559 panic!("error parsing offer: {:?}", e);
1562 let mut tlv_stream = offer.as_tlv_stream();
1563 tlv_stream.description = None;
1565 let mut encoded_offer = Vec::new();
1566 tlv_stream.write(&mut encoded_offer).unwrap();
1568 match Offer::try_from(encoded_offer) {
1569 Ok(_) => panic!("expected error"),
1571 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1577 fn parses_offer_with_paths() {
1578 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1580 introduction_node_id: pubkey(40),
1581 blinding_point: pubkey(41),
1583 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1584 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1588 introduction_node_id: pubkey(40),
1589 blinding_point: pubkey(41),
1591 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1592 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1597 if let Err(e) = offer.to_string().parse::<Offer>() {
1598 panic!("error parsing offer: {:?}", e);
1601 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1602 builder.offer.paths = Some(vec![]);
1604 let offer = builder.build().unwrap();
1605 if let Err(e) = offer.to_string().parse::<Offer>() {
1606 panic!("error parsing offer: {:?}", e);
1611 fn parses_offer_with_quantity() {
1612 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1613 .supported_quantity(Quantity::One)
1616 if let Err(e) = offer.to_string().parse::<Offer>() {
1617 panic!("error parsing offer: {:?}", e);
1620 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1621 .supported_quantity(Quantity::Unbounded)
1624 if let Err(e) = offer.to_string().parse::<Offer>() {
1625 panic!("error parsing offer: {:?}", e);
1628 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1629 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1632 if let Err(e) = offer.to_string().parse::<Offer>() {
1633 panic!("error parsing offer: {:?}", e);
1636 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1637 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1640 if let Err(e) = offer.to_string().parse::<Offer>() {
1641 panic!("error parsing offer: {:?}", e);
1646 fn parses_offer_with_node_id() {
1647 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1648 if let Err(e) = offer.to_string().parse::<Offer>() {
1649 panic!("error parsing offer: {:?}", e);
1652 let mut tlv_stream = offer.as_tlv_stream();
1653 tlv_stream.node_id = None;
1655 let mut encoded_offer = Vec::new();
1656 tlv_stream.write(&mut encoded_offer).unwrap();
1658 match Offer::try_from(encoded_offer) {
1659 Ok(_) => panic!("expected error"),
1661 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1667 fn fails_parsing_offer_with_extra_tlv_records() {
1668 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1670 let mut encoded_offer = Vec::new();
1671 offer.write(&mut encoded_offer).unwrap();
1672 BigSize(80).write(&mut encoded_offer).unwrap();
1673 BigSize(32).write(&mut encoded_offer).unwrap();
1674 [42u8; 32].write(&mut encoded_offer).unwrap();
1676 match Offer::try_from(encoded_offer) {
1677 Ok(_) => panic!("expected error"),
1678 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1685 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1686 use crate::ln::msgs::DecodeError;
1689 fn parses_bech32_encoded_offers() {
1691 // Minimal bolt12 offer
1692 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1695 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1697 // for bitcoin (redundant)
1698 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1700 // for bitcoin or liquidv1
1701 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1704 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1707 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1710 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1713 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1716 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1719 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1721 // with unlimited (or unknown) quantity
1722 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1724 // with single quantity (weird but valid)
1725 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1728 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1730 // with blinded path via Bob (0x424242...), blinding 020202...
1731 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1733 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1734 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1736 // unknown odd field
1737 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1739 for encoded_offer in &offers {
1740 if let Err(e) = encoded_offer.parse::<Offer>() {
1741 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1747 fn fails_parsing_bech32_encoded_offers() {
1748 // Malformed: fields out of order
1750 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1751 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1754 // Malformed: unknown even TLV type 78
1756 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1757 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1762 "lno1".parse::<Offer>(),
1763 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1766 // Malformed: truncated at type
1768 "lno1pg".parse::<Offer>(),
1769 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1772 // Malformed: truncated in length
1774 "lno1pt7s".parse::<Offer>(),
1775 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1778 // Malformed: truncated after length
1780 "lno1pgpq".parse::<Offer>(),
1781 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1784 // Malformed: truncated in description
1786 "lno1pgpyz".parse::<Offer>(),
1787 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1790 // Malformed: invalid offer_chains length
1792 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1793 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1796 // Malformed: truncated currency UTF-8
1798 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1799 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1802 // Malformed: invalid currency UTF-8
1804 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1805 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1808 // Malformed: truncated description UTF-8
1810 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1811 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1814 // Malformed: invalid description UTF-8
1816 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1817 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1820 // Malformed: truncated offer_paths
1822 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1823 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1826 // Malformed: zero num_hops in blinded_path
1828 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1829 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1832 // Malformed: truncated onionmsg_hop in blinded_path
1834 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1835 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1838 // Malformed: bad first_node_id in blinded_path
1840 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1841 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1844 // Malformed: bad blinding in blinded_path
1846 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1847 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1850 // Malformed: bad blinded_node_id in onionmsg_hop
1852 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1853 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1856 // Malformed: truncated issuer UTF-8
1858 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1859 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1862 // Malformed: invalid issuer UTF-8
1864 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1865 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1868 // Malformed: invalid offer_node_id
1870 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1871 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1874 // Contains type >= 80
1876 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1877 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1880 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1881 // Contains unknown feature 22
1883 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1886 // Missing offer_description
1888 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1889 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1892 // Missing offer_node_id"
1894 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1895 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),