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::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::MAX_VALUE_MSAT;
94 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
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 use crate::prelude::*;
103 #[cfg(feature = "std")]
104 use std::time::SystemTime;
106 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
108 /// Builds an [`Offer`] for the "offer to be paid" flow.
110 /// See [module-level documentation] for usage.
112 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
114 /// [module-level documentation]: self
115 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
116 offer: OfferContents,
117 metadata_strategy: core::marker::PhantomData<M>,
118 secp_ctx: Option<&'a Secp256k1<T>>,
121 /// Builds an [`Offer`] for the "offer to be paid" flow.
123 /// See [module-level documentation] for usage.
125 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
127 /// [module-level documentation]: self
129 pub struct OfferWithExplicitMetadataBuilder<'a> {
130 offer: OfferContents,
131 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
132 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
135 /// Builds an [`Offer`] for the "offer to be paid" flow.
137 /// See [module-level documentation] for usage.
139 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
141 /// [module-level documentation]: self
143 pub struct OfferWithDerivedMetadataBuilder<'a> {
144 offer: OfferContents,
145 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
146 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
149 /// Indicates how [`Offer::metadata`] may be set.
151 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
152 pub trait MetadataStrategy {}
154 /// [`Offer::metadata`] may be explicitly set or left empty.
156 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
157 pub struct ExplicitMetadata {}
159 /// [`Offer::metadata`] will be derived.
161 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
162 pub struct DerivedMetadata {}
164 impl MetadataStrategy for ExplicitMetadata {}
166 impl MetadataStrategy for DerivedMetadata {}
168 macro_rules! offer_explicit_metadata_builder_methods { (
169 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
171 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
172 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
173 /// while the offer is valid.
175 /// Use a different pubkey per offer to avoid correlating offers.
179 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
180 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
182 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
183 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
184 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
186 offer: OfferContents {
187 chains: None, metadata: None, amount: None, description,
188 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
189 supported_quantity: Quantity::One, signing_pubkey,
191 metadata_strategy: core::marker::PhantomData,
196 /// Sets the [`Offer::metadata`] to the given bytes.
198 /// Successive calls to this method will override the previous setting.
199 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
200 $self.offer.metadata = Some(Metadata::Bytes(metadata));
205 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
206 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
207 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
208 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
209 /// provided `node_id` is used for the signing pubkey.
211 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
212 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
215 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
216 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
217 pub fn deriving_signing_pubkey<ES: Deref>(
218 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
219 secp_ctx: &'a Secp256k1<$secp_context>
220 ) -> Self where ES::Target: EntropySource {
221 let nonce = Nonce::from_entropy_source(entropy_source);
222 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
223 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
225 offer: OfferContents {
226 chains: None, metadata: Some(metadata), amount: None, description,
227 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
228 supported_quantity: Quantity::One, signing_pubkey: node_id,
230 metadata_strategy: core::marker::PhantomData,
231 secp_ctx: Some(secp_ctx),
236 macro_rules! offer_builder_methods { (
237 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
239 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
240 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
242 /// See [`Offer::chains`] on how this relates to the payment currency.
244 /// Successive calls to this method will add another chain hash.
245 pub fn chain($self: $self_type, network: Network) -> $return_type {
246 $self.chain_hash(ChainHash::using_genesis_block(network))
249 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
250 /// [`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(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
256 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
257 if !chains.contains(&chain) {
264 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
266 /// Successive calls to this method will override the previous setting.
267 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
268 $self.amount(Amount::Bitcoin { amount_msats })
271 /// Sets the [`Offer::amount`].
273 /// Successive calls to this method will override the previous setting.
274 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
275 $self.offer.amount = Some(amount);
279 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
280 /// already passed is valid and can be checked for using [`Offer::is_expired`].
282 /// Successive calls to this method will override the previous setting.
283 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
284 $self.offer.absolute_expiry = Some(absolute_expiry);
288 /// Sets the [`Offer::issuer`].
290 /// Successive calls to this method will override the previous setting.
291 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
292 $self.offer.issuer = Some(issuer);
296 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
297 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
299 /// Successive calls to this method will add another blinded path. Caller is responsible for not
300 /// adding duplicate paths.
301 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
302 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
306 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
307 /// [`Quantity::One`].
309 /// Successive calls to this method will override the previous setting.
310 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
311 $self.offer.supported_quantity = quantity;
315 /// Builds an [`Offer`] from the builder's settings.
316 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
317 match $self.offer.amount {
318 Some(Amount::Bitcoin { amount_msats }) => {
319 if amount_msats > MAX_VALUE_MSAT {
320 return Err(Bolt12SemanticError::InvalidAmount);
323 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
327 if let Some(chains) = &$self.offer.chains {
328 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
329 $self.offer.chains = None;
333 Ok($self.build_without_checks())
336 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
337 // Create the metadata for stateless verification of an InvoiceRequest.
338 if let Some(mut metadata) = $self.offer.metadata.take() {
339 if metadata.has_derivation_material() {
340 if $self.offer.paths.is_none() {
341 metadata = metadata.without_keys();
344 let mut tlv_stream = $self.offer.as_tlv_stream();
345 debug_assert_eq!(tlv_stream.metadata, None);
346 tlv_stream.metadata = None;
347 if metadata.derives_recipient_keys() {
348 tlv_stream.node_id = None;
351 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
352 metadata = derived_metadata;
353 if let Some(keys) = keys {
354 $self.offer.signing_pubkey = keys.public_key();
358 $self.offer.metadata = Some(metadata);
361 let mut bytes = Vec::new();
362 $self.offer.write(&mut bytes).unwrap();
366 #[cfg(not(c_bindings))]
367 contents: $self.offer,
369 contents: $self.offer.clone()
375 macro_rules! offer_builder_test_methods { (
376 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
378 #[cfg_attr(c_bindings, allow(dead_code))]
379 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
380 $self.offer.features = features;
384 #[cfg_attr(c_bindings, allow(dead_code))]
385 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
386 $self.offer.paths = None;
390 #[cfg_attr(c_bindings, allow(dead_code))]
391 pub(super) fn build_unchecked($self: $self_type) -> Offer {
392 $self.build_without_checks()
396 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
397 offer_builder_methods!(self, Self, Self, self, mut);
400 offer_builder_test_methods!(self, Self, Self, self, mut);
403 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
404 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
407 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
408 offer_derived_metadata_builder_methods!(T);
411 #[cfg(all(c_bindings, not(test)))]
412 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
413 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
414 offer_builder_methods!(self, &mut Self, (), ());
417 #[cfg(all(c_bindings, test))]
418 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
419 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
420 offer_builder_methods!(self, &mut Self, &mut Self, self);
421 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
424 #[cfg(all(c_bindings, not(test)))]
425 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
426 offer_derived_metadata_builder_methods!(secp256k1::All);
427 offer_builder_methods!(self, &mut Self, (), ());
430 #[cfg(all(c_bindings, test))]
431 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
432 offer_derived_metadata_builder_methods!(secp256k1::All);
433 offer_builder_methods!(self, &mut Self, &mut Self, self);
434 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
438 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
439 for OfferWithDerivedMetadataBuilder<'a> {
440 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
441 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
443 Self { offer, metadata_strategy, secp_ctx }
447 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
449 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
450 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
451 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
453 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
456 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
458 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
459 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
460 #[derive(Clone, Debug)]
461 #[cfg_attr(test, derive(PartialEq))]
463 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
465 pub(super) bytes: Vec<u8>,
466 pub(super) contents: OfferContents,
469 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
470 /// [`Bolt12Invoice`].
472 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
473 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
474 #[derive(Clone, Debug)]
475 #[cfg_attr(test, derive(PartialEq))]
476 pub(super) struct OfferContents {
477 chains: Option<Vec<ChainHash>>,
478 metadata: Option<Metadata>,
479 amount: Option<Amount>,
481 features: OfferFeatures,
482 absolute_expiry: Option<Duration>,
483 issuer: Option<String>,
484 paths: Option<Vec<BlindedPath>>,
485 supported_quantity: Quantity,
486 signing_pubkey: PublicKey,
489 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
490 // TODO: Return a slice once ChainHash has constants.
491 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
492 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
493 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
494 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
495 /// for the selected chain.
496 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
500 // TODO: Link to corresponding method in `InvoiceRequest`.
501 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
502 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
503 pub fn metadata(&$self) -> Option<&Vec<u8>> {
507 /// The minimum amount required for a successful payment of a single item.
508 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
512 /// A complete description of the purpose of the payment. Intended to be displayed to the user
513 /// but with the caveat that it has not been verified in any way.
514 pub fn description(&$self) -> $crate::util::string::PrintableString {
515 $contents.description()
518 /// Features pertaining to the offer.
519 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
520 &$contents.features()
523 /// Duration since the Unix epoch when an invoice should no longer be requested.
525 /// If `None`, the offer does not expire.
526 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
527 $contents.absolute_expiry()
530 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
531 /// displayed to the user but with the caveat that it has not been verified in any way.
532 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
536 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
537 /// recipient privacy by obfuscating its node id.
538 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
542 /// The quantity of items supported.
543 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
544 $contents.supported_quantity()
547 /// The public key used by the recipient to sign invoices.
548 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
549 $contents.signing_pubkey()
554 offer_accessors!(self, self.contents);
556 pub(super) fn implied_chain(&self) -> ChainHash {
557 self.contents.implied_chain()
560 /// Returns whether the given chain is supported by the offer.
561 pub fn supports_chain(&self, chain: ChainHash) -> bool {
562 self.contents.supports_chain(chain)
565 /// Whether the offer has expired.
566 #[cfg(feature = "std")]
567 pub fn is_expired(&self) -> bool {
568 self.contents.is_expired()
571 /// Whether the offer has expired given the duration since the Unix epoch.
572 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
573 self.contents.is_expired_no_std(duration_since_epoch)
576 /// Returns whether the given quantity is valid for the offer.
577 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
578 self.contents.is_valid_quantity(quantity)
581 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
583 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
584 pub fn expects_quantity(&self) -> bool {
585 self.contents.expects_quantity()
589 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
590 /// Similar to [`Offer::request_invoice`] except it:
591 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
593 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
594 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
595 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
596 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
597 /// be used when sending the payment for the requested invoice.
599 /// Useful to protect the sender's privacy.
601 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
603 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
604 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
605 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
606 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
607 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
608 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>,
609 payment_id: PaymentId
610 ) -> Result<$builder, Bolt12SemanticError>
612 ES::Target: EntropySource,
614 if $self.offer_features().requires_unknown_bits() {
615 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
618 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
622 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
623 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
624 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
626 /// Useful for recurring payments using the same `payer_id` with different invoices.
628 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
630 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
631 pub fn request_invoice_deriving_metadata<ES: Deref>(
632 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
633 payment_id: PaymentId
634 ) -> Result<$builder, Bolt12SemanticError>
636 ES::Target: EntropySource,
638 if $self.offer_features().requires_unknown_bits() {
639 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
642 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
645 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
646 /// which will be reflected in the `Bolt12Invoice` response.
648 /// The `metadata` is useful for including information about the derivation of `payer_id` such
649 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
650 /// hashing in the signature calculation.
652 /// This should not leak any information such as by using a simple BIP-32 derivation path.
653 /// Otherwise, payments may be correlated.
655 /// Errors if the offer contains unknown required features.
657 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
659 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
660 pub fn request_invoice(
661 &$self, metadata: Vec<u8>, payer_id: PublicKey
662 ) -> Result<$builder, Bolt12SemanticError> {
663 if $self.offer_features().requires_unknown_bits() {
664 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
667 Ok(<$builder>::new($self, metadata, payer_id))
672 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
673 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
678 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
679 self.contents.as_tlv_stream()
683 impl AsRef<[u8]> for Offer {
684 fn as_ref(&self) -> &[u8] {
690 pub fn chains(&self) -> Vec<ChainHash> {
691 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
694 pub fn implied_chain(&self) -> ChainHash {
695 ChainHash::using_genesis_block(Network::Bitcoin)
698 pub fn supports_chain(&self, chain: ChainHash) -> bool {
699 self.chains().contains(&chain)
702 pub fn metadata(&self) -> Option<&Vec<u8>> {
703 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
706 pub fn amount(&self) -> Option<&Amount> {
710 pub fn description(&self) -> PrintableString {
711 PrintableString(&self.description)
714 pub fn features(&self) -> &OfferFeatures {
718 pub fn absolute_expiry(&self) -> Option<Duration> {
722 #[cfg(feature = "std")]
723 pub(super) fn is_expired(&self) -> bool {
724 SystemTime::UNIX_EPOCH
726 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
730 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
732 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
736 pub fn issuer(&self) -> Option<PrintableString> {
737 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
740 pub fn paths(&self) -> &[BlindedPath] {
741 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
744 pub(super) fn check_amount_msats_for_quantity(
745 &self, amount_msats: Option<u64>, quantity: Option<u64>
746 ) -> Result<(), Bolt12SemanticError> {
747 let offer_amount_msats = match self.amount {
749 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
750 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
753 if !self.expects_quantity() || quantity.is_some() {
754 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
755 .ok_or(Bolt12SemanticError::InvalidAmount)?;
756 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
758 if amount_msats < expected_amount_msats {
759 return Err(Bolt12SemanticError::InsufficientAmount);
762 if amount_msats > MAX_VALUE_MSAT {
763 return Err(Bolt12SemanticError::InvalidAmount);
770 pub fn supported_quantity(&self) -> Quantity {
771 self.supported_quantity
774 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
775 let expects_quantity = self.expects_quantity();
777 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
778 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
779 Some(quantity) if !self.is_valid_quantity(quantity) => {
780 Err(Bolt12SemanticError::InvalidQuantity)
786 fn is_valid_quantity(&self, quantity: u64) -> bool {
787 match self.supported_quantity {
788 Quantity::Bounded(n) => quantity <= n.get(),
789 Quantity::Unbounded => quantity > 0,
790 Quantity::One => quantity == 1,
794 fn expects_quantity(&self) -> bool {
795 match self.supported_quantity {
796 Quantity::Bounded(_) => true,
797 Quantity::Unbounded => true,
798 Quantity::One => false,
802 pub(super) fn signing_pubkey(&self) -> PublicKey {
806 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
807 pub(super) fn verify<T: secp256k1::Signing>(
808 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
809 ) -> Result<Option<KeyPair>, ()> {
810 match self.metadata() {
812 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
813 match record.r#type {
814 OFFER_METADATA_TYPE => false,
815 OFFER_NODE_ID_TYPE => {
816 !self.metadata.as_ref().unwrap().derives_recipient_keys()
821 signer::verify_recipient_metadata(
822 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
829 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
830 let (currency, amount) = match &self.amount {
831 None => (None, None),
832 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
833 Some(Amount::Currency { iso4217_code, amount }) => (
834 Some(iso4217_code), Some(*amount)
839 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
843 chains: self.chains.as_ref(),
844 metadata: self.metadata(),
847 description: Some(&self.description),
849 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
850 paths: self.paths.as_ref(),
851 issuer: self.issuer.as_ref(),
852 quantity_max: self.supported_quantity.to_tlv_record(),
853 node_id: Some(&self.signing_pubkey),
858 impl Writeable for Offer {
859 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
860 WithoutLength(&self.bytes).write(writer)
864 impl Writeable for OfferContents {
865 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
866 self.as_tlv_stream().write(writer)
870 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
871 /// another currency.
872 #[derive(Clone, Debug, PartialEq)]
874 /// An amount of bitcoin.
876 /// The amount in millisatoshi.
879 /// An amount of currency specified using ISO 4712.
881 /// The currency that the amount is denominated in.
882 iso4217_code: CurrencyCode,
883 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
888 /// An ISO 4712 three-letter currency code (e.g., USD).
889 pub type CurrencyCode = [u8; 3];
891 /// Quantity of items supported by an [`Offer`].
892 #[derive(Clone, Copy, Debug, PartialEq)]
894 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
895 /// but is limited (e.g., because of per customer or inventory limits).
897 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
900 /// One or more items. Use when more than one item can be requested without any limit.
902 /// Only one item. Use when only a single item can be requested.
907 fn to_tlv_record(&self) -> Option<u64> {
909 Quantity::Bounded(n) => Some(n.get()),
910 Quantity::Unbounded => Some(0),
911 Quantity::One => None,
916 /// Valid type range for offer TLV records.
917 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
919 /// TLV record type for [`Offer::metadata`].
920 const OFFER_METADATA_TYPE: u64 = 4;
922 /// TLV record type for [`Offer::signing_pubkey`].
923 const OFFER_NODE_ID_TYPE: u64 = 22;
925 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
926 (2, chains: (Vec<ChainHash>, WithoutLength)),
927 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
928 (6, currency: CurrencyCode),
929 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
930 (10, description: (String, WithoutLength)),
931 (12, features: (OfferFeatures, WithoutLength)),
932 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
933 (16, paths: (Vec<BlindedPath>, WithoutLength)),
934 (18, issuer: (String, WithoutLength)),
935 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
936 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
939 impl Bech32Encode for Offer {
940 const BECH32_HRP: &'static str = "lno";
943 impl FromStr for Offer {
944 type Err = Bolt12ParseError;
946 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
947 Self::from_bech32_str(s)
951 impl TryFrom<Vec<u8>> for Offer {
952 type Error = Bolt12ParseError;
954 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
955 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
956 let ParsedMessage { bytes, tlv_stream } = offer;
957 let contents = OfferContents::try_from(tlv_stream)?;
958 Ok(Offer { bytes, contents })
962 impl TryFrom<OfferTlvStream> for OfferContents {
963 type Error = Bolt12SemanticError;
965 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
967 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
968 issuer, quantity_max, node_id,
971 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
973 let amount = match (currency, amount) {
974 (None, None) => None,
975 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
976 return Err(Bolt12SemanticError::InvalidAmount);
978 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
979 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
980 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
983 let description = match description {
984 None => return Err(Bolt12SemanticError::MissingDescription),
985 Some(description) => description,
988 let features = features.unwrap_or_else(OfferFeatures::empty);
990 let absolute_expiry = absolute_expiry
991 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
993 let supported_quantity = match quantity_max {
994 None => Quantity::One,
995 Some(0) => Quantity::Unbounded,
996 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
999 let signing_pubkey = match node_id {
1000 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1001 Some(node_id) => node_id,
1005 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1006 supported_quantity, signing_pubkey,
1011 impl core::fmt::Display for Offer {
1012 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1013 self.fmt_bech32_str(f)
1019 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1020 #[cfg(not(c_bindings))]
1022 super::OfferBuilder,
1026 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1029 use bitcoin::blockdata::constants::ChainHash;
1030 use bitcoin::network::constants::Network;
1031 use bitcoin::secp256k1::Secp256k1;
1032 use core::convert::TryFrom;
1033 use core::num::NonZeroU64;
1034 use core::time::Duration;
1035 use crate::blinded_path::{BlindedHop, BlindedPath};
1036 use crate::sign::KeyMaterial;
1037 use crate::ln::features::OfferFeatures;
1038 use crate::ln::inbound_payment::ExpandedKey;
1039 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1040 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1041 use crate::offers::test_utils::*;
1042 use crate::util::ser::{BigSize, Writeable};
1043 use crate::util::string::PrintableString;
1046 fn builds_offer_with_defaults() {
1047 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1049 let mut buffer = Vec::new();
1050 offer.write(&mut buffer).unwrap();
1052 assert_eq!(offer.bytes, buffer.as_slice());
1053 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1054 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1055 assert_eq!(offer.metadata(), None);
1056 assert_eq!(offer.amount(), None);
1057 assert_eq!(offer.description(), PrintableString("foo"));
1058 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1059 assert_eq!(offer.absolute_expiry(), None);
1060 #[cfg(feature = "std")]
1061 assert!(!offer.is_expired());
1062 assert_eq!(offer.paths(), &[]);
1063 assert_eq!(offer.issuer(), None);
1064 assert_eq!(offer.supported_quantity(), Quantity::One);
1065 assert_eq!(offer.signing_pubkey(), pubkey(42));
1068 offer.as_tlv_stream(),
1074 description: Some(&String::from("foo")),
1076 absolute_expiry: None,
1080 node_id: Some(&pubkey(42)),
1084 if let Err(e) = Offer::try_from(buffer) {
1085 panic!("error parsing offer: {:?}", e);
1090 fn builds_offer_with_chains() {
1091 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1092 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1094 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1095 .chain(Network::Bitcoin)
1098 assert!(offer.supports_chain(mainnet));
1099 assert_eq!(offer.chains(), vec![mainnet]);
1100 assert_eq!(offer.as_tlv_stream().chains, None);
1102 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1103 .chain(Network::Testnet)
1106 assert!(offer.supports_chain(testnet));
1107 assert_eq!(offer.chains(), vec![testnet]);
1108 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1110 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1111 .chain(Network::Testnet)
1112 .chain(Network::Testnet)
1115 assert!(offer.supports_chain(testnet));
1116 assert_eq!(offer.chains(), vec![testnet]);
1117 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1119 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1120 .chain(Network::Bitcoin)
1121 .chain(Network::Testnet)
1124 assert!(offer.supports_chain(mainnet));
1125 assert!(offer.supports_chain(testnet));
1126 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1127 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1131 fn builds_offer_with_metadata() {
1132 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1133 .metadata(vec![42; 32]).unwrap()
1136 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1137 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1139 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1140 .metadata(vec![42; 32]).unwrap()
1141 .metadata(vec![43; 32]).unwrap()
1144 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1145 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1149 fn builds_offer_with_metadata_derived() {
1150 let desc = "foo".to_string();
1151 let node_id = recipient_pubkey();
1152 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1153 let entropy = FixedEntropy {};
1154 let secp_ctx = Secp256k1::new();
1157 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1158 let offer = OfferBuilder
1159 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1162 assert_eq!(offer.signing_pubkey(), node_id);
1164 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1166 .sign(payer_sign).unwrap();
1167 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1169 // Fails verification with altered offer field
1170 let mut tlv_stream = offer.as_tlv_stream();
1171 tlv_stream.amount = Some(100);
1173 let mut encoded_offer = Vec::new();
1174 tlv_stream.write(&mut encoded_offer).unwrap();
1176 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1177 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1179 .sign(payer_sign).unwrap();
1180 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1182 // Fails verification with altered metadata
1183 let mut tlv_stream = offer.as_tlv_stream();
1184 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1185 tlv_stream.metadata = Some(&metadata);
1187 let mut encoded_offer = Vec::new();
1188 tlv_stream.write(&mut encoded_offer).unwrap();
1190 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1191 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1193 .sign(payer_sign).unwrap();
1194 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1198 fn builds_offer_with_derived_signing_pubkey() {
1199 let desc = "foo".to_string();
1200 let node_id = recipient_pubkey();
1201 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1202 let entropy = FixedEntropy {};
1203 let secp_ctx = Secp256k1::new();
1205 let blinded_path = BlindedPath {
1206 introduction_node_id: pubkey(40),
1207 blinding_point: pubkey(41),
1209 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1210 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1215 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1216 let offer = OfferBuilder
1217 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1221 assert_ne!(offer.signing_pubkey(), node_id);
1223 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225 .sign(payer_sign).unwrap();
1226 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1228 // Fails verification with altered offer field
1229 let mut tlv_stream = offer.as_tlv_stream();
1230 tlv_stream.amount = Some(100);
1232 let mut encoded_offer = Vec::new();
1233 tlv_stream.write(&mut encoded_offer).unwrap();
1235 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1236 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1238 .sign(payer_sign).unwrap();
1239 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1241 // Fails verification with altered signing pubkey
1242 let mut tlv_stream = offer.as_tlv_stream();
1243 let signing_pubkey = pubkey(1);
1244 tlv_stream.node_id = Some(&signing_pubkey);
1246 let mut encoded_offer = Vec::new();
1247 tlv_stream.write(&mut encoded_offer).unwrap();
1249 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1250 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1252 .sign(payer_sign).unwrap();
1253 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1257 fn builds_offer_with_amount() {
1258 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1259 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1261 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1265 let tlv_stream = offer.as_tlv_stream();
1266 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1267 assert_eq!(tlv_stream.amount, Some(1000));
1268 assert_eq!(tlv_stream.currency, None);
1270 #[cfg(not(c_bindings))]
1271 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1272 .amount(currency_amount.clone());
1274 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1276 builder.amount(currency_amount.clone());
1277 let tlv_stream = builder.offer.as_tlv_stream();
1278 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1279 assert_eq!(tlv_stream.amount, Some(10));
1280 assert_eq!(tlv_stream.currency, Some(b"USD"));
1281 match builder.build() {
1282 Ok(_) => panic!("expected error"),
1283 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1286 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1287 .amount(currency_amount.clone())
1288 .amount(bitcoin_amount.clone())
1291 let tlv_stream = offer.as_tlv_stream();
1292 assert_eq!(tlv_stream.amount, Some(1000));
1293 assert_eq!(tlv_stream.currency, None);
1295 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1296 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1297 Ok(_) => panic!("expected error"),
1298 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1303 fn builds_offer_with_features() {
1304 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1305 .features_unchecked(OfferFeatures::unknown())
1308 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1309 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1311 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1312 .features_unchecked(OfferFeatures::unknown())
1313 .features_unchecked(OfferFeatures::empty())
1316 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1317 assert_eq!(offer.as_tlv_stream().features, None);
1321 fn builds_offer_with_absolute_expiry() {
1322 let future_expiry = Duration::from_secs(u64::max_value());
1323 let past_expiry = Duration::from_secs(0);
1324 let now = future_expiry - Duration::from_secs(1_000);
1326 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1327 .absolute_expiry(future_expiry)
1330 #[cfg(feature = "std")]
1331 assert!(!offer.is_expired());
1332 assert!(!offer.is_expired_no_std(now));
1333 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1334 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1336 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1337 .absolute_expiry(future_expiry)
1338 .absolute_expiry(past_expiry)
1341 #[cfg(feature = "std")]
1342 assert!(offer.is_expired());
1343 assert!(offer.is_expired_no_std(now));
1344 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1345 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1349 fn builds_offer_with_paths() {
1352 introduction_node_id: pubkey(40),
1353 blinding_point: pubkey(41),
1355 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1356 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1360 introduction_node_id: pubkey(40),
1361 blinding_point: pubkey(41),
1363 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1364 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1369 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1370 .path(paths[0].clone())
1371 .path(paths[1].clone())
1374 let tlv_stream = offer.as_tlv_stream();
1375 assert_eq!(offer.paths(), paths.as_slice());
1376 assert_eq!(offer.signing_pubkey(), pubkey(42));
1377 assert_ne!(pubkey(42), pubkey(44));
1378 assert_eq!(tlv_stream.paths, Some(&paths));
1379 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1383 fn builds_offer_with_issuer() {
1384 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1385 .issuer("bar".into())
1388 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1389 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1391 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1392 .issuer("bar".into())
1393 .issuer("baz".into())
1396 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1397 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1401 fn builds_offer_with_supported_quantity() {
1402 let one = NonZeroU64::new(1).unwrap();
1403 let ten = NonZeroU64::new(10).unwrap();
1405 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1406 .supported_quantity(Quantity::One)
1409 let tlv_stream = offer.as_tlv_stream();
1410 assert_eq!(offer.supported_quantity(), Quantity::One);
1411 assert_eq!(tlv_stream.quantity_max, None);
1413 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1414 .supported_quantity(Quantity::Unbounded)
1417 let tlv_stream = offer.as_tlv_stream();
1418 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1419 assert_eq!(tlv_stream.quantity_max, Some(0));
1421 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1422 .supported_quantity(Quantity::Bounded(ten))
1425 let tlv_stream = offer.as_tlv_stream();
1426 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1427 assert_eq!(tlv_stream.quantity_max, Some(10));
1429 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1430 .supported_quantity(Quantity::Bounded(one))
1433 let tlv_stream = offer.as_tlv_stream();
1434 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1435 assert_eq!(tlv_stream.quantity_max, Some(1));
1437 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1438 .supported_quantity(Quantity::Bounded(ten))
1439 .supported_quantity(Quantity::One)
1442 let tlv_stream = offer.as_tlv_stream();
1443 assert_eq!(offer.supported_quantity(), Quantity::One);
1444 assert_eq!(tlv_stream.quantity_max, None);
1448 fn fails_requesting_invoice_with_unknown_required_features() {
1449 match OfferBuilder::new("foo".into(), pubkey(42))
1450 .features_unchecked(OfferFeatures::unknown())
1452 .request_invoice(vec![1; 32], pubkey(43))
1454 Ok(_) => panic!("expected error"),
1455 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1460 fn parses_offer_with_chains() {
1461 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1462 .chain(Network::Bitcoin)
1463 .chain(Network::Testnet)
1466 if let Err(e) = offer.to_string().parse::<Offer>() {
1467 panic!("error parsing offer: {:?}", e);
1472 fn parses_offer_with_amount() {
1473 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1474 .amount(Amount::Bitcoin { amount_msats: 1000 })
1477 if let Err(e) = offer.to_string().parse::<Offer>() {
1478 panic!("error parsing offer: {:?}", e);
1481 let mut tlv_stream = offer.as_tlv_stream();
1482 tlv_stream.amount = Some(1000);
1483 tlv_stream.currency = Some(b"USD");
1485 let mut encoded_offer = Vec::new();
1486 tlv_stream.write(&mut encoded_offer).unwrap();
1488 if let Err(e) = Offer::try_from(encoded_offer) {
1489 panic!("error parsing offer: {:?}", e);
1492 let mut tlv_stream = offer.as_tlv_stream();
1493 tlv_stream.amount = None;
1494 tlv_stream.currency = Some(b"USD");
1496 let mut encoded_offer = Vec::new();
1497 tlv_stream.write(&mut encoded_offer).unwrap();
1499 match Offer::try_from(encoded_offer) {
1500 Ok(_) => panic!("expected error"),
1501 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1504 let mut tlv_stream = offer.as_tlv_stream();
1505 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1506 tlv_stream.currency = None;
1508 let mut encoded_offer = Vec::new();
1509 tlv_stream.write(&mut encoded_offer).unwrap();
1511 match Offer::try_from(encoded_offer) {
1512 Ok(_) => panic!("expected error"),
1513 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1518 fn parses_offer_with_description() {
1519 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1520 if let Err(e) = offer.to_string().parse::<Offer>() {
1521 panic!("error parsing offer: {:?}", e);
1524 let mut tlv_stream = offer.as_tlv_stream();
1525 tlv_stream.description = None;
1527 let mut encoded_offer = Vec::new();
1528 tlv_stream.write(&mut encoded_offer).unwrap();
1530 match Offer::try_from(encoded_offer) {
1531 Ok(_) => panic!("expected error"),
1533 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1539 fn parses_offer_with_paths() {
1540 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1542 introduction_node_id: pubkey(40),
1543 blinding_point: pubkey(41),
1545 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1546 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1550 introduction_node_id: pubkey(40),
1551 blinding_point: pubkey(41),
1553 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1554 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1559 if let Err(e) = offer.to_string().parse::<Offer>() {
1560 panic!("error parsing offer: {:?}", e);
1563 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1564 builder.offer.paths = Some(vec![]);
1566 let offer = builder.build().unwrap();
1567 if let Err(e) = offer.to_string().parse::<Offer>() {
1568 panic!("error parsing offer: {:?}", e);
1573 fn parses_offer_with_quantity() {
1574 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1575 .supported_quantity(Quantity::One)
1578 if let Err(e) = offer.to_string().parse::<Offer>() {
1579 panic!("error parsing offer: {:?}", e);
1582 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1583 .supported_quantity(Quantity::Unbounded)
1586 if let Err(e) = offer.to_string().parse::<Offer>() {
1587 panic!("error parsing offer: {:?}", e);
1590 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1591 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1594 if let Err(e) = offer.to_string().parse::<Offer>() {
1595 panic!("error parsing offer: {:?}", e);
1598 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1599 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1602 if let Err(e) = offer.to_string().parse::<Offer>() {
1603 panic!("error parsing offer: {:?}", e);
1608 fn parses_offer_with_node_id() {
1609 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1610 if let Err(e) = offer.to_string().parse::<Offer>() {
1611 panic!("error parsing offer: {:?}", e);
1614 let mut tlv_stream = offer.as_tlv_stream();
1615 tlv_stream.node_id = None;
1617 let mut encoded_offer = Vec::new();
1618 tlv_stream.write(&mut encoded_offer).unwrap();
1620 match Offer::try_from(encoded_offer) {
1621 Ok(_) => panic!("expected error"),
1623 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1629 fn fails_parsing_offer_with_extra_tlv_records() {
1630 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1632 let mut encoded_offer = Vec::new();
1633 offer.write(&mut encoded_offer).unwrap();
1634 BigSize(80).write(&mut encoded_offer).unwrap();
1635 BigSize(32).write(&mut encoded_offer).unwrap();
1636 [42u8; 32].write(&mut encoded_offer).unwrap();
1638 match Offer::try_from(encoded_offer) {
1639 Ok(_) => panic!("expected error"),
1640 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1647 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1648 use crate::ln::msgs::DecodeError;
1651 fn parses_bech32_encoded_offers() {
1653 // Minimal bolt12 offer
1654 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1657 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1659 // for bitcoin (redundant)
1660 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1662 // for bitcoin or liquidv1
1663 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1666 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1669 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1672 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1675 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1678 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1681 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1683 // with unlimited (or unknown) quantity
1684 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1686 // with single quantity (weird but valid)
1687 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1690 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1692 // with blinded path via Bob (0x424242...), blinding 020202...
1693 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1695 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1696 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1698 // unknown odd field
1699 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1701 for encoded_offer in &offers {
1702 if let Err(e) = encoded_offer.parse::<Offer>() {
1703 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1709 fn fails_parsing_bech32_encoded_offers() {
1710 // Malformed: fields out of order
1712 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1713 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1716 // Malformed: unknown even TLV type 78
1718 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1719 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1724 "lno1".parse::<Offer>(),
1725 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1728 // Malformed: truncated at type
1730 "lno1pg".parse::<Offer>(),
1731 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1734 // Malformed: truncated in length
1736 "lno1pt7s".parse::<Offer>(),
1737 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1740 // Malformed: truncated after length
1742 "lno1pgpq".parse::<Offer>(),
1743 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1746 // Malformed: truncated in description
1748 "lno1pgpyz".parse::<Offer>(),
1749 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1752 // Malformed: invalid offer_chains length
1754 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1755 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1758 // Malformed: truncated currency UTF-8
1760 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1761 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1764 // Malformed: invalid currency UTF-8
1766 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1767 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1770 // Malformed: truncated description UTF-8
1772 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1773 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1776 // Malformed: invalid description UTF-8
1778 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1779 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1782 // Malformed: truncated offer_paths
1784 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1785 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1788 // Malformed: zero num_hops in blinded_path
1790 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1791 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1794 // Malformed: truncated onionmsg_hop in blinded_path
1796 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1797 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1800 // Malformed: bad first_node_id in blinded_path
1802 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1803 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1806 // Malformed: bad blinding in blinded_path
1808 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1809 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1812 // Malformed: bad blinded_node_id in onionmsg_hop
1814 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1815 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1818 // Malformed: truncated issuer UTF-8
1820 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1821 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1824 // Malformed: invalid issuer UTF-8
1826 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1827 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1830 // Malformed: invalid offer_node_id
1832 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1833 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1836 // Contains type >= 80
1838 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1839 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1842 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1843 // Contains unknown feature 22
1845 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1848 // Missing offer_description
1850 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1851 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1854 // Missing offer_node_id"
1856 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1857 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),