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: Some(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: Some(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 = Some(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(crate) fn clear_signing_pubkey($($self_mut)* $self: $self_type) -> $return_type {
441 $self.offer.signing_pubkey = None;
445 #[cfg_attr(c_bindings, allow(dead_code))]
446 pub(super) fn build_unchecked($self: $self_type) -> Offer {
447 $self.build_without_checks()
451 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
452 offer_builder_methods!(self, Self, Self, self, mut);
455 offer_builder_test_methods!(self, Self, Self, self, mut);
458 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
459 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
462 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
463 offer_derived_metadata_builder_methods!(T);
466 #[cfg(all(c_bindings, not(test)))]
467 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
468 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
469 offer_builder_methods!(self, &mut Self, (), ());
472 #[cfg(all(c_bindings, test))]
473 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
474 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
475 offer_builder_methods!(self, &mut Self, &mut Self, self);
476 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
479 #[cfg(all(c_bindings, not(test)))]
480 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
481 offer_derived_metadata_builder_methods!(secp256k1::All);
482 offer_builder_methods!(self, &mut Self, (), ());
485 #[cfg(all(c_bindings, test))]
486 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
487 offer_derived_metadata_builder_methods!(secp256k1::All);
488 offer_builder_methods!(self, &mut Self, &mut Self, self);
489 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
493 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
494 for OfferWithDerivedMetadataBuilder<'a> {
495 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
496 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
498 Self { offer, metadata_strategy, secp_ctx }
503 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
504 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
505 fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
506 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
508 Self { offer, metadata_strategy, secp_ctx }
512 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
514 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
515 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
516 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
518 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
521 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
523 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
524 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
525 #[derive(Clone, Debug)]
527 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
529 pub(super) bytes: Vec<u8>,
530 pub(super) contents: OfferContents,
534 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
535 /// [`Bolt12Invoice`].
537 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
538 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
539 #[derive(Clone, Debug)]
540 #[cfg_attr(test, derive(PartialEq))]
541 pub(super) struct OfferContents {
542 chains: Option<Vec<ChainHash>>,
543 metadata: Option<Metadata>,
544 amount: Option<Amount>,
546 features: OfferFeatures,
547 absolute_expiry: Option<Duration>,
548 issuer: Option<String>,
549 paths: Option<Vec<BlindedPath>>,
550 supported_quantity: Quantity,
551 signing_pubkey: Option<PublicKey>,
554 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
555 // TODO: Return a slice once ChainHash has constants.
556 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
557 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
558 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
559 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
560 /// for the selected chain.
561 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
565 // TODO: Link to corresponding method in `InvoiceRequest`.
566 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
567 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
568 pub fn metadata(&$self) -> Option<&Vec<u8>> {
572 /// The minimum amount required for a successful payment of a single item.
573 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
577 /// A complete description of the purpose of the payment. Intended to be displayed to the user
578 /// but with the caveat that it has not been verified in any way.
579 pub fn description(&$self) -> $crate::util::string::PrintableString {
580 $contents.description()
583 /// Features pertaining to the offer.
584 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
585 &$contents.features()
588 /// Duration since the Unix epoch when an invoice should no longer be requested.
590 /// If `None`, the offer does not expire.
591 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
592 $contents.absolute_expiry()
595 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
596 /// displayed to the user but with the caveat that it has not been verified in any way.
597 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
601 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
602 /// recipient privacy by obfuscating its node id.
603 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
607 /// The quantity of items supported.
608 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
609 $contents.supported_quantity()
612 /// The public key used by the recipient to sign invoices.
613 pub fn signing_pubkey(&$self) -> Option<bitcoin::secp256k1::PublicKey> {
614 $contents.signing_pubkey()
619 offer_accessors!(self, self.contents);
621 /// Returns the id of the offer.
622 pub fn id(&self) -> OfferId {
626 pub(super) fn implied_chain(&self) -> ChainHash {
627 self.contents.implied_chain()
630 /// Returns whether the given chain is supported by the offer.
631 pub fn supports_chain(&self, chain: ChainHash) -> bool {
632 self.contents.supports_chain(chain)
635 /// Whether the offer has expired.
636 #[cfg(feature = "std")]
637 pub fn is_expired(&self) -> bool {
638 self.contents.is_expired()
641 /// Whether the offer has expired given the duration since the Unix epoch.
642 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
643 self.contents.is_expired_no_std(duration_since_epoch)
646 /// Returns whether the given quantity is valid for the offer.
647 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
648 self.contents.is_valid_quantity(quantity)
651 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
653 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
654 pub fn expects_quantity(&self) -> bool {
655 self.contents.expects_quantity()
659 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
660 /// Similar to [`Offer::request_invoice`] except it:
661 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
663 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
664 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
665 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
666 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
667 /// be used when sending the payment for the requested invoice.
669 /// Useful to protect the sender's privacy.
671 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
672 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
673 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
674 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
675 pub fn request_invoice_deriving_payer_id<
677 #[cfg(not(c_bindings))]
678 T: secp256k1::Signing
680 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
681 #[cfg(not(c_bindings))]
682 secp_ctx: &'b Secp256k1<T>,
684 secp_ctx: &'b Secp256k1<secp256k1::All>,
685 payment_id: PaymentId
686 ) -> Result<$builder, Bolt12SemanticError>
688 ES::Target: EntropySource,
690 if $self.offer_features().requires_unknown_bits() {
691 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
694 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
698 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
699 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
700 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
702 /// Useful for recurring payments using the same `payer_id` with different invoices.
704 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
705 pub fn request_invoice_deriving_metadata<ES: Deref>(
706 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
707 payment_id: PaymentId
708 ) -> Result<$builder, Bolt12SemanticError>
710 ES::Target: EntropySource,
712 if $self.offer_features().requires_unknown_bits() {
713 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
716 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
719 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
720 /// which will be reflected in the `Bolt12Invoice` response.
722 /// The `metadata` is useful for including information about the derivation of `payer_id` such
723 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
724 /// hashing in the signature calculation.
726 /// This should not leak any information such as by using a simple BIP-32 derivation path.
727 /// Otherwise, payments may be correlated.
729 /// Errors if the offer contains unknown required features.
731 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
732 pub fn request_invoice(
733 &$self, metadata: Vec<u8>, payer_id: PublicKey
734 ) -> Result<$builder, Bolt12SemanticError> {
735 if $self.offer_features().requires_unknown_bits() {
736 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
739 Ok(<$builder>::new($self, metadata, payer_id))
743 #[cfg(not(c_bindings))]
745 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
746 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
751 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
752 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
757 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
758 self.contents.as_tlv_stream()
762 impl AsRef<[u8]> for Offer {
763 fn as_ref(&self) -> &[u8] {
768 impl PartialEq for Offer {
769 fn eq(&self, other: &Self) -> bool {
770 self.bytes.eq(&other.bytes)
776 impl Hash for Offer {
777 fn hash<H: Hasher>(&self, state: &mut H) {
778 self.bytes.hash(state);
783 pub fn chains(&self) -> Vec<ChainHash> {
784 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
787 pub fn implied_chain(&self) -> ChainHash {
788 ChainHash::using_genesis_block(Network::Bitcoin)
791 pub fn supports_chain(&self, chain: ChainHash) -> bool {
792 self.chains().contains(&chain)
795 pub fn metadata(&self) -> Option<&Vec<u8>> {
796 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
799 pub fn amount(&self) -> Option<&Amount> {
803 pub fn description(&self) -> PrintableString {
804 PrintableString(&self.description)
807 pub fn features(&self) -> &OfferFeatures {
811 pub fn absolute_expiry(&self) -> Option<Duration> {
815 #[cfg(feature = "std")]
816 pub(super) fn is_expired(&self) -> bool {
817 SystemTime::UNIX_EPOCH
819 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
823 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
825 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
829 pub fn issuer(&self) -> Option<PrintableString> {
830 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
833 pub fn paths(&self) -> &[BlindedPath] {
834 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
837 pub(super) fn check_amount_msats_for_quantity(
838 &self, amount_msats: Option<u64>, quantity: Option<u64>
839 ) -> Result<(), Bolt12SemanticError> {
840 let offer_amount_msats = match self.amount {
842 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
843 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
846 if !self.expects_quantity() || quantity.is_some() {
847 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
848 .ok_or(Bolt12SemanticError::InvalidAmount)?;
849 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
851 if amount_msats < expected_amount_msats {
852 return Err(Bolt12SemanticError::InsufficientAmount);
855 if amount_msats > MAX_VALUE_MSAT {
856 return Err(Bolt12SemanticError::InvalidAmount);
863 pub fn supported_quantity(&self) -> Quantity {
864 self.supported_quantity
867 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
868 let expects_quantity = self.expects_quantity();
870 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
871 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
872 Some(quantity) if !self.is_valid_quantity(quantity) => {
873 Err(Bolt12SemanticError::InvalidQuantity)
879 fn is_valid_quantity(&self, quantity: u64) -> bool {
880 match self.supported_quantity {
881 Quantity::Bounded(n) => quantity <= n.get(),
882 Quantity::Unbounded => quantity > 0,
883 Quantity::One => quantity == 1,
887 fn expects_quantity(&self) -> bool {
888 match self.supported_quantity {
889 Quantity::Bounded(_) => true,
890 Quantity::Unbounded => true,
891 Quantity::One => false,
895 pub(super) fn signing_pubkey(&self) -> Option<PublicKey> {
899 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
900 pub(super) fn verify<T: secp256k1::Signing>(
901 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
902 ) -> Result<(OfferId, Option<KeyPair>), ()> {
903 match self.metadata() {
905 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
906 match record.r#type {
907 OFFER_METADATA_TYPE => false,
908 OFFER_NODE_ID_TYPE => {
909 !self.metadata.as_ref().unwrap().derives_recipient_keys()
914 let signing_pubkey = match self.signing_pubkey() {
915 Some(signing_pubkey) => signing_pubkey,
916 None => return Err(()),
918 let keys = signer::verify_recipient_metadata(
919 metadata, key, IV_BYTES, signing_pubkey, tlv_stream, secp_ctx
922 let offer_id = OfferId::from_valid_invreq_tlv_stream(bytes);
930 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
931 let (currency, amount) = match &self.amount {
932 None => (None, None),
933 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
934 Some(Amount::Currency { iso4217_code, amount }) => (
935 Some(iso4217_code), Some(*amount)
940 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
944 chains: self.chains.as_ref(),
945 metadata: self.metadata(),
948 description: Some(&self.description),
950 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
951 paths: self.paths.as_ref(),
952 issuer: self.issuer.as_ref(),
953 quantity_max: self.supported_quantity.to_tlv_record(),
954 node_id: self.signing_pubkey.as_ref(),
959 impl Writeable for Offer {
960 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
961 WithoutLength(&self.bytes).write(writer)
965 impl Writeable for OfferContents {
966 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
967 self.as_tlv_stream().write(writer)
971 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
972 /// another currency.
973 #[derive(Clone, Debug, PartialEq)]
975 /// An amount of bitcoin.
977 /// The amount in millisatoshi.
980 /// An amount of currency specified using ISO 4712.
982 /// The currency that the amount is denominated in.
983 iso4217_code: CurrencyCode,
984 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
989 /// An ISO 4712 three-letter currency code (e.g., USD).
990 pub type CurrencyCode = [u8; 3];
992 /// Quantity of items supported by an [`Offer`].
993 #[derive(Clone, Copy, Debug, PartialEq)]
995 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
996 /// but is limited (e.g., because of per customer or inventory limits).
998 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
1000 Bounded(NonZeroU64),
1001 /// One or more items. Use when more than one item can be requested without any limit.
1003 /// Only one item. Use when only a single item can be requested.
1008 fn to_tlv_record(&self) -> Option<u64> {
1010 Quantity::Bounded(n) => Some(n.get()),
1011 Quantity::Unbounded => Some(0),
1012 Quantity::One => None,
1017 /// Valid type range for offer TLV records.
1018 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
1020 /// TLV record type for [`Offer::metadata`].
1021 const OFFER_METADATA_TYPE: u64 = 4;
1023 /// TLV record type for [`Offer::signing_pubkey`].
1024 const OFFER_NODE_ID_TYPE: u64 = 22;
1026 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
1027 (2, chains: (Vec<ChainHash>, WithoutLength)),
1028 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1029 (6, currency: CurrencyCode),
1030 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
1031 (10, description: (String, WithoutLength)),
1032 (12, features: (OfferFeatures, WithoutLength)),
1033 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
1034 (16, paths: (Vec<BlindedPath>, WithoutLength)),
1035 (18, issuer: (String, WithoutLength)),
1036 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
1037 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
1040 impl Bech32Encode for Offer {
1041 const BECH32_HRP: &'static str = "lno";
1044 impl FromStr for Offer {
1045 type Err = Bolt12ParseError;
1047 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
1048 Self::from_bech32_str(s)
1052 impl TryFrom<Vec<u8>> for Offer {
1053 type Error = Bolt12ParseError;
1055 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1056 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1057 let ParsedMessage { bytes, tlv_stream } = offer;
1058 let contents = OfferContents::try_from(tlv_stream)?;
1059 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
1061 Ok(Offer { bytes, contents, id })
1065 impl TryFrom<OfferTlvStream> for OfferContents {
1066 type Error = Bolt12SemanticError;
1068 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1069 let OfferTlvStream {
1070 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1071 issuer, quantity_max, node_id,
1074 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1076 let amount = match (currency, amount) {
1077 (None, None) => None,
1078 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1079 return Err(Bolt12SemanticError::InvalidAmount);
1081 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1082 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1083 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1086 let description = match description {
1087 None => return Err(Bolt12SemanticError::MissingDescription),
1088 Some(description) => description,
1091 let features = features.unwrap_or_else(OfferFeatures::empty);
1093 let absolute_expiry = absolute_expiry
1094 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1096 let supported_quantity = match quantity_max {
1097 None => Quantity::One,
1098 Some(0) => Quantity::Unbounded,
1099 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1102 let (signing_pubkey, paths) = match (node_id, paths) {
1103 (None, None) => return Err(Bolt12SemanticError::MissingSigningPubkey),
1104 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1105 (node_id, paths) => (node_id, paths),
1109 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1110 supported_quantity, signing_pubkey,
1115 impl core::fmt::Display for Offer {
1116 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1117 self.fmt_bech32_str(f)
1123 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1124 #[cfg(not(c_bindings))]
1126 super::OfferBuilder,
1130 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1133 use bitcoin::blockdata::constants::ChainHash;
1134 use bitcoin::network::constants::Network;
1135 use bitcoin::secp256k1::Secp256k1;
1136 use core::num::NonZeroU64;
1137 use core::time::Duration;
1138 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1139 use crate::sign::KeyMaterial;
1140 use crate::ln::features::OfferFeatures;
1141 use crate::ln::inbound_payment::ExpandedKey;
1142 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1143 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1144 use crate::offers::test_utils::*;
1145 use crate::util::ser::{BigSize, Writeable};
1146 use crate::util::string::PrintableString;
1149 fn builds_offer_with_defaults() {
1150 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1152 let mut buffer = Vec::new();
1153 offer.write(&mut buffer).unwrap();
1155 assert_eq!(offer.bytes, buffer.as_slice());
1156 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1157 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1158 assert_eq!(offer.metadata(), None);
1159 assert_eq!(offer.amount(), None);
1160 assert_eq!(offer.description(), PrintableString("foo"));
1161 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1162 assert_eq!(offer.absolute_expiry(), None);
1163 #[cfg(feature = "std")]
1164 assert!(!offer.is_expired());
1165 assert_eq!(offer.paths(), &[]);
1166 assert_eq!(offer.issuer(), None);
1167 assert_eq!(offer.supported_quantity(), Quantity::One);
1168 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1171 offer.as_tlv_stream(),
1177 description: Some(&String::from("foo")),
1179 absolute_expiry: None,
1183 node_id: Some(&pubkey(42)),
1187 if let Err(e) = Offer::try_from(buffer) {
1188 panic!("error parsing offer: {:?}", e);
1193 fn builds_offer_with_chains() {
1194 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1195 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1197 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1198 .chain(Network::Bitcoin)
1201 assert!(offer.supports_chain(mainnet));
1202 assert_eq!(offer.chains(), vec![mainnet]);
1203 assert_eq!(offer.as_tlv_stream().chains, None);
1205 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1206 .chain(Network::Testnet)
1209 assert!(offer.supports_chain(testnet));
1210 assert_eq!(offer.chains(), vec![testnet]);
1211 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1213 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1214 .chain(Network::Testnet)
1215 .chain(Network::Testnet)
1218 assert!(offer.supports_chain(testnet));
1219 assert_eq!(offer.chains(), vec![testnet]);
1220 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1222 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1223 .chain(Network::Bitcoin)
1224 .chain(Network::Testnet)
1227 assert!(offer.supports_chain(mainnet));
1228 assert!(offer.supports_chain(testnet));
1229 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1230 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1234 fn builds_offer_with_metadata() {
1235 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1236 .metadata(vec![42; 32]).unwrap()
1239 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1240 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1242 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1243 .metadata(vec![42; 32]).unwrap()
1244 .metadata(vec![43; 32]).unwrap()
1247 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1248 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1252 fn builds_offer_with_metadata_derived() {
1253 let desc = "foo".to_string();
1254 let node_id = recipient_pubkey();
1255 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1256 let entropy = FixedEntropy {};
1257 let secp_ctx = Secp256k1::new();
1260 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1261 let offer = OfferBuilder
1262 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1265 assert_eq!(offer.signing_pubkey(), Some(node_id));
1267 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1269 .sign(payer_sign).unwrap();
1270 match invoice_request.verify(&expanded_key, &secp_ctx) {
1271 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1272 Err(_) => panic!("unexpected error"),
1275 // Fails verification with altered offer field
1276 let mut tlv_stream = offer.as_tlv_stream();
1277 tlv_stream.amount = Some(100);
1279 let mut encoded_offer = Vec::new();
1280 tlv_stream.write(&mut encoded_offer).unwrap();
1282 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1285 .sign(payer_sign).unwrap();
1286 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1288 // Fails verification with altered metadata
1289 let mut tlv_stream = offer.as_tlv_stream();
1290 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1291 tlv_stream.metadata = Some(&metadata);
1293 let mut encoded_offer = Vec::new();
1294 tlv_stream.write(&mut encoded_offer).unwrap();
1296 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1297 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1299 .sign(payer_sign).unwrap();
1300 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1304 fn builds_offer_with_derived_signing_pubkey() {
1305 let desc = "foo".to_string();
1306 let node_id = recipient_pubkey();
1307 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1308 let entropy = FixedEntropy {};
1309 let secp_ctx = Secp256k1::new();
1311 let blinded_path = BlindedPath {
1312 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1313 blinding_point: pubkey(41),
1315 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1316 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1321 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1322 let offer = OfferBuilder
1323 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1327 assert_ne!(offer.signing_pubkey(), Some(node_id));
1329 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1331 .sign(payer_sign).unwrap();
1332 match invoice_request.verify(&expanded_key, &secp_ctx) {
1333 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1334 Err(_) => panic!("unexpected error"),
1337 // Fails verification with altered offer field
1338 let mut tlv_stream = offer.as_tlv_stream();
1339 tlv_stream.amount = Some(100);
1341 let mut encoded_offer = Vec::new();
1342 tlv_stream.write(&mut encoded_offer).unwrap();
1344 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1345 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1347 .sign(payer_sign).unwrap();
1348 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1350 // Fails verification with altered signing pubkey
1351 let mut tlv_stream = offer.as_tlv_stream();
1352 let signing_pubkey = pubkey(1);
1353 tlv_stream.node_id = Some(&signing_pubkey);
1355 let mut encoded_offer = Vec::new();
1356 tlv_stream.write(&mut encoded_offer).unwrap();
1358 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1359 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1361 .sign(payer_sign).unwrap();
1362 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1366 fn builds_offer_with_amount() {
1367 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1368 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1370 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1374 let tlv_stream = offer.as_tlv_stream();
1375 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1376 assert_eq!(tlv_stream.amount, Some(1000));
1377 assert_eq!(tlv_stream.currency, None);
1379 #[cfg(not(c_bindings))]
1380 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1381 .amount(currency_amount.clone());
1383 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1385 builder.amount(currency_amount.clone());
1386 let tlv_stream = builder.offer.as_tlv_stream();
1387 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1388 assert_eq!(tlv_stream.amount, Some(10));
1389 assert_eq!(tlv_stream.currency, Some(b"USD"));
1390 match builder.build() {
1391 Ok(_) => panic!("expected error"),
1392 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1395 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1396 .amount(currency_amount.clone())
1397 .amount(bitcoin_amount.clone())
1400 let tlv_stream = offer.as_tlv_stream();
1401 assert_eq!(tlv_stream.amount, Some(1000));
1402 assert_eq!(tlv_stream.currency, None);
1404 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1405 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1406 Ok(_) => panic!("expected error"),
1407 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1412 fn builds_offer_with_features() {
1413 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1414 .features_unchecked(OfferFeatures::unknown())
1417 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1418 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1420 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1421 .features_unchecked(OfferFeatures::unknown())
1422 .features_unchecked(OfferFeatures::empty())
1425 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1426 assert_eq!(offer.as_tlv_stream().features, None);
1430 fn builds_offer_with_absolute_expiry() {
1431 let future_expiry = Duration::from_secs(u64::max_value());
1432 let past_expiry = Duration::from_secs(0);
1433 let now = future_expiry - Duration::from_secs(1_000);
1435 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1436 .absolute_expiry(future_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(future_expiry));
1443 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1445 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1446 .absolute_expiry(future_expiry)
1447 .absolute_expiry(past_expiry)
1450 #[cfg(feature = "std")]
1451 assert!(offer.is_expired());
1452 assert!(offer.is_expired_no_std(now));
1453 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1454 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1458 fn builds_offer_with_paths() {
1461 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1462 blinding_point: pubkey(41),
1464 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1465 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1469 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1470 blinding_point: pubkey(41),
1472 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1473 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1478 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1479 .path(paths[0].clone())
1480 .path(paths[1].clone())
1483 let tlv_stream = offer.as_tlv_stream();
1484 assert_eq!(offer.paths(), paths.as_slice());
1485 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1486 assert_ne!(pubkey(42), pubkey(44));
1487 assert_eq!(tlv_stream.paths, Some(&paths));
1488 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1492 fn builds_offer_with_issuer() {
1493 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1494 .issuer("bar".into())
1497 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1498 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1500 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1501 .issuer("bar".into())
1502 .issuer("baz".into())
1505 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1506 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1510 fn builds_offer_with_supported_quantity() {
1511 let one = NonZeroU64::new(1).unwrap();
1512 let ten = NonZeroU64::new(10).unwrap();
1514 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1515 .supported_quantity(Quantity::One)
1518 let tlv_stream = offer.as_tlv_stream();
1519 assert_eq!(offer.supported_quantity(), Quantity::One);
1520 assert_eq!(tlv_stream.quantity_max, None);
1522 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1523 .supported_quantity(Quantity::Unbounded)
1526 let tlv_stream = offer.as_tlv_stream();
1527 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1528 assert_eq!(tlv_stream.quantity_max, Some(0));
1530 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1531 .supported_quantity(Quantity::Bounded(ten))
1534 let tlv_stream = offer.as_tlv_stream();
1535 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1536 assert_eq!(tlv_stream.quantity_max, Some(10));
1538 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1539 .supported_quantity(Quantity::Bounded(one))
1542 let tlv_stream = offer.as_tlv_stream();
1543 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1544 assert_eq!(tlv_stream.quantity_max, Some(1));
1546 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1547 .supported_quantity(Quantity::Bounded(ten))
1548 .supported_quantity(Quantity::One)
1551 let tlv_stream = offer.as_tlv_stream();
1552 assert_eq!(offer.supported_quantity(), Quantity::One);
1553 assert_eq!(tlv_stream.quantity_max, None);
1557 fn fails_requesting_invoice_with_unknown_required_features() {
1558 match OfferBuilder::new("foo".into(), pubkey(42))
1559 .features_unchecked(OfferFeatures::unknown())
1561 .request_invoice(vec![1; 32], pubkey(43))
1563 Ok(_) => panic!("expected error"),
1564 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1569 fn parses_offer_with_chains() {
1570 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1571 .chain(Network::Bitcoin)
1572 .chain(Network::Testnet)
1575 if let Err(e) = offer.to_string().parse::<Offer>() {
1576 panic!("error parsing offer: {:?}", e);
1581 fn parses_offer_with_amount() {
1582 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1583 .amount(Amount::Bitcoin { amount_msats: 1000 })
1586 if let Err(e) = offer.to_string().parse::<Offer>() {
1587 panic!("error parsing offer: {:?}", e);
1590 let mut tlv_stream = offer.as_tlv_stream();
1591 tlv_stream.amount = Some(1000);
1592 tlv_stream.currency = Some(b"USD");
1594 let mut encoded_offer = Vec::new();
1595 tlv_stream.write(&mut encoded_offer).unwrap();
1597 if let Err(e) = Offer::try_from(encoded_offer) {
1598 panic!("error parsing offer: {:?}", e);
1601 let mut tlv_stream = offer.as_tlv_stream();
1602 tlv_stream.amount = None;
1603 tlv_stream.currency = Some(b"USD");
1605 let mut encoded_offer = Vec::new();
1606 tlv_stream.write(&mut encoded_offer).unwrap();
1608 match Offer::try_from(encoded_offer) {
1609 Ok(_) => panic!("expected error"),
1610 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1613 let mut tlv_stream = offer.as_tlv_stream();
1614 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1615 tlv_stream.currency = None;
1617 let mut encoded_offer = Vec::new();
1618 tlv_stream.write(&mut encoded_offer).unwrap();
1620 match Offer::try_from(encoded_offer) {
1621 Ok(_) => panic!("expected error"),
1622 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1627 fn parses_offer_with_description() {
1628 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1629 if let Err(e) = offer.to_string().parse::<Offer>() {
1630 panic!("error parsing offer: {:?}", e);
1633 let mut tlv_stream = offer.as_tlv_stream();
1634 tlv_stream.description = None;
1636 let mut encoded_offer = Vec::new();
1637 tlv_stream.write(&mut encoded_offer).unwrap();
1639 match Offer::try_from(encoded_offer) {
1640 Ok(_) => panic!("expected error"),
1642 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1648 fn parses_offer_with_paths() {
1649 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1651 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1652 blinding_point: pubkey(41),
1654 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1655 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1659 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1660 blinding_point: pubkey(41),
1662 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1663 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1668 if let Err(e) = offer.to_string().parse::<Offer>() {
1669 panic!("error parsing offer: {:?}", e);
1672 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1674 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1675 blinding_point: pubkey(41),
1677 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1678 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1681 .clear_signing_pubkey()
1684 if let Err(e) = offer.to_string().parse::<Offer>() {
1685 panic!("error parsing offer: {:?}", e);
1688 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1689 builder.offer.paths = Some(vec![]);
1691 let offer = builder.build().unwrap();
1692 match offer.to_string().parse::<Offer>() {
1693 Ok(_) => panic!("expected error"),
1695 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths));
1701 fn parses_offer_with_quantity() {
1702 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1703 .supported_quantity(Quantity::One)
1706 if let Err(e) = offer.to_string().parse::<Offer>() {
1707 panic!("error parsing offer: {:?}", e);
1710 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1711 .supported_quantity(Quantity::Unbounded)
1714 if let Err(e) = offer.to_string().parse::<Offer>() {
1715 panic!("error parsing offer: {:?}", e);
1718 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1719 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1722 if let Err(e) = offer.to_string().parse::<Offer>() {
1723 panic!("error parsing offer: {:?}", e);
1726 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1727 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1730 if let Err(e) = offer.to_string().parse::<Offer>() {
1731 panic!("error parsing offer: {:?}", e);
1736 fn parses_offer_with_node_id() {
1737 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1738 if let Err(e) = offer.to_string().parse::<Offer>() {
1739 panic!("error parsing offer: {:?}", e);
1742 let mut tlv_stream = offer.as_tlv_stream();
1743 tlv_stream.node_id = None;
1745 let mut encoded_offer = Vec::new();
1746 tlv_stream.write(&mut encoded_offer).unwrap();
1748 match Offer::try_from(encoded_offer) {
1749 Ok(_) => panic!("expected error"),
1751 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1757 fn fails_parsing_offer_with_extra_tlv_records() {
1758 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1760 let mut encoded_offer = Vec::new();
1761 offer.write(&mut encoded_offer).unwrap();
1762 BigSize(80).write(&mut encoded_offer).unwrap();
1763 BigSize(32).write(&mut encoded_offer).unwrap();
1764 [42u8; 32].write(&mut encoded_offer).unwrap();
1766 match Offer::try_from(encoded_offer) {
1767 Ok(_) => panic!("expected error"),
1768 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1775 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1776 use crate::ln::msgs::DecodeError;
1779 fn parses_bech32_encoded_offers() {
1781 // Minimal bolt12 offer
1782 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1785 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1787 // for bitcoin (redundant)
1788 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1790 // for bitcoin or liquidv1
1791 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1794 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1797 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1800 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1803 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1806 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1809 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1811 // with unlimited (or unknown) quantity
1812 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1814 // with single quantity (weird but valid)
1815 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1818 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1820 // with blinded path via Bob (0x424242...), blinding 020202...
1821 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1823 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1824 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1826 // unknown odd field
1827 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1829 for encoded_offer in &offers {
1830 if let Err(e) = encoded_offer.parse::<Offer>() {
1831 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1837 fn fails_parsing_bech32_encoded_offers() {
1838 // Malformed: fields out of order
1840 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1841 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1844 // Malformed: unknown even TLV type 78
1846 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1847 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1852 "lno1".parse::<Offer>(),
1853 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1856 // Malformed: truncated at type
1858 "lno1pg".parse::<Offer>(),
1859 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1862 // Malformed: truncated in length
1864 "lno1pt7s".parse::<Offer>(),
1865 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1868 // Malformed: truncated after length
1870 "lno1pgpq".parse::<Offer>(),
1871 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1874 // Malformed: truncated in description
1876 "lno1pgpyz".parse::<Offer>(),
1877 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1880 // Malformed: invalid offer_chains length
1882 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1883 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1886 // Malformed: truncated currency UTF-8
1888 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1889 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1892 // Malformed: invalid currency UTF-8
1894 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1895 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1898 // Malformed: truncated description UTF-8
1900 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1901 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1904 // Malformed: invalid description UTF-8
1906 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1907 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1910 // Malformed: truncated offer_paths
1912 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1913 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1916 // Malformed: zero num_hops in blinded_path
1918 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1919 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1922 // Malformed: truncated onionmsg_hop in blinded_path
1924 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1925 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1928 // Malformed: bad first_node_id in blinded_path
1930 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1931 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1934 // Malformed: bad blinding in blinded_path
1936 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1937 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1940 // Malformed: bad blinded_node_id in onionmsg_hop
1942 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1943 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1946 // Malformed: truncated issuer UTF-8
1948 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1949 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1952 // Malformed: invalid issuer UTF-8
1954 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1955 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1958 // Malformed: invalid offer_node_id
1960 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1961 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1964 // Contains type >= 80
1966 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1967 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1970 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1971 // Contains unknown feature 22
1973 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1976 // Missing offer_description
1978 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1979 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1982 // Missing offer_node_id"
1984 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1985 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),