1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `offer` messages.
12 //! An [`Offer`] represents an "offer to be paid." It is typically constructed by a merchant and
13 //! published as a QR code to be scanned by a customer. The customer uses the offer to request an
14 //! invoice from the merchant to be paid.
19 //! extern crate bitcoin;
20 //! extern crate core;
21 //! extern crate lightning;
23 //! use core::convert::TryFrom;
24 //! use core::num::NonZeroU64;
25 //! use core::time::Duration;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
29 //! use lightning::offers::parse::Bolt12ParseError;
30 //! use lightning::util::ser::{Readable, Writeable};
32 //! # use lightning::blinded_path::BlindedPath;
33 //! # #[cfg(feature = "std")]
34 //! # use std::time::SystemTime;
36 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
39 //! # #[cfg(feature = "std")]
40 //! # fn build() -> Result<(), Bolt12ParseError> {
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
43 //! let pubkey = PublicKey::from(keys);
45 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
46 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
47 //! .amount_msats(20_000)
48 //! .supported_quantity(Quantity::Unbounded)
49 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //! .issuer("Foo Bar".to_string())
51 //! .path(create_blinded_path())
52 //! .path(create_another_blinded_path())
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
79 use bitcoin::blockdata::constants::ChainHash;
80 use bitcoin::network::constants::Network;
81 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
82 use core::hash::{Hash, Hasher};
83 use core::num::NonZeroU64;
85 use core::str::FromStr;
86 use core::time::Duration;
87 use crate::sign::EntropySource;
89 use crate::blinded_path::BlindedPath;
90 use crate::ln::channelmanager::PaymentId;
91 use crate::ln::features::OfferFeatures;
92 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
93 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
94 use crate::offers::merkle::{TaggedHash, TlvStream};
95 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
96 use crate::offers::signer::{Metadata, MetadataMaterial, self};
97 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
98 use crate::util::string::PrintableString;
100 #[cfg(not(c_bindings))]
102 crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder},
106 crate::offers::invoice_request::{InvoiceRequestWithDerivedPayerIdBuilder, InvoiceRequestWithExplicitPayerIdBuilder},
109 #[allow(unused_imports)]
110 use crate::prelude::*;
112 #[cfg(feature = "std")]
113 use std::time::SystemTime;
115 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
117 /// An identifier for an [`Offer`] built using [`DerivedMetadata`].
118 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
119 pub struct OfferId(pub [u8; 32]);
122 const ID_TAG: &'static str = "LDK Offer ID";
124 fn from_valid_offer_tlv_stream(bytes: &[u8]) -> Self {
125 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(Self::ID_TAG, bytes);
126 Self(tagged_hash.to_bytes())
129 fn from_valid_invreq_tlv_stream(bytes: &[u8]) -> Self {
130 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES);
131 let tagged_hash = TaggedHash::from_tlv_stream(Self::ID_TAG, tlv_stream);
132 Self(tagged_hash.to_bytes())
136 impl Writeable for OfferId {
137 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
142 impl Readable for OfferId {
143 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
144 Ok(OfferId(Readable::read(r)?))
148 /// Builds an [`Offer`] for the "offer to be paid" flow.
150 /// See [module-level documentation] for usage.
152 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
154 /// [module-level documentation]: self
155 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
156 offer: OfferContents,
157 metadata_strategy: core::marker::PhantomData<M>,
158 secp_ctx: Option<&'a Secp256k1<T>>,
161 /// Builds an [`Offer`] for the "offer to be paid" flow.
163 /// See [module-level documentation] for usage.
165 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
167 /// [module-level documentation]: self
169 pub struct OfferWithExplicitMetadataBuilder<'a> {
170 offer: OfferContents,
171 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
172 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
175 /// Builds an [`Offer`] for the "offer to be paid" flow.
177 /// See [module-level documentation] for usage.
179 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
181 /// [module-level documentation]: self
183 pub struct OfferWithDerivedMetadataBuilder<'a> {
184 offer: OfferContents,
185 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
186 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
189 /// Indicates how [`Offer::metadata`] may be set.
191 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
192 pub trait MetadataStrategy {}
194 /// [`Offer::metadata`] may be explicitly set or left empty.
196 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
197 pub struct ExplicitMetadata {}
199 /// [`Offer::metadata`] will be derived.
201 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
202 pub struct DerivedMetadata {}
204 impl MetadataStrategy for ExplicitMetadata {}
206 impl MetadataStrategy for DerivedMetadata {}
208 macro_rules! offer_explicit_metadata_builder_methods { (
209 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
211 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
212 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
213 /// while the offer is valid.
215 /// Use a different pubkey per offer to avoid correlating offers.
219 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
220 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
222 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
223 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
224 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
226 offer: OfferContents {
227 chains: None, metadata: None, amount: None, description,
228 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
229 supported_quantity: Quantity::One, signing_pubkey,
231 metadata_strategy: core::marker::PhantomData,
236 /// Sets the [`Offer::metadata`] to the given bytes.
238 /// Successive calls to this method will override the previous setting.
239 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
240 $self.offer.metadata = Some(Metadata::Bytes(metadata));
245 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
246 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
247 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
248 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
249 /// provided `node_id` is used for the signing pubkey.
251 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
252 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
255 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
256 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
257 pub fn deriving_signing_pubkey<ES: Deref>(
258 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
259 secp_ctx: &'a Secp256k1<$secp_context>
260 ) -> Self where ES::Target: EntropySource {
261 let nonce = Nonce::from_entropy_source(entropy_source);
262 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
263 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
265 offer: OfferContents {
266 chains: None, metadata: Some(metadata), amount: None, description,
267 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
268 supported_quantity: Quantity::One, signing_pubkey: node_id,
270 metadata_strategy: core::marker::PhantomData,
271 secp_ctx: Some(secp_ctx),
276 macro_rules! offer_builder_methods { (
277 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
279 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
280 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
282 /// See [`Offer::chains`] on how this relates to the payment currency.
284 /// Successive calls to this method will add another chain hash.
285 pub fn chain($self: $self_type, network: Network) -> $return_type {
286 $self.chain_hash(ChainHash::using_genesis_block(network))
289 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
290 /// [`Network::Bitcoin`] is assumed to be the only one supported.
292 /// See [`Offer::chains`] on how this relates to the payment currency.
294 /// Successive calls to this method will add another chain hash.
295 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
296 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
297 if !chains.contains(&chain) {
304 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
306 /// Successive calls to this method will override the previous setting.
307 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
308 $self.amount(Amount::Bitcoin { amount_msats })
311 /// Sets the [`Offer::amount`].
313 /// Successive calls to this method will override the previous setting.
314 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
315 $self.offer.amount = Some(amount);
319 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
320 /// already passed is valid and can be checked for using [`Offer::is_expired`].
322 /// Successive calls to this method will override the previous setting.
323 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
324 $self.offer.absolute_expiry = Some(absolute_expiry);
328 /// Sets the [`Offer::issuer`].
330 /// Successive calls to this method will override the previous setting.
331 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
332 $self.offer.issuer = Some(issuer);
336 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
337 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
339 /// Successive calls to this method will add another blinded path. Caller is responsible for not
340 /// adding duplicate paths.
341 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
342 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
346 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
347 /// [`Quantity::One`].
349 /// Successive calls to this method will override the previous setting.
350 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
351 $self.offer.supported_quantity = quantity;
355 /// Builds an [`Offer`] from the builder's settings.
356 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
357 match $self.offer.amount {
358 Some(Amount::Bitcoin { amount_msats }) => {
359 if amount_msats > MAX_VALUE_MSAT {
360 return Err(Bolt12SemanticError::InvalidAmount);
363 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
367 if let Some(chains) = &$self.offer.chains {
368 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
369 $self.offer.chains = None;
373 Ok($self.build_without_checks())
376 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
377 // Create the metadata for stateless verification of an InvoiceRequest.
378 if let Some(mut metadata) = $self.offer.metadata.take() {
379 if metadata.has_derivation_material() {
380 if $self.offer.paths.is_none() {
381 metadata = metadata.without_keys();
384 let mut tlv_stream = $self.offer.as_tlv_stream();
385 debug_assert_eq!(tlv_stream.metadata, None);
386 tlv_stream.metadata = None;
387 if metadata.derives_recipient_keys() {
388 tlv_stream.node_id = None;
391 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
392 metadata = derived_metadata;
393 if let Some(keys) = keys {
394 $self.offer.signing_pubkey = keys.public_key();
398 $self.offer.metadata = Some(metadata);
401 let mut bytes = Vec::new();
402 $self.offer.write(&mut bytes).unwrap();
404 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
408 #[cfg(not(c_bindings))]
409 contents: $self.offer,
411 contents: $self.offer.clone(),
418 macro_rules! offer_builder_test_methods { (
419 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
421 #[cfg_attr(c_bindings, allow(dead_code))]
422 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
423 $self.offer.features = features;
427 #[cfg_attr(c_bindings, allow(dead_code))]
428 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
429 $self.offer.chains = None;
433 #[cfg_attr(c_bindings, allow(dead_code))]
434 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
435 $self.offer.paths = None;
439 #[cfg_attr(c_bindings, allow(dead_code))]
440 pub(super) fn build_unchecked($self: $self_type) -> Offer {
441 $self.build_without_checks()
445 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
446 offer_builder_methods!(self, Self, Self, self, mut);
449 offer_builder_test_methods!(self, Self, Self, self, mut);
452 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
453 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
456 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
457 offer_derived_metadata_builder_methods!(T);
460 #[cfg(all(c_bindings, not(test)))]
461 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
462 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
463 offer_builder_methods!(self, &mut Self, (), ());
466 #[cfg(all(c_bindings, test))]
467 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
468 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
469 offer_builder_methods!(self, &mut Self, &mut Self, self);
470 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
473 #[cfg(all(c_bindings, not(test)))]
474 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
475 offer_derived_metadata_builder_methods!(secp256k1::All);
476 offer_builder_methods!(self, &mut Self, (), ());
479 #[cfg(all(c_bindings, test))]
480 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
481 offer_derived_metadata_builder_methods!(secp256k1::All);
482 offer_builder_methods!(self, &mut Self, &mut Self, self);
483 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
487 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
488 for OfferWithDerivedMetadataBuilder<'a> {
489 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
490 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
492 Self { offer, metadata_strategy, secp_ctx }
497 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
498 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
499 fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
500 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
502 Self { offer, metadata_strategy, secp_ctx }
506 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
508 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
509 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
510 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
512 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
515 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
517 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
518 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
519 #[derive(Clone, Debug)]
521 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
523 pub(super) bytes: Vec<u8>,
524 pub(super) contents: OfferContents,
528 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
529 /// [`Bolt12Invoice`].
531 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
532 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
533 #[derive(Clone, Debug)]
534 #[cfg_attr(test, derive(PartialEq))]
535 pub(super) struct OfferContents {
536 chains: Option<Vec<ChainHash>>,
537 metadata: Option<Metadata>,
538 amount: Option<Amount>,
540 features: OfferFeatures,
541 absolute_expiry: Option<Duration>,
542 issuer: Option<String>,
543 paths: Option<Vec<BlindedPath>>,
544 supported_quantity: Quantity,
545 signing_pubkey: PublicKey,
548 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
549 // TODO: Return a slice once ChainHash has constants.
550 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
551 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
552 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
553 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
554 /// for the selected chain.
555 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
559 // TODO: Link to corresponding method in `InvoiceRequest`.
560 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
561 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
562 pub fn metadata(&$self) -> Option<&Vec<u8>> {
566 /// The minimum amount required for a successful payment of a single item.
567 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
571 /// A complete description of the purpose of the payment. Intended to be displayed to the user
572 /// but with the caveat that it has not been verified in any way.
573 pub fn description(&$self) -> $crate::util::string::PrintableString {
574 $contents.description()
577 /// Features pertaining to the offer.
578 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
579 &$contents.features()
582 /// Duration since the Unix epoch when an invoice should no longer be requested.
584 /// If `None`, the offer does not expire.
585 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
586 $contents.absolute_expiry()
589 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
590 /// displayed to the user but with the caveat that it has not been verified in any way.
591 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
595 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
596 /// recipient privacy by obfuscating its node id.
597 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
601 /// The quantity of items supported.
602 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
603 $contents.supported_quantity()
606 /// The public key used by the recipient to sign invoices.
607 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
608 $contents.signing_pubkey()
613 offer_accessors!(self, self.contents);
615 /// Returns the id of the offer.
616 pub fn id(&self) -> OfferId {
620 pub(super) fn implied_chain(&self) -> ChainHash {
621 self.contents.implied_chain()
624 /// Returns whether the given chain is supported by the offer.
625 pub fn supports_chain(&self, chain: ChainHash) -> bool {
626 self.contents.supports_chain(chain)
629 /// Whether the offer has expired.
630 #[cfg(feature = "std")]
631 pub fn is_expired(&self) -> bool {
632 self.contents.is_expired()
635 /// Whether the offer has expired given the duration since the Unix epoch.
636 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
637 self.contents.is_expired_no_std(duration_since_epoch)
640 /// Returns whether the given quantity is valid for the offer.
641 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
642 self.contents.is_valid_quantity(quantity)
645 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
647 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
648 pub fn expects_quantity(&self) -> bool {
649 self.contents.expects_quantity()
653 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
654 /// Similar to [`Offer::request_invoice`] except it:
655 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
657 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
658 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
659 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
660 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
661 /// be used when sending the payment for the requested invoice.
663 /// Useful to protect the sender's privacy.
665 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
666 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
667 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
668 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
669 pub fn request_invoice_deriving_payer_id<
671 #[cfg(not(c_bindings))]
672 T: secp256k1::Signing
674 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
675 #[cfg(not(c_bindings))]
676 secp_ctx: &'b Secp256k1<T>,
678 secp_ctx: &'b Secp256k1<secp256k1::All>,
679 payment_id: PaymentId
680 ) -> Result<$builder, Bolt12SemanticError>
682 ES::Target: EntropySource,
684 if $self.offer_features().requires_unknown_bits() {
685 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
688 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
692 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
693 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
694 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
696 /// Useful for recurring payments using the same `payer_id` with different invoices.
698 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
699 pub fn request_invoice_deriving_metadata<ES: Deref>(
700 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
701 payment_id: PaymentId
702 ) -> Result<$builder, Bolt12SemanticError>
704 ES::Target: EntropySource,
706 if $self.offer_features().requires_unknown_bits() {
707 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
710 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
713 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
714 /// which will be reflected in the `Bolt12Invoice` response.
716 /// The `metadata` is useful for including information about the derivation of `payer_id` such
717 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
718 /// hashing in the signature calculation.
720 /// This should not leak any information such as by using a simple BIP-32 derivation path.
721 /// Otherwise, payments may be correlated.
723 /// Errors if the offer contains unknown required features.
725 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
726 pub fn request_invoice(
727 &$self, metadata: Vec<u8>, payer_id: PublicKey
728 ) -> Result<$builder, Bolt12SemanticError> {
729 if $self.offer_features().requires_unknown_bits() {
730 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
733 Ok(<$builder>::new($self, metadata, payer_id))
737 #[cfg(not(c_bindings))]
739 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
740 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
745 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
746 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
751 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
752 self.contents.as_tlv_stream()
756 impl AsRef<[u8]> for Offer {
757 fn as_ref(&self) -> &[u8] {
762 impl PartialEq for Offer {
763 fn eq(&self, other: &Self) -> bool {
764 self.bytes.eq(&other.bytes)
770 impl Hash for Offer {
771 fn hash<H: Hasher>(&self, state: &mut H) {
772 self.bytes.hash(state);
777 pub fn chains(&self) -> Vec<ChainHash> {
778 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
781 pub fn implied_chain(&self) -> ChainHash {
782 ChainHash::using_genesis_block(Network::Bitcoin)
785 pub fn supports_chain(&self, chain: ChainHash) -> bool {
786 self.chains().contains(&chain)
789 pub fn metadata(&self) -> Option<&Vec<u8>> {
790 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
793 pub fn amount(&self) -> Option<&Amount> {
797 pub fn description(&self) -> PrintableString {
798 PrintableString(&self.description)
801 pub fn features(&self) -> &OfferFeatures {
805 pub fn absolute_expiry(&self) -> Option<Duration> {
809 #[cfg(feature = "std")]
810 pub(super) fn is_expired(&self) -> bool {
811 SystemTime::UNIX_EPOCH
813 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
817 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
819 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
823 pub fn issuer(&self) -> Option<PrintableString> {
824 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
827 pub fn paths(&self) -> &[BlindedPath] {
828 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
831 pub(super) fn check_amount_msats_for_quantity(
832 &self, amount_msats: Option<u64>, quantity: Option<u64>
833 ) -> Result<(), Bolt12SemanticError> {
834 let offer_amount_msats = match self.amount {
836 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
837 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
840 if !self.expects_quantity() || quantity.is_some() {
841 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
842 .ok_or(Bolt12SemanticError::InvalidAmount)?;
843 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
845 if amount_msats < expected_amount_msats {
846 return Err(Bolt12SemanticError::InsufficientAmount);
849 if amount_msats > MAX_VALUE_MSAT {
850 return Err(Bolt12SemanticError::InvalidAmount);
857 pub fn supported_quantity(&self) -> Quantity {
858 self.supported_quantity
861 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
862 let expects_quantity = self.expects_quantity();
864 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
865 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
866 Some(quantity) if !self.is_valid_quantity(quantity) => {
867 Err(Bolt12SemanticError::InvalidQuantity)
873 fn is_valid_quantity(&self, quantity: u64) -> bool {
874 match self.supported_quantity {
875 Quantity::Bounded(n) => quantity <= n.get(),
876 Quantity::Unbounded => quantity > 0,
877 Quantity::One => quantity == 1,
881 fn expects_quantity(&self) -> bool {
882 match self.supported_quantity {
883 Quantity::Bounded(_) => true,
884 Quantity::Unbounded => true,
885 Quantity::One => false,
889 pub(super) fn signing_pubkey(&self) -> PublicKey {
893 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
894 pub(super) fn verify<T: secp256k1::Signing>(
895 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
896 ) -> Result<(OfferId, Option<KeyPair>), ()> {
897 match self.metadata() {
899 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
900 match record.r#type {
901 OFFER_METADATA_TYPE => false,
902 OFFER_NODE_ID_TYPE => {
903 !self.metadata.as_ref().unwrap().derives_recipient_keys()
908 let keys = signer::verify_recipient_metadata(
909 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
912 let offer_id = OfferId::from_valid_invreq_tlv_stream(bytes);
920 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
921 let (currency, amount) = match &self.amount {
922 None => (None, None),
923 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
924 Some(Amount::Currency { iso4217_code, amount }) => (
925 Some(iso4217_code), Some(*amount)
930 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
934 chains: self.chains.as_ref(),
935 metadata: self.metadata(),
938 description: Some(&self.description),
940 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
941 paths: self.paths.as_ref(),
942 issuer: self.issuer.as_ref(),
943 quantity_max: self.supported_quantity.to_tlv_record(),
944 node_id: Some(&self.signing_pubkey),
949 impl Writeable for Offer {
950 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
951 WithoutLength(&self.bytes).write(writer)
955 impl Writeable for OfferContents {
956 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
957 self.as_tlv_stream().write(writer)
961 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
962 /// another currency.
963 #[derive(Clone, Debug, PartialEq)]
965 /// An amount of bitcoin.
967 /// The amount in millisatoshi.
970 /// An amount of currency specified using ISO 4712.
972 /// The currency that the amount is denominated in.
973 iso4217_code: CurrencyCode,
974 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
979 /// An ISO 4712 three-letter currency code (e.g., USD).
980 pub type CurrencyCode = [u8; 3];
982 /// Quantity of items supported by an [`Offer`].
983 #[derive(Clone, Copy, Debug, PartialEq)]
985 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
986 /// but is limited (e.g., because of per customer or inventory limits).
988 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
991 /// One or more items. Use when more than one item can be requested without any limit.
993 /// Only one item. Use when only a single item can be requested.
998 fn to_tlv_record(&self) -> Option<u64> {
1000 Quantity::Bounded(n) => Some(n.get()),
1001 Quantity::Unbounded => Some(0),
1002 Quantity::One => None,
1007 /// Valid type range for offer TLV records.
1008 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
1010 /// TLV record type for [`Offer::metadata`].
1011 const OFFER_METADATA_TYPE: u64 = 4;
1013 /// TLV record type for [`Offer::signing_pubkey`].
1014 const OFFER_NODE_ID_TYPE: u64 = 22;
1016 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
1017 (2, chains: (Vec<ChainHash>, WithoutLength)),
1018 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1019 (6, currency: CurrencyCode),
1020 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
1021 (10, description: (String, WithoutLength)),
1022 (12, features: (OfferFeatures, WithoutLength)),
1023 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
1024 (16, paths: (Vec<BlindedPath>, WithoutLength)),
1025 (18, issuer: (String, WithoutLength)),
1026 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
1027 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
1030 impl Bech32Encode for Offer {
1031 const BECH32_HRP: &'static str = "lno";
1034 impl FromStr for Offer {
1035 type Err = Bolt12ParseError;
1037 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
1038 Self::from_bech32_str(s)
1042 impl TryFrom<Vec<u8>> for Offer {
1043 type Error = Bolt12ParseError;
1045 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1046 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1047 let ParsedMessage { bytes, tlv_stream } = offer;
1048 let contents = OfferContents::try_from(tlv_stream)?;
1049 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
1051 Ok(Offer { bytes, contents, id })
1055 impl TryFrom<OfferTlvStream> for OfferContents {
1056 type Error = Bolt12SemanticError;
1058 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1059 let OfferTlvStream {
1060 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1061 issuer, quantity_max, node_id,
1064 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1066 let amount = match (currency, amount) {
1067 (None, None) => None,
1068 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1069 return Err(Bolt12SemanticError::InvalidAmount);
1071 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1072 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1073 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1076 let description = match description {
1077 None => return Err(Bolt12SemanticError::MissingDescription),
1078 Some(description) => description,
1081 let features = features.unwrap_or_else(OfferFeatures::empty);
1083 let absolute_expiry = absolute_expiry
1084 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1086 let supported_quantity = match quantity_max {
1087 None => Quantity::One,
1088 Some(0) => Quantity::Unbounded,
1089 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1092 let signing_pubkey = match node_id {
1093 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1094 Some(node_id) => node_id,
1098 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1099 supported_quantity, signing_pubkey,
1104 impl core::fmt::Display for Offer {
1105 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1106 self.fmt_bech32_str(f)
1112 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1113 #[cfg(not(c_bindings))]
1115 super::OfferBuilder,
1119 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1122 use bitcoin::blockdata::constants::ChainHash;
1123 use bitcoin::network::constants::Network;
1124 use bitcoin::secp256k1::Secp256k1;
1125 use core::num::NonZeroU64;
1126 use core::time::Duration;
1127 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1128 use crate::sign::KeyMaterial;
1129 use crate::ln::features::OfferFeatures;
1130 use crate::ln::inbound_payment::ExpandedKey;
1131 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1132 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1133 use crate::offers::test_utils::*;
1134 use crate::util::ser::{BigSize, Writeable};
1135 use crate::util::string::PrintableString;
1138 fn builds_offer_with_defaults() {
1139 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1141 let mut buffer = Vec::new();
1142 offer.write(&mut buffer).unwrap();
1144 assert_eq!(offer.bytes, buffer.as_slice());
1145 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1146 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1147 assert_eq!(offer.metadata(), None);
1148 assert_eq!(offer.amount(), None);
1149 assert_eq!(offer.description(), PrintableString("foo"));
1150 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1151 assert_eq!(offer.absolute_expiry(), None);
1152 #[cfg(feature = "std")]
1153 assert!(!offer.is_expired());
1154 assert_eq!(offer.paths(), &[]);
1155 assert_eq!(offer.issuer(), None);
1156 assert_eq!(offer.supported_quantity(), Quantity::One);
1157 assert_eq!(offer.signing_pubkey(), pubkey(42));
1160 offer.as_tlv_stream(),
1166 description: Some(&String::from("foo")),
1168 absolute_expiry: None,
1172 node_id: Some(&pubkey(42)),
1176 if let Err(e) = Offer::try_from(buffer) {
1177 panic!("error parsing offer: {:?}", e);
1182 fn builds_offer_with_chains() {
1183 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1184 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1186 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1187 .chain(Network::Bitcoin)
1190 assert!(offer.supports_chain(mainnet));
1191 assert_eq!(offer.chains(), vec![mainnet]);
1192 assert_eq!(offer.as_tlv_stream().chains, None);
1194 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1195 .chain(Network::Testnet)
1198 assert!(offer.supports_chain(testnet));
1199 assert_eq!(offer.chains(), vec![testnet]);
1200 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1202 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1203 .chain(Network::Testnet)
1204 .chain(Network::Testnet)
1207 assert!(offer.supports_chain(testnet));
1208 assert_eq!(offer.chains(), vec![testnet]);
1209 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1211 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1212 .chain(Network::Bitcoin)
1213 .chain(Network::Testnet)
1216 assert!(offer.supports_chain(mainnet));
1217 assert!(offer.supports_chain(testnet));
1218 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1219 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1223 fn builds_offer_with_metadata() {
1224 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1225 .metadata(vec![42; 32]).unwrap()
1228 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1229 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1231 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1232 .metadata(vec![42; 32]).unwrap()
1233 .metadata(vec![43; 32]).unwrap()
1236 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1237 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1241 fn builds_offer_with_metadata_derived() {
1242 let desc = "foo".to_string();
1243 let node_id = recipient_pubkey();
1244 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1245 let entropy = FixedEntropy {};
1246 let secp_ctx = Secp256k1::new();
1249 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1250 let offer = OfferBuilder
1251 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1254 assert_eq!(offer.signing_pubkey(), node_id);
1256 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1258 .sign(payer_sign).unwrap();
1259 match invoice_request.verify(&expanded_key, &secp_ctx) {
1260 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1261 Err(_) => panic!("unexpected error"),
1264 // Fails verification with altered offer field
1265 let mut tlv_stream = offer.as_tlv_stream();
1266 tlv_stream.amount = Some(100);
1268 let mut encoded_offer = Vec::new();
1269 tlv_stream.write(&mut encoded_offer).unwrap();
1271 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1272 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1274 .sign(payer_sign).unwrap();
1275 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1277 // Fails verification with altered metadata
1278 let mut tlv_stream = offer.as_tlv_stream();
1279 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1280 tlv_stream.metadata = Some(&metadata);
1282 let mut encoded_offer = Vec::new();
1283 tlv_stream.write(&mut encoded_offer).unwrap();
1285 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1286 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1288 .sign(payer_sign).unwrap();
1289 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1293 fn builds_offer_with_derived_signing_pubkey() {
1294 let desc = "foo".to_string();
1295 let node_id = recipient_pubkey();
1296 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1297 let entropy = FixedEntropy {};
1298 let secp_ctx = Secp256k1::new();
1300 let blinded_path = BlindedPath {
1301 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1302 blinding_point: pubkey(41),
1304 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1305 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1310 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1311 let offer = OfferBuilder
1312 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1316 assert_ne!(offer.signing_pubkey(), node_id);
1318 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1320 .sign(payer_sign).unwrap();
1321 match invoice_request.verify(&expanded_key, &secp_ctx) {
1322 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1323 Err(_) => panic!("unexpected error"),
1326 // Fails verification with altered offer field
1327 let mut tlv_stream = offer.as_tlv_stream();
1328 tlv_stream.amount = Some(100);
1330 let mut encoded_offer = Vec::new();
1331 tlv_stream.write(&mut encoded_offer).unwrap();
1333 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1334 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1336 .sign(payer_sign).unwrap();
1337 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1339 // Fails verification with altered signing pubkey
1340 let mut tlv_stream = offer.as_tlv_stream();
1341 let signing_pubkey = pubkey(1);
1342 tlv_stream.node_id = Some(&signing_pubkey);
1344 let mut encoded_offer = Vec::new();
1345 tlv_stream.write(&mut encoded_offer).unwrap();
1347 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1348 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1350 .sign(payer_sign).unwrap();
1351 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1355 fn builds_offer_with_amount() {
1356 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1357 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1359 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1363 let tlv_stream = offer.as_tlv_stream();
1364 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1365 assert_eq!(tlv_stream.amount, Some(1000));
1366 assert_eq!(tlv_stream.currency, None);
1368 #[cfg(not(c_bindings))]
1369 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1370 .amount(currency_amount.clone());
1372 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1374 builder.amount(currency_amount.clone());
1375 let tlv_stream = builder.offer.as_tlv_stream();
1376 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1377 assert_eq!(tlv_stream.amount, Some(10));
1378 assert_eq!(tlv_stream.currency, Some(b"USD"));
1379 match builder.build() {
1380 Ok(_) => panic!("expected error"),
1381 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1384 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1385 .amount(currency_amount.clone())
1386 .amount(bitcoin_amount.clone())
1389 let tlv_stream = offer.as_tlv_stream();
1390 assert_eq!(tlv_stream.amount, Some(1000));
1391 assert_eq!(tlv_stream.currency, None);
1393 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1394 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1395 Ok(_) => panic!("expected error"),
1396 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1401 fn builds_offer_with_features() {
1402 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1403 .features_unchecked(OfferFeatures::unknown())
1406 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1407 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1409 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1410 .features_unchecked(OfferFeatures::unknown())
1411 .features_unchecked(OfferFeatures::empty())
1414 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1415 assert_eq!(offer.as_tlv_stream().features, None);
1419 fn builds_offer_with_absolute_expiry() {
1420 let future_expiry = Duration::from_secs(u64::max_value());
1421 let past_expiry = Duration::from_secs(0);
1422 let now = future_expiry - Duration::from_secs(1_000);
1424 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1425 .absolute_expiry(future_expiry)
1428 #[cfg(feature = "std")]
1429 assert!(!offer.is_expired());
1430 assert!(!offer.is_expired_no_std(now));
1431 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1432 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1434 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1435 .absolute_expiry(future_expiry)
1436 .absolute_expiry(past_expiry)
1439 #[cfg(feature = "std")]
1440 assert!(offer.is_expired());
1441 assert!(offer.is_expired_no_std(now));
1442 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1443 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1447 fn builds_offer_with_paths() {
1450 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1451 blinding_point: pubkey(41),
1453 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1454 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1458 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1459 blinding_point: pubkey(41),
1461 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1462 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1467 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1468 .path(paths[0].clone())
1469 .path(paths[1].clone())
1472 let tlv_stream = offer.as_tlv_stream();
1473 assert_eq!(offer.paths(), paths.as_slice());
1474 assert_eq!(offer.signing_pubkey(), pubkey(42));
1475 assert_ne!(pubkey(42), pubkey(44));
1476 assert_eq!(tlv_stream.paths, Some(&paths));
1477 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1481 fn builds_offer_with_issuer() {
1482 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1483 .issuer("bar".into())
1486 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1487 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1489 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1490 .issuer("bar".into())
1491 .issuer("baz".into())
1494 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1495 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1499 fn builds_offer_with_supported_quantity() {
1500 let one = NonZeroU64::new(1).unwrap();
1501 let ten = NonZeroU64::new(10).unwrap();
1503 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1504 .supported_quantity(Quantity::One)
1507 let tlv_stream = offer.as_tlv_stream();
1508 assert_eq!(offer.supported_quantity(), Quantity::One);
1509 assert_eq!(tlv_stream.quantity_max, None);
1511 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1512 .supported_quantity(Quantity::Unbounded)
1515 let tlv_stream = offer.as_tlv_stream();
1516 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1517 assert_eq!(tlv_stream.quantity_max, Some(0));
1519 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1520 .supported_quantity(Quantity::Bounded(ten))
1523 let tlv_stream = offer.as_tlv_stream();
1524 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1525 assert_eq!(tlv_stream.quantity_max, Some(10));
1527 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1528 .supported_quantity(Quantity::Bounded(one))
1531 let tlv_stream = offer.as_tlv_stream();
1532 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1533 assert_eq!(tlv_stream.quantity_max, Some(1));
1535 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1536 .supported_quantity(Quantity::Bounded(ten))
1537 .supported_quantity(Quantity::One)
1540 let tlv_stream = offer.as_tlv_stream();
1541 assert_eq!(offer.supported_quantity(), Quantity::One);
1542 assert_eq!(tlv_stream.quantity_max, None);
1546 fn fails_requesting_invoice_with_unknown_required_features() {
1547 match OfferBuilder::new("foo".into(), pubkey(42))
1548 .features_unchecked(OfferFeatures::unknown())
1550 .request_invoice(vec![1; 32], pubkey(43))
1552 Ok(_) => panic!("expected error"),
1553 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1558 fn parses_offer_with_chains() {
1559 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1560 .chain(Network::Bitcoin)
1561 .chain(Network::Testnet)
1564 if let Err(e) = offer.to_string().parse::<Offer>() {
1565 panic!("error parsing offer: {:?}", e);
1570 fn parses_offer_with_amount() {
1571 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1572 .amount(Amount::Bitcoin { amount_msats: 1000 })
1575 if let Err(e) = offer.to_string().parse::<Offer>() {
1576 panic!("error parsing offer: {:?}", e);
1579 let mut tlv_stream = offer.as_tlv_stream();
1580 tlv_stream.amount = Some(1000);
1581 tlv_stream.currency = Some(b"USD");
1583 let mut encoded_offer = Vec::new();
1584 tlv_stream.write(&mut encoded_offer).unwrap();
1586 if let Err(e) = Offer::try_from(encoded_offer) {
1587 panic!("error parsing offer: {:?}", e);
1590 let mut tlv_stream = offer.as_tlv_stream();
1591 tlv_stream.amount = None;
1592 tlv_stream.currency = Some(b"USD");
1594 let mut encoded_offer = Vec::new();
1595 tlv_stream.write(&mut encoded_offer).unwrap();
1597 match Offer::try_from(encoded_offer) {
1598 Ok(_) => panic!("expected error"),
1599 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1602 let mut tlv_stream = offer.as_tlv_stream();
1603 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1604 tlv_stream.currency = None;
1606 let mut encoded_offer = Vec::new();
1607 tlv_stream.write(&mut encoded_offer).unwrap();
1609 match Offer::try_from(encoded_offer) {
1610 Ok(_) => panic!("expected error"),
1611 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1616 fn parses_offer_with_description() {
1617 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1618 if let Err(e) = offer.to_string().parse::<Offer>() {
1619 panic!("error parsing offer: {:?}", e);
1622 let mut tlv_stream = offer.as_tlv_stream();
1623 tlv_stream.description = None;
1625 let mut encoded_offer = Vec::new();
1626 tlv_stream.write(&mut encoded_offer).unwrap();
1628 match Offer::try_from(encoded_offer) {
1629 Ok(_) => panic!("expected error"),
1631 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1637 fn parses_offer_with_paths() {
1638 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1640 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1641 blinding_point: pubkey(41),
1643 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1644 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1648 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1649 blinding_point: pubkey(41),
1651 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1652 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1657 if let Err(e) = offer.to_string().parse::<Offer>() {
1658 panic!("error parsing offer: {:?}", e);
1661 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1662 builder.offer.paths = Some(vec![]);
1664 let offer = builder.build().unwrap();
1665 if let Err(e) = offer.to_string().parse::<Offer>() {
1666 panic!("error parsing offer: {:?}", e);
1671 fn parses_offer_with_quantity() {
1672 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1673 .supported_quantity(Quantity::One)
1676 if let Err(e) = offer.to_string().parse::<Offer>() {
1677 panic!("error parsing offer: {:?}", e);
1680 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1681 .supported_quantity(Quantity::Unbounded)
1684 if let Err(e) = offer.to_string().parse::<Offer>() {
1685 panic!("error parsing offer: {:?}", e);
1688 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1689 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1692 if let Err(e) = offer.to_string().parse::<Offer>() {
1693 panic!("error parsing offer: {:?}", e);
1696 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1697 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1700 if let Err(e) = offer.to_string().parse::<Offer>() {
1701 panic!("error parsing offer: {:?}", e);
1706 fn parses_offer_with_node_id() {
1707 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1708 if let Err(e) = offer.to_string().parse::<Offer>() {
1709 panic!("error parsing offer: {:?}", e);
1712 let mut tlv_stream = offer.as_tlv_stream();
1713 tlv_stream.node_id = None;
1715 let mut encoded_offer = Vec::new();
1716 tlv_stream.write(&mut encoded_offer).unwrap();
1718 match Offer::try_from(encoded_offer) {
1719 Ok(_) => panic!("expected error"),
1721 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1727 fn fails_parsing_offer_with_extra_tlv_records() {
1728 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1730 let mut encoded_offer = Vec::new();
1731 offer.write(&mut encoded_offer).unwrap();
1732 BigSize(80).write(&mut encoded_offer).unwrap();
1733 BigSize(32).write(&mut encoded_offer).unwrap();
1734 [42u8; 32].write(&mut encoded_offer).unwrap();
1736 match Offer::try_from(encoded_offer) {
1737 Ok(_) => panic!("expected error"),
1738 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1745 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1746 use crate::ln::msgs::DecodeError;
1749 fn parses_bech32_encoded_offers() {
1751 // Minimal bolt12 offer
1752 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1755 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1757 // for bitcoin (redundant)
1758 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1760 // for bitcoin or liquidv1
1761 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1764 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1767 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1770 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1773 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1776 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1779 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1781 // with unlimited (or unknown) quantity
1782 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1784 // with single quantity (weird but valid)
1785 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1788 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1790 // with blinded path via Bob (0x424242...), blinding 020202...
1791 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1793 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1794 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1796 // unknown odd field
1797 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1799 for encoded_offer in &offers {
1800 if let Err(e) = encoded_offer.parse::<Offer>() {
1801 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1807 fn fails_parsing_bech32_encoded_offers() {
1808 // Malformed: fields out of order
1810 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1811 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1814 // Malformed: unknown even TLV type 78
1816 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1817 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1822 "lno1".parse::<Offer>(),
1823 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1826 // Malformed: truncated at type
1828 "lno1pg".parse::<Offer>(),
1829 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1832 // Malformed: truncated in length
1834 "lno1pt7s".parse::<Offer>(),
1835 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1838 // Malformed: truncated after length
1840 "lno1pgpq".parse::<Offer>(),
1841 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1844 // Malformed: truncated in description
1846 "lno1pgpyz".parse::<Offer>(),
1847 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1850 // Malformed: invalid offer_chains length
1852 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1853 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1856 // Malformed: truncated currency UTF-8
1858 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1859 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1862 // Malformed: invalid currency UTF-8
1864 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1865 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1868 // Malformed: truncated description UTF-8
1870 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1871 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1874 // Malformed: invalid description UTF-8
1876 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1877 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1880 // Malformed: truncated offer_paths
1882 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1883 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1886 // Malformed: zero num_hops in blinded_path
1888 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1889 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1892 // Malformed: truncated onionmsg_hop in blinded_path
1894 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1895 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1898 // Malformed: bad first_node_id in blinded_path
1900 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1901 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1904 // Malformed: bad blinding in blinded_path
1906 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1907 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1910 // Malformed: bad blinded_node_id in onionmsg_hop
1912 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1913 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1916 // Malformed: truncated issuer UTF-8
1918 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1919 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1922 // Malformed: invalid issuer UTF-8
1924 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1925 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1928 // Malformed: invalid offer_node_id
1930 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1931 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1934 // Contains type >= 80
1936 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1937 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1940 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1941 // Contains unknown feature 22
1943 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1946 // Missing offer_description
1948 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1949 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1952 // Missing offer_node_id"
1954 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1955 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),