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::MAX_VALUE_MSAT;
94 use crate::offers::merkle::TlvStream;
95 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
96 use crate::offers::signer::{Metadata, MetadataMaterial, self};
97 use crate::util::ser::{HighZeroBytesDroppedBigSize, 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 /// Builds an [`Offer`] for the "offer to be paid" flow.
119 /// See [module-level documentation] for usage.
121 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
123 /// [module-level documentation]: self
124 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
125 offer: OfferContents,
126 metadata_strategy: core::marker::PhantomData<M>,
127 secp_ctx: Option<&'a Secp256k1<T>>,
130 /// Builds an [`Offer`] for the "offer to be paid" flow.
132 /// See [module-level documentation] for usage.
134 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
136 /// [module-level documentation]: self
138 pub struct OfferWithExplicitMetadataBuilder<'a> {
139 offer: OfferContents,
140 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
141 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
144 /// Builds an [`Offer`] for the "offer to be paid" flow.
146 /// See [module-level documentation] for usage.
148 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
150 /// [module-level documentation]: self
152 pub struct OfferWithDerivedMetadataBuilder<'a> {
153 offer: OfferContents,
154 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
155 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
158 /// Indicates how [`Offer::metadata`] may be set.
160 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
161 pub trait MetadataStrategy {}
163 /// [`Offer::metadata`] may be explicitly set or left empty.
165 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
166 pub struct ExplicitMetadata {}
168 /// [`Offer::metadata`] will be derived.
170 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
171 pub struct DerivedMetadata {}
173 impl MetadataStrategy for ExplicitMetadata {}
175 impl MetadataStrategy for DerivedMetadata {}
177 macro_rules! offer_explicit_metadata_builder_methods { (
178 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
180 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
181 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
182 /// while the offer is valid.
184 /// Use a different pubkey per offer to avoid correlating offers.
188 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
189 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
191 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
192 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
193 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
195 offer: OfferContents {
196 chains: None, metadata: None, amount: None, description,
197 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
198 supported_quantity: Quantity::One, signing_pubkey,
200 metadata_strategy: core::marker::PhantomData,
205 /// Sets the [`Offer::metadata`] to the given bytes.
207 /// Successive calls to this method will override the previous setting.
208 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
209 $self.offer.metadata = Some(Metadata::Bytes(metadata));
214 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
215 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
216 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
217 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
218 /// provided `node_id` is used for the signing pubkey.
220 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
221 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
224 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
225 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
226 pub fn deriving_signing_pubkey<ES: Deref>(
227 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
228 secp_ctx: &'a Secp256k1<$secp_context>
229 ) -> Self where ES::Target: EntropySource {
230 let nonce = Nonce::from_entropy_source(entropy_source);
231 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
232 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
234 offer: OfferContents {
235 chains: None, metadata: Some(metadata), amount: None, description,
236 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
237 supported_quantity: Quantity::One, signing_pubkey: node_id,
239 metadata_strategy: core::marker::PhantomData,
240 secp_ctx: Some(secp_ctx),
245 macro_rules! offer_builder_methods { (
246 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
248 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
249 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
251 /// See [`Offer::chains`] on how this relates to the payment currency.
253 /// Successive calls to this method will add another chain hash.
254 pub fn chain($self: $self_type, network: Network) -> $return_type {
255 $self.chain_hash(ChainHash::using_genesis_block(network))
258 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
259 /// [`Network::Bitcoin`] is assumed to be the only one supported.
261 /// See [`Offer::chains`] on how this relates to the payment currency.
263 /// Successive calls to this method will add another chain hash.
264 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
265 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
266 if !chains.contains(&chain) {
273 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
275 /// Successive calls to this method will override the previous setting.
276 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
277 $self.amount(Amount::Bitcoin { amount_msats })
280 /// Sets the [`Offer::amount`].
282 /// Successive calls to this method will override the previous setting.
283 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
284 $self.offer.amount = Some(amount);
288 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
289 /// already passed is valid and can be checked for using [`Offer::is_expired`].
291 /// Successive calls to this method will override the previous setting.
292 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
293 $self.offer.absolute_expiry = Some(absolute_expiry);
297 /// Sets the [`Offer::issuer`].
299 /// Successive calls to this method will override the previous setting.
300 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
301 $self.offer.issuer = Some(issuer);
305 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
306 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
308 /// Successive calls to this method will add another blinded path. Caller is responsible for not
309 /// adding duplicate paths.
310 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
311 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
315 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
316 /// [`Quantity::One`].
318 /// Successive calls to this method will override the previous setting.
319 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
320 $self.offer.supported_quantity = quantity;
324 /// Builds an [`Offer`] from the builder's settings.
325 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
326 match $self.offer.amount {
327 Some(Amount::Bitcoin { amount_msats }) => {
328 if amount_msats > MAX_VALUE_MSAT {
329 return Err(Bolt12SemanticError::InvalidAmount);
332 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
336 if let Some(chains) = &$self.offer.chains {
337 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
338 $self.offer.chains = None;
342 Ok($self.build_without_checks())
345 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
346 // Create the metadata for stateless verification of an InvoiceRequest.
347 if let Some(mut metadata) = $self.offer.metadata.take() {
348 if metadata.has_derivation_material() {
349 if $self.offer.paths.is_none() {
350 metadata = metadata.without_keys();
353 let mut tlv_stream = $self.offer.as_tlv_stream();
354 debug_assert_eq!(tlv_stream.metadata, None);
355 tlv_stream.metadata = None;
356 if metadata.derives_recipient_keys() {
357 tlv_stream.node_id = None;
360 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
361 metadata = derived_metadata;
362 if let Some(keys) = keys {
363 $self.offer.signing_pubkey = keys.public_key();
367 $self.offer.metadata = Some(metadata);
370 let mut bytes = Vec::new();
371 $self.offer.write(&mut bytes).unwrap();
375 #[cfg(not(c_bindings))]
376 contents: $self.offer,
378 contents: $self.offer.clone()
384 macro_rules! offer_builder_test_methods { (
385 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
387 #[cfg_attr(c_bindings, allow(dead_code))]
388 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
389 $self.offer.features = features;
393 #[cfg_attr(c_bindings, allow(dead_code))]
394 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
395 $self.offer.chains = None;
399 #[cfg_attr(c_bindings, allow(dead_code))]
400 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
401 $self.offer.paths = None;
405 #[cfg_attr(c_bindings, allow(dead_code))]
406 pub(super) fn build_unchecked($self: $self_type) -> Offer {
407 $self.build_without_checks()
411 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
412 offer_builder_methods!(self, Self, Self, self, mut);
415 offer_builder_test_methods!(self, Self, Self, self, mut);
418 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
419 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
422 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
423 offer_derived_metadata_builder_methods!(T);
426 #[cfg(all(c_bindings, not(test)))]
427 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
428 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
429 offer_builder_methods!(self, &mut Self, (), ());
432 #[cfg(all(c_bindings, test))]
433 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
434 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
435 offer_builder_methods!(self, &mut Self, &mut Self, self);
436 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
439 #[cfg(all(c_bindings, not(test)))]
440 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
441 offer_derived_metadata_builder_methods!(secp256k1::All);
442 offer_builder_methods!(self, &mut Self, (), ());
445 #[cfg(all(c_bindings, test))]
446 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
447 offer_derived_metadata_builder_methods!(secp256k1::All);
448 offer_builder_methods!(self, &mut Self, &mut Self, self);
449 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
453 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
454 for OfferWithDerivedMetadataBuilder<'a> {
455 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
456 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
458 Self { offer, metadata_strategy, secp_ctx }
462 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
464 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
465 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
466 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
468 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
471 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
473 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
474 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
475 #[derive(Clone, Debug)]
477 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
479 pub(super) bytes: Vec<u8>,
480 pub(super) contents: OfferContents,
483 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
484 /// [`Bolt12Invoice`].
486 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
487 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
488 #[derive(Clone, Debug)]
489 #[cfg_attr(test, derive(PartialEq))]
490 pub(super) struct OfferContents {
491 chains: Option<Vec<ChainHash>>,
492 metadata: Option<Metadata>,
493 amount: Option<Amount>,
495 features: OfferFeatures,
496 absolute_expiry: Option<Duration>,
497 issuer: Option<String>,
498 paths: Option<Vec<BlindedPath>>,
499 supported_quantity: Quantity,
500 signing_pubkey: PublicKey,
503 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
504 // TODO: Return a slice once ChainHash has constants.
505 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
506 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
507 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
508 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
509 /// for the selected chain.
510 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
514 // TODO: Link to corresponding method in `InvoiceRequest`.
515 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
516 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
517 pub fn metadata(&$self) -> Option<&Vec<u8>> {
521 /// The minimum amount required for a successful payment of a single item.
522 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
526 /// A complete description of the purpose of the payment. Intended to be displayed to the user
527 /// but with the caveat that it has not been verified in any way.
528 pub fn description(&$self) -> $crate::util::string::PrintableString {
529 $contents.description()
532 /// Features pertaining to the offer.
533 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
534 &$contents.features()
537 /// Duration since the Unix epoch when an invoice should no longer be requested.
539 /// If `None`, the offer does not expire.
540 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
541 $contents.absolute_expiry()
544 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
545 /// displayed to the user but with the caveat that it has not been verified in any way.
546 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
550 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
551 /// recipient privacy by obfuscating its node id.
552 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
556 /// The quantity of items supported.
557 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
558 $contents.supported_quantity()
561 /// The public key used by the recipient to sign invoices.
562 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
563 $contents.signing_pubkey()
568 offer_accessors!(self, self.contents);
570 pub(super) fn implied_chain(&self) -> ChainHash {
571 self.contents.implied_chain()
574 /// Returns whether the given chain is supported by the offer.
575 pub fn supports_chain(&self, chain: ChainHash) -> bool {
576 self.contents.supports_chain(chain)
579 /// Whether the offer has expired.
580 #[cfg(feature = "std")]
581 pub fn is_expired(&self) -> bool {
582 self.contents.is_expired()
585 /// Whether the offer has expired given the duration since the Unix epoch.
586 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
587 self.contents.is_expired_no_std(duration_since_epoch)
590 /// Returns whether the given quantity is valid for the offer.
591 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
592 self.contents.is_valid_quantity(quantity)
595 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
597 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
598 pub fn expects_quantity(&self) -> bool {
599 self.contents.expects_quantity()
603 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
604 /// Similar to [`Offer::request_invoice`] except it:
605 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
607 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
608 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
609 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
610 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
611 /// be used when sending the payment for the requested invoice.
613 /// Useful to protect the sender's privacy.
615 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
616 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
617 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
618 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
619 pub fn request_invoice_deriving_payer_id<
621 #[cfg(not(c_bindings))]
622 T: secp256k1::Signing
624 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
625 #[cfg(not(c_bindings))]
626 secp_ctx: &'b Secp256k1<T>,
628 secp_ctx: &'b Secp256k1<secp256k1::All>,
629 payment_id: PaymentId
630 ) -> Result<$builder, Bolt12SemanticError>
632 ES::Target: EntropySource,
634 if $self.offer_features().requires_unknown_bits() {
635 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
638 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
642 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
643 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
644 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
646 /// Useful for recurring payments using the same `payer_id` with different invoices.
648 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
649 pub fn request_invoice_deriving_metadata<ES: Deref>(
650 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
651 payment_id: PaymentId
652 ) -> Result<$builder, Bolt12SemanticError>
654 ES::Target: EntropySource,
656 if $self.offer_features().requires_unknown_bits() {
657 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
660 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
663 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
664 /// which will be reflected in the `Bolt12Invoice` response.
666 /// The `metadata` is useful for including information about the derivation of `payer_id` such
667 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
668 /// hashing in the signature calculation.
670 /// This should not leak any information such as by using a simple BIP-32 derivation path.
671 /// Otherwise, payments may be correlated.
673 /// Errors if the offer contains unknown required features.
675 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
676 pub fn request_invoice(
677 &$self, metadata: Vec<u8>, payer_id: PublicKey
678 ) -> Result<$builder, Bolt12SemanticError> {
679 if $self.offer_features().requires_unknown_bits() {
680 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
683 Ok(<$builder>::new($self, metadata, payer_id))
687 #[cfg(not(c_bindings))]
689 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
690 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
695 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
696 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
701 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
702 self.contents.as_tlv_stream()
706 impl AsRef<[u8]> for Offer {
707 fn as_ref(&self) -> &[u8] {
712 impl PartialEq for Offer {
713 fn eq(&self, other: &Self) -> bool {
714 self.bytes.eq(&other.bytes)
720 impl Hash for Offer {
721 fn hash<H: Hasher>(&self, state: &mut H) {
722 self.bytes.hash(state);
727 pub fn chains(&self) -> Vec<ChainHash> {
728 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
731 pub fn implied_chain(&self) -> ChainHash {
732 ChainHash::using_genesis_block(Network::Bitcoin)
735 pub fn supports_chain(&self, chain: ChainHash) -> bool {
736 self.chains().contains(&chain)
739 pub fn metadata(&self) -> Option<&Vec<u8>> {
740 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
743 pub fn amount(&self) -> Option<&Amount> {
747 pub fn description(&self) -> PrintableString {
748 PrintableString(&self.description)
751 pub fn features(&self) -> &OfferFeatures {
755 pub fn absolute_expiry(&self) -> Option<Duration> {
759 #[cfg(feature = "std")]
760 pub(super) fn is_expired(&self) -> bool {
761 SystemTime::UNIX_EPOCH
763 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
767 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
769 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
773 pub fn issuer(&self) -> Option<PrintableString> {
774 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
777 pub fn paths(&self) -> &[BlindedPath] {
778 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
781 pub(super) fn check_amount_msats_for_quantity(
782 &self, amount_msats: Option<u64>, quantity: Option<u64>
783 ) -> Result<(), Bolt12SemanticError> {
784 let offer_amount_msats = match self.amount {
786 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
787 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
790 if !self.expects_quantity() || quantity.is_some() {
791 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
792 .ok_or(Bolt12SemanticError::InvalidAmount)?;
793 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
795 if amount_msats < expected_amount_msats {
796 return Err(Bolt12SemanticError::InsufficientAmount);
799 if amount_msats > MAX_VALUE_MSAT {
800 return Err(Bolt12SemanticError::InvalidAmount);
807 pub fn supported_quantity(&self) -> Quantity {
808 self.supported_quantity
811 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
812 let expects_quantity = self.expects_quantity();
814 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
815 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
816 Some(quantity) if !self.is_valid_quantity(quantity) => {
817 Err(Bolt12SemanticError::InvalidQuantity)
823 fn is_valid_quantity(&self, quantity: u64) -> bool {
824 match self.supported_quantity {
825 Quantity::Bounded(n) => quantity <= n.get(),
826 Quantity::Unbounded => quantity > 0,
827 Quantity::One => quantity == 1,
831 fn expects_quantity(&self) -> bool {
832 match self.supported_quantity {
833 Quantity::Bounded(_) => true,
834 Quantity::Unbounded => true,
835 Quantity::One => false,
839 pub(super) fn signing_pubkey(&self) -> PublicKey {
843 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
844 pub(super) fn verify<T: secp256k1::Signing>(
845 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
846 ) -> Result<Option<KeyPair>, ()> {
847 match self.metadata() {
849 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
850 match record.r#type {
851 OFFER_METADATA_TYPE => false,
852 OFFER_NODE_ID_TYPE => {
853 !self.metadata.as_ref().unwrap().derives_recipient_keys()
858 signer::verify_recipient_metadata(
859 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
866 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
867 let (currency, amount) = match &self.amount {
868 None => (None, None),
869 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
870 Some(Amount::Currency { iso4217_code, amount }) => (
871 Some(iso4217_code), Some(*amount)
876 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
880 chains: self.chains.as_ref(),
881 metadata: self.metadata(),
884 description: Some(&self.description),
886 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
887 paths: self.paths.as_ref(),
888 issuer: self.issuer.as_ref(),
889 quantity_max: self.supported_quantity.to_tlv_record(),
890 node_id: Some(&self.signing_pubkey),
895 impl Writeable for Offer {
896 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
897 WithoutLength(&self.bytes).write(writer)
901 impl Writeable for OfferContents {
902 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
903 self.as_tlv_stream().write(writer)
907 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
908 /// another currency.
909 #[derive(Clone, Debug, PartialEq)]
911 /// An amount of bitcoin.
913 /// The amount in millisatoshi.
916 /// An amount of currency specified using ISO 4712.
918 /// The currency that the amount is denominated in.
919 iso4217_code: CurrencyCode,
920 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
925 /// An ISO 4712 three-letter currency code (e.g., USD).
926 pub type CurrencyCode = [u8; 3];
928 /// Quantity of items supported by an [`Offer`].
929 #[derive(Clone, Copy, Debug, PartialEq)]
931 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
932 /// but is limited (e.g., because of per customer or inventory limits).
934 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
937 /// One or more items. Use when more than one item can be requested without any limit.
939 /// Only one item. Use when only a single item can be requested.
944 fn to_tlv_record(&self) -> Option<u64> {
946 Quantity::Bounded(n) => Some(n.get()),
947 Quantity::Unbounded => Some(0),
948 Quantity::One => None,
953 /// Valid type range for offer TLV records.
954 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
956 /// TLV record type for [`Offer::metadata`].
957 const OFFER_METADATA_TYPE: u64 = 4;
959 /// TLV record type for [`Offer::signing_pubkey`].
960 const OFFER_NODE_ID_TYPE: u64 = 22;
962 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
963 (2, chains: (Vec<ChainHash>, WithoutLength)),
964 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
965 (6, currency: CurrencyCode),
966 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
967 (10, description: (String, WithoutLength)),
968 (12, features: (OfferFeatures, WithoutLength)),
969 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
970 (16, paths: (Vec<BlindedPath>, WithoutLength)),
971 (18, issuer: (String, WithoutLength)),
972 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
973 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
976 impl Bech32Encode for Offer {
977 const BECH32_HRP: &'static str = "lno";
980 impl FromStr for Offer {
981 type Err = Bolt12ParseError;
983 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
984 Self::from_bech32_str(s)
988 impl TryFrom<Vec<u8>> for Offer {
989 type Error = Bolt12ParseError;
991 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
992 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
993 let ParsedMessage { bytes, tlv_stream } = offer;
994 let contents = OfferContents::try_from(tlv_stream)?;
995 Ok(Offer { bytes, contents })
999 impl TryFrom<OfferTlvStream> for OfferContents {
1000 type Error = Bolt12SemanticError;
1002 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1003 let OfferTlvStream {
1004 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1005 issuer, quantity_max, node_id,
1008 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1010 let amount = match (currency, amount) {
1011 (None, None) => None,
1012 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1013 return Err(Bolt12SemanticError::InvalidAmount);
1015 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1016 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1017 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1020 let description = match description {
1021 None => return Err(Bolt12SemanticError::MissingDescription),
1022 Some(description) => description,
1025 let features = features.unwrap_or_else(OfferFeatures::empty);
1027 let absolute_expiry = absolute_expiry
1028 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1030 let supported_quantity = match quantity_max {
1031 None => Quantity::One,
1032 Some(0) => Quantity::Unbounded,
1033 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1036 let signing_pubkey = match node_id {
1037 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1038 Some(node_id) => node_id,
1042 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1043 supported_quantity, signing_pubkey,
1048 impl core::fmt::Display for Offer {
1049 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1050 self.fmt_bech32_str(f)
1056 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1057 #[cfg(not(c_bindings))]
1059 super::OfferBuilder,
1063 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1066 use bitcoin::blockdata::constants::ChainHash;
1067 use bitcoin::network::constants::Network;
1068 use bitcoin::secp256k1::Secp256k1;
1069 use core::num::NonZeroU64;
1070 use core::time::Duration;
1071 use crate::blinded_path::{BlindedHop, BlindedPath};
1072 use crate::sign::KeyMaterial;
1073 use crate::ln::features::OfferFeatures;
1074 use crate::ln::inbound_payment::ExpandedKey;
1075 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1076 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1077 use crate::offers::test_utils::*;
1078 use crate::util::ser::{BigSize, Writeable};
1079 use crate::util::string::PrintableString;
1082 fn builds_offer_with_defaults() {
1083 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1085 let mut buffer = Vec::new();
1086 offer.write(&mut buffer).unwrap();
1088 assert_eq!(offer.bytes, buffer.as_slice());
1089 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1090 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1091 assert_eq!(offer.metadata(), None);
1092 assert_eq!(offer.amount(), None);
1093 assert_eq!(offer.description(), PrintableString("foo"));
1094 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1095 assert_eq!(offer.absolute_expiry(), None);
1096 #[cfg(feature = "std")]
1097 assert!(!offer.is_expired());
1098 assert_eq!(offer.paths(), &[]);
1099 assert_eq!(offer.issuer(), None);
1100 assert_eq!(offer.supported_quantity(), Quantity::One);
1101 assert_eq!(offer.signing_pubkey(), pubkey(42));
1104 offer.as_tlv_stream(),
1110 description: Some(&String::from("foo")),
1112 absolute_expiry: None,
1116 node_id: Some(&pubkey(42)),
1120 if let Err(e) = Offer::try_from(buffer) {
1121 panic!("error parsing offer: {:?}", e);
1126 fn builds_offer_with_chains() {
1127 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1128 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1130 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1131 .chain(Network::Bitcoin)
1134 assert!(offer.supports_chain(mainnet));
1135 assert_eq!(offer.chains(), vec![mainnet]);
1136 assert_eq!(offer.as_tlv_stream().chains, None);
1138 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1139 .chain(Network::Testnet)
1142 assert!(offer.supports_chain(testnet));
1143 assert_eq!(offer.chains(), vec![testnet]);
1144 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1146 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1147 .chain(Network::Testnet)
1148 .chain(Network::Testnet)
1151 assert!(offer.supports_chain(testnet));
1152 assert_eq!(offer.chains(), vec![testnet]);
1153 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1155 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1156 .chain(Network::Bitcoin)
1157 .chain(Network::Testnet)
1160 assert!(offer.supports_chain(mainnet));
1161 assert!(offer.supports_chain(testnet));
1162 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1163 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1167 fn builds_offer_with_metadata() {
1168 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1169 .metadata(vec![42; 32]).unwrap()
1172 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1173 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1175 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1176 .metadata(vec![42; 32]).unwrap()
1177 .metadata(vec![43; 32]).unwrap()
1180 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1181 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1185 fn builds_offer_with_metadata_derived() {
1186 let desc = "foo".to_string();
1187 let node_id = recipient_pubkey();
1188 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1189 let entropy = FixedEntropy {};
1190 let secp_ctx = Secp256k1::new();
1193 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1194 let offer = OfferBuilder
1195 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1198 assert_eq!(offer.signing_pubkey(), node_id);
1200 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1202 .sign(payer_sign).unwrap();
1203 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1205 // Fails verification with altered offer field
1206 let mut tlv_stream = offer.as_tlv_stream();
1207 tlv_stream.amount = Some(100);
1209 let mut encoded_offer = Vec::new();
1210 tlv_stream.write(&mut encoded_offer).unwrap();
1212 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1213 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1215 .sign(payer_sign).unwrap();
1216 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1218 // Fails verification with altered metadata
1219 let mut tlv_stream = offer.as_tlv_stream();
1220 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1221 tlv_stream.metadata = Some(&metadata);
1223 let mut encoded_offer = Vec::new();
1224 tlv_stream.write(&mut encoded_offer).unwrap();
1226 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1227 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1229 .sign(payer_sign).unwrap();
1230 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1234 fn builds_offer_with_derived_signing_pubkey() {
1235 let desc = "foo".to_string();
1236 let node_id = recipient_pubkey();
1237 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1238 let entropy = FixedEntropy {};
1239 let secp_ctx = Secp256k1::new();
1241 let blinded_path = BlindedPath {
1242 introduction_node_id: pubkey(40),
1243 blinding_point: pubkey(41),
1245 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1246 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1251 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1252 let offer = OfferBuilder
1253 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1257 assert_ne!(offer.signing_pubkey(), node_id);
1259 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1261 .sign(payer_sign).unwrap();
1262 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
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 signing pubkey
1278 let mut tlv_stream = offer.as_tlv_stream();
1279 let signing_pubkey = pubkey(1);
1280 tlv_stream.node_id = Some(&signing_pubkey);
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_amount() {
1294 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1295 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1297 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1301 let tlv_stream = offer.as_tlv_stream();
1302 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1303 assert_eq!(tlv_stream.amount, Some(1000));
1304 assert_eq!(tlv_stream.currency, None);
1306 #[cfg(not(c_bindings))]
1307 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1308 .amount(currency_amount.clone());
1310 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1312 builder.amount(currency_amount.clone());
1313 let tlv_stream = builder.offer.as_tlv_stream();
1314 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1315 assert_eq!(tlv_stream.amount, Some(10));
1316 assert_eq!(tlv_stream.currency, Some(b"USD"));
1317 match builder.build() {
1318 Ok(_) => panic!("expected error"),
1319 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1322 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1323 .amount(currency_amount.clone())
1324 .amount(bitcoin_amount.clone())
1327 let tlv_stream = offer.as_tlv_stream();
1328 assert_eq!(tlv_stream.amount, Some(1000));
1329 assert_eq!(tlv_stream.currency, None);
1331 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1332 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1333 Ok(_) => panic!("expected error"),
1334 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1339 fn builds_offer_with_features() {
1340 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1341 .features_unchecked(OfferFeatures::unknown())
1344 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1345 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1347 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1348 .features_unchecked(OfferFeatures::unknown())
1349 .features_unchecked(OfferFeatures::empty())
1352 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1353 assert_eq!(offer.as_tlv_stream().features, None);
1357 fn builds_offer_with_absolute_expiry() {
1358 let future_expiry = Duration::from_secs(u64::max_value());
1359 let past_expiry = Duration::from_secs(0);
1360 let now = future_expiry - Duration::from_secs(1_000);
1362 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1363 .absolute_expiry(future_expiry)
1366 #[cfg(feature = "std")]
1367 assert!(!offer.is_expired());
1368 assert!(!offer.is_expired_no_std(now));
1369 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1370 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1372 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1373 .absolute_expiry(future_expiry)
1374 .absolute_expiry(past_expiry)
1377 #[cfg(feature = "std")]
1378 assert!(offer.is_expired());
1379 assert!(offer.is_expired_no_std(now));
1380 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1381 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1385 fn builds_offer_with_paths() {
1388 introduction_node_id: pubkey(40),
1389 blinding_point: pubkey(41),
1391 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1392 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1396 introduction_node_id: pubkey(40),
1397 blinding_point: pubkey(41),
1399 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1400 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1405 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1406 .path(paths[0].clone())
1407 .path(paths[1].clone())
1410 let tlv_stream = offer.as_tlv_stream();
1411 assert_eq!(offer.paths(), paths.as_slice());
1412 assert_eq!(offer.signing_pubkey(), pubkey(42));
1413 assert_ne!(pubkey(42), pubkey(44));
1414 assert_eq!(tlv_stream.paths, Some(&paths));
1415 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1419 fn builds_offer_with_issuer() {
1420 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1421 .issuer("bar".into())
1424 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1425 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1427 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1428 .issuer("bar".into())
1429 .issuer("baz".into())
1432 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1433 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1437 fn builds_offer_with_supported_quantity() {
1438 let one = NonZeroU64::new(1).unwrap();
1439 let ten = NonZeroU64::new(10).unwrap();
1441 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1442 .supported_quantity(Quantity::One)
1445 let tlv_stream = offer.as_tlv_stream();
1446 assert_eq!(offer.supported_quantity(), Quantity::One);
1447 assert_eq!(tlv_stream.quantity_max, None);
1449 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1450 .supported_quantity(Quantity::Unbounded)
1453 let tlv_stream = offer.as_tlv_stream();
1454 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1455 assert_eq!(tlv_stream.quantity_max, Some(0));
1457 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1458 .supported_quantity(Quantity::Bounded(ten))
1461 let tlv_stream = offer.as_tlv_stream();
1462 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1463 assert_eq!(tlv_stream.quantity_max, Some(10));
1465 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1466 .supported_quantity(Quantity::Bounded(one))
1469 let tlv_stream = offer.as_tlv_stream();
1470 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1471 assert_eq!(tlv_stream.quantity_max, Some(1));
1473 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1474 .supported_quantity(Quantity::Bounded(ten))
1475 .supported_quantity(Quantity::One)
1478 let tlv_stream = offer.as_tlv_stream();
1479 assert_eq!(offer.supported_quantity(), Quantity::One);
1480 assert_eq!(tlv_stream.quantity_max, None);
1484 fn fails_requesting_invoice_with_unknown_required_features() {
1485 match OfferBuilder::new("foo".into(), pubkey(42))
1486 .features_unchecked(OfferFeatures::unknown())
1488 .request_invoice(vec![1; 32], pubkey(43))
1490 Ok(_) => panic!("expected error"),
1491 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1496 fn parses_offer_with_chains() {
1497 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1498 .chain(Network::Bitcoin)
1499 .chain(Network::Testnet)
1502 if let Err(e) = offer.to_string().parse::<Offer>() {
1503 panic!("error parsing offer: {:?}", e);
1508 fn parses_offer_with_amount() {
1509 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1510 .amount(Amount::Bitcoin { amount_msats: 1000 })
1513 if let Err(e) = offer.to_string().parse::<Offer>() {
1514 panic!("error parsing offer: {:?}", e);
1517 let mut tlv_stream = offer.as_tlv_stream();
1518 tlv_stream.amount = Some(1000);
1519 tlv_stream.currency = Some(b"USD");
1521 let mut encoded_offer = Vec::new();
1522 tlv_stream.write(&mut encoded_offer).unwrap();
1524 if let Err(e) = Offer::try_from(encoded_offer) {
1525 panic!("error parsing offer: {:?}", e);
1528 let mut tlv_stream = offer.as_tlv_stream();
1529 tlv_stream.amount = None;
1530 tlv_stream.currency = Some(b"USD");
1532 let mut encoded_offer = Vec::new();
1533 tlv_stream.write(&mut encoded_offer).unwrap();
1535 match Offer::try_from(encoded_offer) {
1536 Ok(_) => panic!("expected error"),
1537 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1540 let mut tlv_stream = offer.as_tlv_stream();
1541 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1542 tlv_stream.currency = None;
1544 let mut encoded_offer = Vec::new();
1545 tlv_stream.write(&mut encoded_offer).unwrap();
1547 match Offer::try_from(encoded_offer) {
1548 Ok(_) => panic!("expected error"),
1549 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1554 fn parses_offer_with_description() {
1555 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1556 if let Err(e) = offer.to_string().parse::<Offer>() {
1557 panic!("error parsing offer: {:?}", e);
1560 let mut tlv_stream = offer.as_tlv_stream();
1561 tlv_stream.description = None;
1563 let mut encoded_offer = Vec::new();
1564 tlv_stream.write(&mut encoded_offer).unwrap();
1566 match Offer::try_from(encoded_offer) {
1567 Ok(_) => panic!("expected error"),
1569 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1575 fn parses_offer_with_paths() {
1576 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1578 introduction_node_id: pubkey(40),
1579 blinding_point: pubkey(41),
1581 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1582 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1586 introduction_node_id: pubkey(40),
1587 blinding_point: pubkey(41),
1589 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1590 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1595 if let Err(e) = offer.to_string().parse::<Offer>() {
1596 panic!("error parsing offer: {:?}", e);
1599 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1600 builder.offer.paths = Some(vec![]);
1602 let offer = builder.build().unwrap();
1603 if let Err(e) = offer.to_string().parse::<Offer>() {
1604 panic!("error parsing offer: {:?}", e);
1609 fn parses_offer_with_quantity() {
1610 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1611 .supported_quantity(Quantity::One)
1614 if let Err(e) = offer.to_string().parse::<Offer>() {
1615 panic!("error parsing offer: {:?}", e);
1618 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1619 .supported_quantity(Quantity::Unbounded)
1622 if let Err(e) = offer.to_string().parse::<Offer>() {
1623 panic!("error parsing offer: {:?}", e);
1626 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1627 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1630 if let Err(e) = offer.to_string().parse::<Offer>() {
1631 panic!("error parsing offer: {:?}", e);
1634 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1635 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1638 if let Err(e) = offer.to_string().parse::<Offer>() {
1639 panic!("error parsing offer: {:?}", e);
1644 fn parses_offer_with_node_id() {
1645 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1646 if let Err(e) = offer.to_string().parse::<Offer>() {
1647 panic!("error parsing offer: {:?}", e);
1650 let mut tlv_stream = offer.as_tlv_stream();
1651 tlv_stream.node_id = None;
1653 let mut encoded_offer = Vec::new();
1654 tlv_stream.write(&mut encoded_offer).unwrap();
1656 match Offer::try_from(encoded_offer) {
1657 Ok(_) => panic!("expected error"),
1659 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1665 fn fails_parsing_offer_with_extra_tlv_records() {
1666 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1668 let mut encoded_offer = Vec::new();
1669 offer.write(&mut encoded_offer).unwrap();
1670 BigSize(80).write(&mut encoded_offer).unwrap();
1671 BigSize(32).write(&mut encoded_offer).unwrap();
1672 [42u8; 32].write(&mut encoded_offer).unwrap();
1674 match Offer::try_from(encoded_offer) {
1675 Ok(_) => panic!("expected error"),
1676 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1683 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1684 use crate::ln::msgs::DecodeError;
1687 fn parses_bech32_encoded_offers() {
1689 // Minimal bolt12 offer
1690 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1693 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1695 // for bitcoin (redundant)
1696 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1698 // for bitcoin or liquidv1
1699 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1702 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1705 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1708 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1711 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1714 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1717 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1719 // with unlimited (or unknown) quantity
1720 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1722 // with single quantity (weird but valid)
1723 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1726 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1728 // with blinded path via Bob (0x424242...), blinding 020202...
1729 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1731 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1732 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1734 // unknown odd field
1735 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1737 for encoded_offer in &offers {
1738 if let Err(e) = encoded_offer.parse::<Offer>() {
1739 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1745 fn fails_parsing_bech32_encoded_offers() {
1746 // Malformed: fields out of order
1748 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1749 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1752 // Malformed: unknown even TLV type 78
1754 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1755 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1760 "lno1".parse::<Offer>(),
1761 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1764 // Malformed: truncated at type
1766 "lno1pg".parse::<Offer>(),
1767 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1770 // Malformed: truncated in length
1772 "lno1pt7s".parse::<Offer>(),
1773 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1776 // Malformed: truncated after length
1778 "lno1pgpq".parse::<Offer>(),
1779 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1782 // Malformed: truncated in description
1784 "lno1pgpyz".parse::<Offer>(),
1785 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1788 // Malformed: invalid offer_chains length
1790 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1791 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1794 // Malformed: truncated currency UTF-8
1796 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1797 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1800 // Malformed: invalid currency UTF-8
1802 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1803 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1806 // Malformed: truncated description UTF-8
1808 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1809 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1812 // Malformed: invalid description UTF-8
1814 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1815 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1818 // Malformed: truncated offer_paths
1820 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1821 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1824 // Malformed: zero num_hops in blinded_path
1826 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1827 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1830 // Malformed: truncated onionmsg_hop in blinded_path
1832 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1833 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1836 // Malformed: bad first_node_id in blinded_path
1838 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1839 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1842 // Malformed: bad blinding in blinded_path
1844 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1845 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1848 // Malformed: bad blinded_node_id in onionmsg_hop
1850 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1851 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1854 // Malformed: truncated issuer UTF-8
1856 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1857 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1860 // Malformed: invalid issuer UTF-8
1862 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1863 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1866 // Malformed: invalid offer_node_id
1868 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1869 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1872 // Contains type >= 80
1874 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1875 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1878 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1879 // Contains unknown feature 22
1881 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1884 // Missing offer_description
1886 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1887 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1890 // Missing offer_node_id"
1892 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1893 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),