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(pubkey)
47 //! .description("coffee, large".to_string())
48 //! .amount_msats(20_000)
49 //! .supported_quantity(Quantity::Unbounded)
50 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
51 //! .issuer("Foo Bar".to_string())
52 //! .path(create_blinded_path())
53 //! .path(create_another_blinded_path())
56 //! // Encode as a bech32 string for use in a QR code.
57 //! let encoded_offer = offer.to_string();
59 //! // Parse from a bech32 string after scanning from a QR code.
60 //! let offer = encoded_offer.parse::<Offer>()?;
62 //! // Encode offer as raw bytes.
63 //! let mut bytes = Vec::new();
64 //! offer.write(&mut bytes).unwrap();
66 //! // Decode raw bytes into an offer.
67 //! let offer = Offer::try_from(bytes)?;
74 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
75 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
77 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
78 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
80 use bitcoin::blockdata::constants::ChainHash;
81 use bitcoin::network::constants::Network;
82 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
83 use core::hash::{Hash, Hasher};
84 use core::num::NonZeroU64;
86 use core::str::FromStr;
87 use core::time::Duration;
88 use crate::sign::EntropySource;
90 use crate::blinded_path::BlindedPath;
91 use crate::ln::channelmanager::PaymentId;
92 use crate::ln::features::OfferFeatures;
93 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
94 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
95 use crate::offers::merkle::{TaggedHash, TlvStream};
96 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
97 use crate::offers::signer::{Metadata, MetadataMaterial, self};
98 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
99 use crate::util::string::PrintableString;
101 #[cfg(not(c_bindings))]
103 crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder},
107 crate::offers::invoice_request::{InvoiceRequestWithDerivedPayerIdBuilder, InvoiceRequestWithExplicitPayerIdBuilder},
110 #[allow(unused_imports)]
111 use crate::prelude::*;
113 #[cfg(feature = "std")]
114 use std::time::SystemTime;
116 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
118 /// An identifier for an [`Offer`] built using [`DerivedMetadata`].
119 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
120 pub struct OfferId(pub [u8; 32]);
123 const ID_TAG: &'static str = "LDK Offer ID";
125 fn from_valid_offer_tlv_stream(bytes: &[u8]) -> Self {
126 let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(Self::ID_TAG, bytes);
127 Self(tagged_hash.to_bytes())
130 fn from_valid_invreq_tlv_stream(bytes: &[u8]) -> Self {
131 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES);
132 let tagged_hash = TaggedHash::from_tlv_stream(Self::ID_TAG, tlv_stream);
133 Self(tagged_hash.to_bytes())
137 impl Writeable for OfferId {
138 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
143 impl Readable for OfferId {
144 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
145 Ok(OfferId(Readable::read(r)?))
149 /// Builds an [`Offer`] for the "offer to be paid" flow.
151 /// See [module-level documentation] for usage.
153 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
155 /// [module-level documentation]: self
156 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
157 offer: OfferContents,
158 metadata_strategy: core::marker::PhantomData<M>,
159 secp_ctx: Option<&'a Secp256k1<T>>,
162 /// Builds an [`Offer`] for the "offer to be paid" flow.
164 /// See [module-level documentation] for usage.
166 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
168 /// [module-level documentation]: self
170 pub struct OfferWithExplicitMetadataBuilder<'a> {
171 offer: OfferContents,
172 metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
173 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
176 /// Builds an [`Offer`] for the "offer to be paid" flow.
178 /// See [module-level documentation] for usage.
180 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
182 /// [module-level documentation]: self
184 pub struct OfferWithDerivedMetadataBuilder<'a> {
185 offer: OfferContents,
186 metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
187 secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
190 /// Indicates how [`Offer::metadata`] may be set.
192 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
193 pub trait MetadataStrategy {}
195 /// [`Offer::metadata`] may be explicitly set or left empty.
197 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
198 pub struct ExplicitMetadata {}
200 /// [`Offer::metadata`] will be derived.
202 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
203 pub struct DerivedMetadata {}
205 impl MetadataStrategy for ExplicitMetadata {}
207 impl MetadataStrategy for DerivedMetadata {}
209 macro_rules! offer_explicit_metadata_builder_methods { (
210 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
212 /// Creates a new builder for an offer setting an empty [`Offer::description`] and using the
213 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
214 /// while the offer is valid.
216 /// Use a different pubkey per offer to avoid correlating offers.
220 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
221 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
223 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
224 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
225 pub fn new(signing_pubkey: PublicKey) -> Self {
227 offer: OfferContents {
228 chains: None, metadata: None, amount: None, description: String::new(),
229 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
230 supported_quantity: Quantity::One, signing_pubkey: Some(signing_pubkey),
232 metadata_strategy: core::marker::PhantomData,
237 /// Sets the [`Offer::metadata`] to the given bytes.
239 /// Successive calls to this method will override the previous setting.
240 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
241 $self.offer.metadata = Some(Metadata::Bytes(metadata));
246 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
247 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
248 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
249 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
250 /// provided `node_id` is used for the signing pubkey.
252 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
253 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
256 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
257 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
258 pub fn deriving_signing_pubkey<ES: Deref>(
259 node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
260 secp_ctx: &'a Secp256k1<$secp_context>
261 ) -> Self where ES::Target: EntropySource {
262 let nonce = Nonce::from_entropy_source(entropy_source);
263 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
264 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
266 offer: OfferContents {
267 chains: None, metadata: Some(metadata), amount: None, description: String::new(),
268 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
269 supported_quantity: Quantity::One, signing_pubkey: Some(node_id),
271 metadata_strategy: core::marker::PhantomData,
272 secp_ctx: Some(secp_ctx),
277 macro_rules! offer_builder_methods { (
278 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
280 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
281 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
283 /// See [`Offer::chains`] on how this relates to the payment currency.
285 /// Successive calls to this method will add another chain hash.
286 pub fn chain($self: $self_type, network: Network) -> $return_type {
287 $self.chain_hash(ChainHash::using_genesis_block(network))
290 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
291 /// [`Network::Bitcoin`] is assumed to be the only one supported.
293 /// See [`Offer::chains`] on how this relates to the payment currency.
295 /// Successive calls to this method will add another chain hash.
296 pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
297 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
298 if !chains.contains(&chain) {
305 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
307 /// Successive calls to this method will override the previous setting.
308 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
309 $self.amount(Amount::Bitcoin { amount_msats })
312 /// Sets the [`Offer::amount`].
314 /// Successive calls to this method will override the previous setting.
315 pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
316 $self.offer.amount = Some(amount);
320 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
321 /// already passed is valid and can be checked for using [`Offer::is_expired`].
323 /// Successive calls to this method will override the previous setting.
324 pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
325 $self.offer.absolute_expiry = Some(absolute_expiry);
329 /// Sets the [`Offer::description`].
331 /// Successive calls to this method will override the previous setting.
332 pub fn description($($self_mut)* $self: $self_type, description: String) -> $return_type {
333 $self.offer.description = description;
337 /// Sets the [`Offer::issuer`].
339 /// Successive calls to this method will override the previous setting.
340 pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
341 $self.offer.issuer = Some(issuer);
345 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
346 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
348 /// Successive calls to this method will add another blinded path. Caller is responsible for not
349 /// adding duplicate paths.
350 pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
351 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
355 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
356 /// [`Quantity::One`].
358 /// Successive calls to this method will override the previous setting.
359 pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
360 $self.offer.supported_quantity = quantity;
364 /// Builds an [`Offer`] from the builder's settings.
365 pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
366 match $self.offer.amount {
367 Some(Amount::Bitcoin { amount_msats }) => {
368 if amount_msats > MAX_VALUE_MSAT {
369 return Err(Bolt12SemanticError::InvalidAmount);
372 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
376 if let Some(chains) = &$self.offer.chains {
377 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
378 $self.offer.chains = None;
382 Ok($self.build_without_checks())
385 fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
386 // Create the metadata for stateless verification of an InvoiceRequest.
387 if let Some(mut metadata) = $self.offer.metadata.take() {
388 if metadata.has_derivation_material() {
389 if $self.offer.paths.is_none() {
390 metadata = metadata.without_keys();
393 let mut tlv_stream = $self.offer.as_tlv_stream();
394 debug_assert_eq!(tlv_stream.metadata, None);
395 tlv_stream.metadata = None;
396 if metadata.derives_recipient_keys() {
397 tlv_stream.node_id = None;
400 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
401 metadata = derived_metadata;
402 if let Some(keys) = keys {
403 $self.offer.signing_pubkey = Some(keys.public_key());
407 $self.offer.metadata = Some(metadata);
410 let mut bytes = Vec::new();
411 $self.offer.write(&mut bytes).unwrap();
413 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
417 #[cfg(not(c_bindings))]
418 contents: $self.offer,
420 contents: $self.offer.clone(),
427 macro_rules! offer_builder_test_methods { (
428 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
430 #[cfg_attr(c_bindings, allow(dead_code))]
431 fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
432 $self.offer.features = features;
436 #[cfg_attr(c_bindings, allow(dead_code))]
437 pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
438 $self.offer.chains = None;
442 #[cfg_attr(c_bindings, allow(dead_code))]
443 pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
444 $self.offer.paths = None;
448 #[cfg_attr(c_bindings, allow(dead_code))]
449 pub(crate) fn clear_signing_pubkey($($self_mut)* $self: $self_type) -> $return_type {
450 $self.offer.signing_pubkey = None;
454 #[cfg_attr(c_bindings, allow(dead_code))]
455 pub(super) fn build_unchecked($self: $self_type) -> Offer {
456 $self.build_without_checks()
460 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
461 offer_builder_methods!(self, Self, Self, self, mut);
464 offer_builder_test_methods!(self, Self, Self, self, mut);
467 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
468 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
471 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
472 offer_derived_metadata_builder_methods!(T);
475 #[cfg(all(c_bindings, not(test)))]
476 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
477 offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
478 offer_builder_methods!(self, &mut Self, (), ());
481 #[cfg(all(c_bindings, test))]
482 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
483 offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
484 offer_builder_methods!(self, &mut Self, &mut Self, self);
485 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
488 #[cfg(all(c_bindings, not(test)))]
489 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
490 offer_derived_metadata_builder_methods!(secp256k1::All);
491 offer_builder_methods!(self, &mut Self, (), ());
494 #[cfg(all(c_bindings, test))]
495 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
496 offer_derived_metadata_builder_methods!(secp256k1::All);
497 offer_builder_methods!(self, &mut Self, &mut Self, self);
498 offer_builder_test_methods!(self, &mut Self, &mut Self, self);
502 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
503 for OfferWithDerivedMetadataBuilder<'a> {
504 fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
505 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
507 Self { offer, metadata_strategy, secp_ctx }
512 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
513 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
514 fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
515 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
517 Self { offer, metadata_strategy, secp_ctx }
521 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
523 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
524 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
525 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
527 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
530 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
532 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
533 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
534 #[derive(Clone, Debug)]
536 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
538 pub(super) bytes: Vec<u8>,
539 pub(super) contents: OfferContents,
543 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
544 /// [`Bolt12Invoice`].
546 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
547 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
548 #[derive(Clone, Debug)]
549 #[cfg_attr(test, derive(PartialEq))]
550 pub(super) struct OfferContents {
551 chains: Option<Vec<ChainHash>>,
552 metadata: Option<Metadata>,
553 amount: Option<Amount>,
555 features: OfferFeatures,
556 absolute_expiry: Option<Duration>,
557 issuer: Option<String>,
558 paths: Option<Vec<BlindedPath>>,
559 supported_quantity: Quantity,
560 signing_pubkey: Option<PublicKey>,
563 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
564 // TODO: Return a slice once ChainHash has constants.
565 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
566 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
567 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
568 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
569 /// for the selected chain.
570 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
574 // TODO: Link to corresponding method in `InvoiceRequest`.
575 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
576 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
577 pub fn metadata(&$self) -> Option<&Vec<u8>> {
581 /// The minimum amount required for a successful payment of a single item.
582 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
586 /// A complete description of the purpose of the payment. Intended to be displayed to the user
587 /// but with the caveat that it has not been verified in any way.
588 pub fn description(&$self) -> $crate::util::string::PrintableString {
589 $contents.description()
592 /// Features pertaining to the offer.
593 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
594 &$contents.features()
597 /// Duration since the Unix epoch when an invoice should no longer be requested.
599 /// If `None`, the offer does not expire.
600 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
601 $contents.absolute_expiry()
604 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
605 /// displayed to the user but with the caveat that it has not been verified in any way.
606 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
610 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
611 /// recipient privacy by obfuscating its node id.
612 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
616 /// The quantity of items supported.
617 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
618 $contents.supported_quantity()
621 /// The public key used by the recipient to sign invoices.
622 pub fn signing_pubkey(&$self) -> Option<bitcoin::secp256k1::PublicKey> {
623 $contents.signing_pubkey()
628 offer_accessors!(self, self.contents);
630 /// Returns the id of the offer.
631 pub fn id(&self) -> OfferId {
635 pub(super) fn implied_chain(&self) -> ChainHash {
636 self.contents.implied_chain()
639 /// Returns whether the given chain is supported by the offer.
640 pub fn supports_chain(&self, chain: ChainHash) -> bool {
641 self.contents.supports_chain(chain)
644 /// Whether the offer has expired.
645 #[cfg(feature = "std")]
646 pub fn is_expired(&self) -> bool {
647 self.contents.is_expired()
650 /// Whether the offer has expired given the duration since the Unix epoch.
651 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
652 self.contents.is_expired_no_std(duration_since_epoch)
655 /// Returns whether the given quantity is valid for the offer.
656 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
657 self.contents.is_valid_quantity(quantity)
660 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
662 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
663 pub fn expects_quantity(&self) -> bool {
664 self.contents.expects_quantity()
668 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
669 /// Similar to [`Offer::request_invoice`] except it:
670 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
672 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
673 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
674 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
675 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
676 /// be used when sending the payment for the requested invoice.
678 /// Useful to protect the sender's privacy.
680 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
681 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
682 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
683 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
684 pub fn request_invoice_deriving_payer_id<
686 #[cfg(not(c_bindings))]
687 T: secp256k1::Signing
689 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
690 #[cfg(not(c_bindings))]
691 secp_ctx: &'b Secp256k1<T>,
693 secp_ctx: &'b Secp256k1<secp256k1::All>,
694 payment_id: PaymentId
695 ) -> Result<$builder, Bolt12SemanticError>
697 ES::Target: EntropySource,
699 if $self.offer_features().requires_unknown_bits() {
700 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
703 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
707 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
708 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
709 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
711 /// Useful for recurring payments using the same `payer_id` with different invoices.
713 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
714 pub fn request_invoice_deriving_metadata<ES: Deref>(
715 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
716 payment_id: PaymentId
717 ) -> Result<$builder, Bolt12SemanticError>
719 ES::Target: EntropySource,
721 if $self.offer_features().requires_unknown_bits() {
722 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
725 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
728 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
729 /// which will be reflected in the `Bolt12Invoice` response.
731 /// The `metadata` is useful for including information about the derivation of `payer_id` such
732 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
733 /// hashing in the signature calculation.
735 /// This should not leak any information such as by using a simple BIP-32 derivation path.
736 /// Otherwise, payments may be correlated.
738 /// Errors if the offer contains unknown required features.
740 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
741 pub fn request_invoice(
742 &$self, metadata: Vec<u8>, payer_id: PublicKey
743 ) -> Result<$builder, Bolt12SemanticError> {
744 if $self.offer_features().requires_unknown_bits() {
745 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
748 Ok(<$builder>::new($self, metadata, payer_id))
752 #[cfg(not(c_bindings))]
754 request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
755 request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
760 request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
761 request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
766 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
767 self.contents.as_tlv_stream()
771 impl AsRef<[u8]> for Offer {
772 fn as_ref(&self) -> &[u8] {
777 impl PartialEq for Offer {
778 fn eq(&self, other: &Self) -> bool {
779 self.bytes.eq(&other.bytes)
785 impl Hash for Offer {
786 fn hash<H: Hasher>(&self, state: &mut H) {
787 self.bytes.hash(state);
792 pub fn chains(&self) -> Vec<ChainHash> {
793 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
796 pub fn implied_chain(&self) -> ChainHash {
797 ChainHash::using_genesis_block(Network::Bitcoin)
800 pub fn supports_chain(&self, chain: ChainHash) -> bool {
801 self.chains().contains(&chain)
804 pub fn metadata(&self) -> Option<&Vec<u8>> {
805 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
808 pub fn amount(&self) -> Option<&Amount> {
812 pub fn description(&self) -> PrintableString {
813 PrintableString(&self.description)
816 pub fn features(&self) -> &OfferFeatures {
820 pub fn absolute_expiry(&self) -> Option<Duration> {
824 #[cfg(feature = "std")]
825 pub(super) fn is_expired(&self) -> bool {
826 SystemTime::UNIX_EPOCH
828 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
832 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
834 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
838 pub fn issuer(&self) -> Option<PrintableString> {
839 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
842 pub fn paths(&self) -> &[BlindedPath] {
843 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
846 pub(super) fn check_amount_msats_for_quantity(
847 &self, amount_msats: Option<u64>, quantity: Option<u64>
848 ) -> Result<(), Bolt12SemanticError> {
849 let offer_amount_msats = match self.amount {
851 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
852 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
855 if !self.expects_quantity() || quantity.is_some() {
856 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
857 .ok_or(Bolt12SemanticError::InvalidAmount)?;
858 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
860 if amount_msats < expected_amount_msats {
861 return Err(Bolt12SemanticError::InsufficientAmount);
864 if amount_msats > MAX_VALUE_MSAT {
865 return Err(Bolt12SemanticError::InvalidAmount);
872 pub fn supported_quantity(&self) -> Quantity {
873 self.supported_quantity
876 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
877 let expects_quantity = self.expects_quantity();
879 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
880 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
881 Some(quantity) if !self.is_valid_quantity(quantity) => {
882 Err(Bolt12SemanticError::InvalidQuantity)
888 fn is_valid_quantity(&self, quantity: u64) -> bool {
889 match self.supported_quantity {
890 Quantity::Bounded(n) => quantity <= n.get(),
891 Quantity::Unbounded => quantity > 0,
892 Quantity::One => quantity == 1,
896 fn expects_quantity(&self) -> bool {
897 match self.supported_quantity {
898 Quantity::Bounded(_) => true,
899 Quantity::Unbounded => true,
900 Quantity::One => false,
904 pub(super) fn signing_pubkey(&self) -> Option<PublicKey> {
908 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
909 pub(super) fn verify<T: secp256k1::Signing>(
910 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
911 ) -> Result<(OfferId, Option<KeyPair>), ()> {
912 match self.metadata() {
914 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
915 match record.r#type {
916 OFFER_METADATA_TYPE => false,
917 OFFER_NODE_ID_TYPE => {
918 !self.metadata.as_ref().unwrap().derives_recipient_keys()
923 let signing_pubkey = match self.signing_pubkey() {
924 Some(signing_pubkey) => signing_pubkey,
925 None => return Err(()),
927 let keys = signer::verify_recipient_metadata(
928 metadata, key, IV_BYTES, signing_pubkey, tlv_stream, secp_ctx
931 let offer_id = OfferId::from_valid_invreq_tlv_stream(bytes);
939 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
940 let (currency, amount) = match &self.amount {
941 None => (None, None),
942 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
943 Some(Amount::Currency { iso4217_code, amount }) => (
944 Some(iso4217_code), Some(*amount)
949 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
953 chains: self.chains.as_ref(),
954 metadata: self.metadata(),
957 description: Some(&self.description),
959 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
960 paths: self.paths.as_ref(),
961 issuer: self.issuer.as_ref(),
962 quantity_max: self.supported_quantity.to_tlv_record(),
963 node_id: self.signing_pubkey.as_ref(),
968 impl Writeable for Offer {
969 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
970 WithoutLength(&self.bytes).write(writer)
974 impl Writeable for OfferContents {
975 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
976 self.as_tlv_stream().write(writer)
980 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
981 /// another currency.
982 #[derive(Clone, Debug, PartialEq)]
984 /// An amount of bitcoin.
986 /// The amount in millisatoshi.
989 /// An amount of currency specified using ISO 4712.
991 /// The currency that the amount is denominated in.
992 iso4217_code: CurrencyCode,
993 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
998 /// An ISO 4712 three-letter currency code (e.g., USD).
999 pub type CurrencyCode = [u8; 3];
1001 /// Quantity of items supported by an [`Offer`].
1002 #[derive(Clone, Copy, Debug, PartialEq)]
1004 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
1005 /// but is limited (e.g., because of per customer or inventory limits).
1007 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
1009 Bounded(NonZeroU64),
1010 /// One or more items. Use when more than one item can be requested without any limit.
1012 /// Only one item. Use when only a single item can be requested.
1017 fn to_tlv_record(&self) -> Option<u64> {
1019 Quantity::Bounded(n) => Some(n.get()),
1020 Quantity::Unbounded => Some(0),
1021 Quantity::One => None,
1026 /// Valid type range for offer TLV records.
1027 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
1029 /// TLV record type for [`Offer::metadata`].
1030 const OFFER_METADATA_TYPE: u64 = 4;
1032 /// TLV record type for [`Offer::signing_pubkey`].
1033 const OFFER_NODE_ID_TYPE: u64 = 22;
1035 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
1036 (2, chains: (Vec<ChainHash>, WithoutLength)),
1037 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
1038 (6, currency: CurrencyCode),
1039 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
1040 (10, description: (String, WithoutLength)),
1041 (12, features: (OfferFeatures, WithoutLength)),
1042 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
1043 (16, paths: (Vec<BlindedPath>, WithoutLength)),
1044 (18, issuer: (String, WithoutLength)),
1045 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
1046 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
1049 impl Bech32Encode for Offer {
1050 const BECH32_HRP: &'static str = "lno";
1053 impl FromStr for Offer {
1054 type Err = Bolt12ParseError;
1056 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
1057 Self::from_bech32_str(s)
1061 impl TryFrom<Vec<u8>> for Offer {
1062 type Error = Bolt12ParseError;
1064 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1065 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1066 let ParsedMessage { bytes, tlv_stream } = offer;
1067 let contents = OfferContents::try_from(tlv_stream)?;
1068 let id = OfferId::from_valid_offer_tlv_stream(&bytes);
1070 Ok(Offer { bytes, contents, id })
1074 impl TryFrom<OfferTlvStream> for OfferContents {
1075 type Error = Bolt12SemanticError;
1077 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1078 let OfferTlvStream {
1079 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1080 issuer, quantity_max, node_id,
1083 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1085 let amount = match (currency, amount) {
1086 (None, None) => None,
1087 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1088 return Err(Bolt12SemanticError::InvalidAmount);
1090 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1091 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1092 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1095 let description = match description {
1096 None => return Err(Bolt12SemanticError::MissingDescription),
1097 Some(description) => description,
1100 let features = features.unwrap_or_else(OfferFeatures::empty);
1102 let absolute_expiry = absolute_expiry
1103 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1105 let supported_quantity = match quantity_max {
1106 None => Quantity::One,
1107 Some(0) => Quantity::Unbounded,
1108 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1111 let (signing_pubkey, paths) = match (node_id, paths) {
1112 (None, None) => return Err(Bolt12SemanticError::MissingSigningPubkey),
1113 (_, Some(paths)) if paths.is_empty() => return Err(Bolt12SemanticError::MissingPaths),
1114 (node_id, paths) => (node_id, paths),
1118 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1119 supported_quantity, signing_pubkey,
1124 impl core::fmt::Display for Offer {
1125 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1126 self.fmt_bech32_str(f)
1132 use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1133 #[cfg(not(c_bindings))]
1135 super::OfferBuilder,
1139 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1142 use bitcoin::blockdata::constants::ChainHash;
1143 use bitcoin::network::constants::Network;
1144 use bitcoin::secp256k1::Secp256k1;
1145 use core::num::NonZeroU64;
1146 use core::time::Duration;
1147 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
1148 use crate::sign::KeyMaterial;
1149 use crate::ln::features::OfferFeatures;
1150 use crate::ln::inbound_payment::ExpandedKey;
1151 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1152 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1153 use crate::offers::test_utils::*;
1154 use crate::util::ser::{BigSize, Writeable};
1155 use crate::util::string::PrintableString;
1158 fn builds_offer_with_defaults() {
1159 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1161 let mut buffer = Vec::new();
1162 offer.write(&mut buffer).unwrap();
1164 assert_eq!(offer.bytes, buffer.as_slice());
1165 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1166 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1167 assert_eq!(offer.metadata(), None);
1168 assert_eq!(offer.amount(), None);
1169 assert_eq!(offer.description(), PrintableString(""));
1170 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1171 assert_eq!(offer.absolute_expiry(), None);
1172 #[cfg(feature = "std")]
1173 assert!(!offer.is_expired());
1174 assert_eq!(offer.paths(), &[]);
1175 assert_eq!(offer.issuer(), None);
1176 assert_eq!(offer.supported_quantity(), Quantity::One);
1177 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1180 offer.as_tlv_stream(),
1186 description: Some(&String::from("")),
1188 absolute_expiry: None,
1192 node_id: Some(&pubkey(42)),
1196 if let Err(e) = Offer::try_from(buffer) {
1197 panic!("error parsing offer: {:?}", e);
1202 fn builds_offer_with_chains() {
1203 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1204 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1206 let offer = OfferBuilder::new(pubkey(42))
1207 .chain(Network::Bitcoin)
1210 assert!(offer.supports_chain(mainnet));
1211 assert_eq!(offer.chains(), vec![mainnet]);
1212 assert_eq!(offer.as_tlv_stream().chains, None);
1214 let offer = OfferBuilder::new(pubkey(42))
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(pubkey(42))
1223 .chain(Network::Testnet)
1224 .chain(Network::Testnet)
1227 assert!(offer.supports_chain(testnet));
1228 assert_eq!(offer.chains(), vec![testnet]);
1229 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1231 let offer = OfferBuilder::new(pubkey(42))
1232 .chain(Network::Bitcoin)
1233 .chain(Network::Testnet)
1236 assert!(offer.supports_chain(mainnet));
1237 assert!(offer.supports_chain(testnet));
1238 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1239 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1243 fn builds_offer_with_metadata() {
1244 let offer = OfferBuilder::new(pubkey(42))
1245 .metadata(vec![42; 32]).unwrap()
1248 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1249 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1251 let offer = OfferBuilder::new(pubkey(42))
1252 .metadata(vec![42; 32]).unwrap()
1253 .metadata(vec![43; 32]).unwrap()
1256 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1257 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1261 fn builds_offer_with_metadata_derived() {
1262 let node_id = recipient_pubkey();
1263 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1264 let entropy = FixedEntropy {};
1265 let secp_ctx = Secp256k1::new();
1268 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1269 let offer = OfferBuilder
1270 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1273 assert_eq!(offer.signing_pubkey(), Some(node_id));
1275 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1277 .sign(payer_sign).unwrap();
1278 match invoice_request.verify(&expanded_key, &secp_ctx) {
1279 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1280 Err(_) => panic!("unexpected error"),
1283 // Fails verification with altered offer field
1284 let mut tlv_stream = offer.as_tlv_stream();
1285 tlv_stream.amount = Some(100);
1287 let mut encoded_offer = Vec::new();
1288 tlv_stream.write(&mut encoded_offer).unwrap();
1290 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1291 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1293 .sign(payer_sign).unwrap();
1294 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1296 // Fails verification with altered metadata
1297 let mut tlv_stream = offer.as_tlv_stream();
1298 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1299 tlv_stream.metadata = Some(&metadata);
1301 let mut encoded_offer = Vec::new();
1302 tlv_stream.write(&mut encoded_offer).unwrap();
1304 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1305 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1307 .sign(payer_sign).unwrap();
1308 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1312 fn builds_offer_with_derived_signing_pubkey() {
1313 let node_id = recipient_pubkey();
1314 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1315 let entropy = FixedEntropy {};
1316 let secp_ctx = Secp256k1::new();
1318 let blinded_path = BlindedPath {
1319 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1320 blinding_point: pubkey(41),
1322 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1323 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1328 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1329 let offer = OfferBuilder
1330 ::deriving_signing_pubkey(node_id, &expanded_key, &entropy, &secp_ctx)
1334 assert_ne!(offer.signing_pubkey(), Some(node_id));
1336 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1338 .sign(payer_sign).unwrap();
1339 match invoice_request.verify(&expanded_key, &secp_ctx) {
1340 Ok(invoice_request) => assert_eq!(invoice_request.offer_id, offer.id()),
1341 Err(_) => panic!("unexpected error"),
1344 // Fails verification with altered offer field
1345 let mut tlv_stream = offer.as_tlv_stream();
1346 tlv_stream.amount = Some(100);
1348 let mut encoded_offer = Vec::new();
1349 tlv_stream.write(&mut encoded_offer).unwrap();
1351 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1352 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1354 .sign(payer_sign).unwrap();
1355 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1357 // Fails verification with altered signing pubkey
1358 let mut tlv_stream = offer.as_tlv_stream();
1359 let signing_pubkey = pubkey(1);
1360 tlv_stream.node_id = Some(&signing_pubkey);
1362 let mut encoded_offer = Vec::new();
1363 tlv_stream.write(&mut encoded_offer).unwrap();
1365 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1366 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1368 .sign(payer_sign).unwrap();
1369 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1373 fn builds_offer_with_amount() {
1374 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1375 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1377 let offer = OfferBuilder::new(pubkey(42))
1381 let tlv_stream = offer.as_tlv_stream();
1382 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1383 assert_eq!(tlv_stream.amount, Some(1000));
1384 assert_eq!(tlv_stream.currency, None);
1386 #[cfg(not(c_bindings))]
1387 let builder = OfferBuilder::new(pubkey(42))
1388 .amount(currency_amount.clone());
1390 let mut builder = OfferBuilder::new(pubkey(42));
1392 builder.amount(currency_amount.clone());
1393 let tlv_stream = builder.offer.as_tlv_stream();
1394 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1395 assert_eq!(tlv_stream.amount, Some(10));
1396 assert_eq!(tlv_stream.currency, Some(b"USD"));
1397 match builder.build() {
1398 Ok(_) => panic!("expected error"),
1399 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1402 let offer = OfferBuilder::new(pubkey(42))
1403 .amount(currency_amount.clone())
1404 .amount(bitcoin_amount.clone())
1407 let tlv_stream = offer.as_tlv_stream();
1408 assert_eq!(tlv_stream.amount, Some(1000));
1409 assert_eq!(tlv_stream.currency, None);
1411 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1412 match OfferBuilder::new(pubkey(42)).amount(invalid_amount).build() {
1413 Ok(_) => panic!("expected error"),
1414 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1419 fn builds_offer_with_description() {
1420 let offer = OfferBuilder::new(pubkey(42))
1421 .description("foo".into())
1424 assert_eq!(offer.description(), PrintableString("foo"));
1425 assert_eq!(offer.as_tlv_stream().description, Some(&String::from("foo")));
1427 let offer = OfferBuilder::new(pubkey(42))
1428 .description("foo".into())
1429 .description("bar".into())
1432 assert_eq!(offer.description(), PrintableString("bar"));
1433 assert_eq!(offer.as_tlv_stream().description, Some(&String::from("bar")));
1437 fn builds_offer_with_features() {
1438 let offer = OfferBuilder::new(pubkey(42))
1439 .features_unchecked(OfferFeatures::unknown())
1442 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1443 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1445 let offer = OfferBuilder::new(pubkey(42))
1446 .features_unchecked(OfferFeatures::unknown())
1447 .features_unchecked(OfferFeatures::empty())
1450 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1451 assert_eq!(offer.as_tlv_stream().features, None);
1455 fn builds_offer_with_absolute_expiry() {
1456 let future_expiry = Duration::from_secs(u64::max_value());
1457 let past_expiry = Duration::from_secs(0);
1458 let now = future_expiry - Duration::from_secs(1_000);
1460 let offer = OfferBuilder::new(pubkey(42))
1461 .absolute_expiry(future_expiry)
1464 #[cfg(feature = "std")]
1465 assert!(!offer.is_expired());
1466 assert!(!offer.is_expired_no_std(now));
1467 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1468 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1470 let offer = OfferBuilder::new(pubkey(42))
1471 .absolute_expiry(future_expiry)
1472 .absolute_expiry(past_expiry)
1475 #[cfg(feature = "std")]
1476 assert!(offer.is_expired());
1477 assert!(offer.is_expired_no_std(now));
1478 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1479 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1483 fn builds_offer_with_paths() {
1486 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1487 blinding_point: pubkey(41),
1489 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1490 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1494 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1495 blinding_point: pubkey(41),
1497 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1498 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1503 let offer = OfferBuilder::new(pubkey(42))
1504 .path(paths[0].clone())
1505 .path(paths[1].clone())
1508 let tlv_stream = offer.as_tlv_stream();
1509 assert_eq!(offer.paths(), paths.as_slice());
1510 assert_eq!(offer.signing_pubkey(), Some(pubkey(42)));
1511 assert_ne!(pubkey(42), pubkey(44));
1512 assert_eq!(tlv_stream.paths, Some(&paths));
1513 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1517 fn builds_offer_with_issuer() {
1518 let offer = OfferBuilder::new(pubkey(42))
1519 .issuer("foo".into())
1522 assert_eq!(offer.issuer(), Some(PrintableString("foo")));
1523 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("foo")));
1525 let offer = OfferBuilder::new(pubkey(42))
1526 .issuer("foo".into())
1527 .issuer("bar".into())
1530 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1531 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1535 fn builds_offer_with_supported_quantity() {
1536 let one = NonZeroU64::new(1).unwrap();
1537 let ten = NonZeroU64::new(10).unwrap();
1539 let offer = OfferBuilder::new(pubkey(42))
1540 .supported_quantity(Quantity::One)
1543 let tlv_stream = offer.as_tlv_stream();
1544 assert_eq!(offer.supported_quantity(), Quantity::One);
1545 assert_eq!(tlv_stream.quantity_max, None);
1547 let offer = OfferBuilder::new(pubkey(42))
1548 .supported_quantity(Quantity::Unbounded)
1551 let tlv_stream = offer.as_tlv_stream();
1552 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1553 assert_eq!(tlv_stream.quantity_max, Some(0));
1555 let offer = OfferBuilder::new(pubkey(42))
1556 .supported_quantity(Quantity::Bounded(ten))
1559 let tlv_stream = offer.as_tlv_stream();
1560 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1561 assert_eq!(tlv_stream.quantity_max, Some(10));
1563 let offer = OfferBuilder::new(pubkey(42))
1564 .supported_quantity(Quantity::Bounded(one))
1567 let tlv_stream = offer.as_tlv_stream();
1568 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1569 assert_eq!(tlv_stream.quantity_max, Some(1));
1571 let offer = OfferBuilder::new(pubkey(42))
1572 .supported_quantity(Quantity::Bounded(ten))
1573 .supported_quantity(Quantity::One)
1576 let tlv_stream = offer.as_tlv_stream();
1577 assert_eq!(offer.supported_quantity(), Quantity::One);
1578 assert_eq!(tlv_stream.quantity_max, None);
1582 fn fails_requesting_invoice_with_unknown_required_features() {
1583 match OfferBuilder::new(pubkey(42))
1584 .features_unchecked(OfferFeatures::unknown())
1586 .request_invoice(vec![1; 32], pubkey(43))
1588 Ok(_) => panic!("expected error"),
1589 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1594 fn parses_offer_with_chains() {
1595 let offer = OfferBuilder::new(pubkey(42))
1596 .chain(Network::Bitcoin)
1597 .chain(Network::Testnet)
1600 if let Err(e) = offer.to_string().parse::<Offer>() {
1601 panic!("error parsing offer: {:?}", e);
1606 fn parses_offer_with_amount() {
1607 let offer = OfferBuilder::new(pubkey(42))
1608 .amount(Amount::Bitcoin { amount_msats: 1000 })
1611 if let Err(e) = offer.to_string().parse::<Offer>() {
1612 panic!("error parsing offer: {:?}", e);
1615 let mut tlv_stream = offer.as_tlv_stream();
1616 tlv_stream.amount = Some(1000);
1617 tlv_stream.currency = Some(b"USD");
1619 let mut encoded_offer = Vec::new();
1620 tlv_stream.write(&mut encoded_offer).unwrap();
1622 if let Err(e) = Offer::try_from(encoded_offer) {
1623 panic!("error parsing offer: {:?}", e);
1626 let mut tlv_stream = offer.as_tlv_stream();
1627 tlv_stream.amount = None;
1628 tlv_stream.currency = Some(b"USD");
1630 let mut encoded_offer = Vec::new();
1631 tlv_stream.write(&mut encoded_offer).unwrap();
1633 match Offer::try_from(encoded_offer) {
1634 Ok(_) => panic!("expected error"),
1635 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1638 let mut tlv_stream = offer.as_tlv_stream();
1639 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1640 tlv_stream.currency = None;
1642 let mut encoded_offer = Vec::new();
1643 tlv_stream.write(&mut encoded_offer).unwrap();
1645 match Offer::try_from(encoded_offer) {
1646 Ok(_) => panic!("expected error"),
1647 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1652 fn parses_offer_with_description() {
1653 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1654 if let Err(e) = offer.to_string().parse::<Offer>() {
1655 panic!("error parsing offer: {:?}", e);
1658 let mut tlv_stream = offer.as_tlv_stream();
1659 tlv_stream.description = None;
1661 let mut encoded_offer = Vec::new();
1662 tlv_stream.write(&mut encoded_offer).unwrap();
1664 match Offer::try_from(encoded_offer) {
1665 Ok(_) => panic!("expected error"),
1667 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1673 fn parses_offer_with_paths() {
1674 let offer = OfferBuilder::new(pubkey(42))
1676 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1677 blinding_point: pubkey(41),
1679 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1680 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1684 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1685 blinding_point: pubkey(41),
1687 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1688 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1693 if let Err(e) = offer.to_string().parse::<Offer>() {
1694 panic!("error parsing offer: {:?}", e);
1697 let offer = OfferBuilder::new(pubkey(42))
1699 introduction_node: IntroductionNode::NodeId(pubkey(40)),
1700 blinding_point: pubkey(41),
1702 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1703 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1706 .clear_signing_pubkey()
1709 if let Err(e) = offer.to_string().parse::<Offer>() {
1710 panic!("error parsing offer: {:?}", e);
1713 let mut builder = OfferBuilder::new(pubkey(42));
1714 builder.offer.paths = Some(vec![]);
1716 let offer = builder.build().unwrap();
1717 match offer.to_string().parse::<Offer>() {
1718 Ok(_) => panic!("expected error"),
1720 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingPaths));
1726 fn parses_offer_with_quantity() {
1727 let offer = OfferBuilder::new(pubkey(42))
1728 .supported_quantity(Quantity::One)
1731 if let Err(e) = offer.to_string().parse::<Offer>() {
1732 panic!("error parsing offer: {:?}", e);
1735 let offer = OfferBuilder::new(pubkey(42))
1736 .supported_quantity(Quantity::Unbounded)
1739 if let Err(e) = offer.to_string().parse::<Offer>() {
1740 panic!("error parsing offer: {:?}", e);
1743 let offer = OfferBuilder::new(pubkey(42))
1744 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1747 if let Err(e) = offer.to_string().parse::<Offer>() {
1748 panic!("error parsing offer: {:?}", e);
1751 let offer = OfferBuilder::new(pubkey(42))
1752 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1755 if let Err(e) = offer.to_string().parse::<Offer>() {
1756 panic!("error parsing offer: {:?}", e);
1761 fn parses_offer_with_node_id() {
1762 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1763 if let Err(e) = offer.to_string().parse::<Offer>() {
1764 panic!("error parsing offer: {:?}", e);
1767 let mut tlv_stream = offer.as_tlv_stream();
1768 tlv_stream.node_id = None;
1770 let mut encoded_offer = Vec::new();
1771 tlv_stream.write(&mut encoded_offer).unwrap();
1773 match Offer::try_from(encoded_offer) {
1774 Ok(_) => panic!("expected error"),
1776 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1782 fn fails_parsing_offer_with_extra_tlv_records() {
1783 let offer = OfferBuilder::new(pubkey(42)).build().unwrap();
1785 let mut encoded_offer = Vec::new();
1786 offer.write(&mut encoded_offer).unwrap();
1787 BigSize(80).write(&mut encoded_offer).unwrap();
1788 BigSize(32).write(&mut encoded_offer).unwrap();
1789 [42u8; 32].write(&mut encoded_offer).unwrap();
1791 match Offer::try_from(encoded_offer) {
1792 Ok(_) => panic!("expected error"),
1793 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1800 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1801 use crate::ln::msgs::DecodeError;
1804 fn parses_bech32_encoded_offers() {
1806 // Minimal bolt12 offer
1807 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1810 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1812 // for bitcoin (redundant)
1813 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1815 // for bitcoin or liquidv1
1816 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1819 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1822 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1825 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1828 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1831 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1834 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1836 // with unlimited (or unknown) quantity
1837 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1839 // with single quantity (weird but valid)
1840 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1843 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1845 // with blinded path via Bob (0x424242...), blinding 020202...
1846 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1848 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1849 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1851 // unknown odd field
1852 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1854 for encoded_offer in &offers {
1855 if let Err(e) = encoded_offer.parse::<Offer>() {
1856 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1862 fn fails_parsing_bech32_encoded_offers() {
1863 // Malformed: fields out of order
1865 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1866 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1869 // Malformed: unknown even TLV type 78
1871 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1872 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1877 "lno1".parse::<Offer>(),
1878 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1881 // Malformed: truncated at type
1883 "lno1pg".parse::<Offer>(),
1884 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1887 // Malformed: truncated in length
1889 "lno1pt7s".parse::<Offer>(),
1890 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1893 // Malformed: truncated after length
1895 "lno1pgpq".parse::<Offer>(),
1896 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1899 // Malformed: truncated in description
1901 "lno1pgpyz".parse::<Offer>(),
1902 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1905 // Malformed: invalid offer_chains length
1907 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1908 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1911 // Malformed: truncated currency UTF-8
1913 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1914 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1917 // Malformed: invalid currency UTF-8
1919 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1920 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1923 // Malformed: truncated description UTF-8
1925 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1926 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1929 // Malformed: invalid description UTF-8
1931 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1932 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1935 // Malformed: truncated offer_paths
1937 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1938 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1941 // Malformed: zero num_hops in blinded_path
1943 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1944 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1947 // Malformed: truncated onionmsg_hop in blinded_path
1949 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1950 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1953 // Malformed: bad first_node_id in blinded_path
1955 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1956 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1959 // Malformed: bad blinding in blinded_path
1961 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1962 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1965 // Malformed: bad blinded_node_id in onionmsg_hop
1967 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1968 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1971 // Malformed: truncated issuer UTF-8
1973 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1974 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1977 // Malformed: invalid issuer UTF-8
1979 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1980 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1983 // Malformed: invalid offer_node_id
1985 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1986 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1989 // Contains type >= 80
1991 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1992 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1995 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1996 // Contains unknown feature 22
1998 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
2001 // Missing offer_description
2003 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
2004 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
2007 // Missing offer_node_id"
2009 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
2010 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),