1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Data structures and encoding for `offer` messages.
12 //! An [`Offer`] represents an "offer to be paid." It is typically constructed by a merchant and
13 //! published as a QR code to be scanned by a customer. The customer uses the offer to request an
14 //! invoice from the merchant to be paid.
19 //! extern crate bitcoin;
20 //! extern crate core;
21 //! extern crate lightning;
23 //! use core::convert::TryFrom;
24 //! use core::num::NonZeroU64;
25 //! use core::time::Duration;
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
29 //! use lightning::offers::parse::Bolt12ParseError;
30 //! use lightning::util::ser::{Readable, Writeable};
32 //! # use lightning::blinded_path::BlindedPath;
33 //! # #[cfg(feature = "std")]
34 //! # use std::time::SystemTime;
36 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
39 //! # #[cfg(feature = "std")]
40 //! # fn build() -> Result<(), Bolt12ParseError> {
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
43 //! let pubkey = PublicKey::from(keys);
45 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
46 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
47 //! .amount_msats(20_000)
48 //! .supported_quantity(Quantity::Unbounded)
49 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //! .issuer("Foo Bar".to_string())
51 //! .path(create_blinded_path())
52 //! .path(create_another_blinded_path())
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
79 use bitcoin::blockdata::constants::ChainHash;
80 use bitcoin::network::constants::Network;
81 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
82 use core::convert::TryFrom;
83 use core::num::NonZeroU64;
85 use core::str::FromStr;
86 use core::time::Duration;
87 use crate::sign::EntropySource;
89 use crate::blinded_path::BlindedPath;
90 use crate::ln::channelmanager::PaymentId;
91 use crate::ln::features::OfferFeatures;
92 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
93 use crate::ln::msgs::MAX_VALUE_MSAT;
94 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
95 use crate::offers::merkle::TlvStream;
96 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
97 use crate::offers::signer::{Metadata, MetadataMaterial, self};
98 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
99 use crate::util::string::PrintableString;
101 use crate::prelude::*;
103 #[cfg(feature = "std")]
104 use std::time::SystemTime;
106 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
108 /// Builds an [`Offer`] for the "offer to be paid" flow.
110 /// See [module-level documentation] for usage.
112 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
114 /// [module-level documentation]: self
115 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
116 offer: OfferContents,
117 metadata_strategy: core::marker::PhantomData<M>,
118 secp_ctx: Option<&'a Secp256k1<T>>,
121 /// Indicates how [`Offer::metadata`] may be set.
123 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
124 pub trait MetadataStrategy {}
126 /// [`Offer::metadata`] may be explicitly set or left empty.
128 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
129 pub struct ExplicitMetadata {}
131 /// [`Offer::metadata`] will be derived.
133 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
134 pub struct DerivedMetadata {}
136 impl MetadataStrategy for ExplicitMetadata {}
137 impl MetadataStrategy for DerivedMetadata {}
139 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
140 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
141 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
142 /// while the offer is valid.
144 /// Use a different pubkey per offer to avoid correlating offers.
148 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
149 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
151 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
152 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
153 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
155 offer: OfferContents {
156 chains: None, metadata: None, amount: None, description,
157 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
158 supported_quantity: Quantity::One, signing_pubkey,
160 metadata_strategy: core::marker::PhantomData,
165 /// Sets the [`Offer::metadata`] to the given bytes.
167 /// Successive calls to this method will override the previous setting.
168 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, Bolt12SemanticError> {
169 self.offer.metadata = Some(Metadata::Bytes(metadata));
174 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
175 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
176 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
177 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
178 /// provided `node_id` is used for the signing pubkey.
180 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
181 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
184 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
185 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
186 pub fn deriving_signing_pubkey<ES: Deref>(
187 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
188 secp_ctx: &'a Secp256k1<T>
189 ) -> Self where ES::Target: EntropySource {
190 let nonce = Nonce::from_entropy_source(entropy_source);
191 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
192 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
194 offer: OfferContents {
195 chains: None, metadata: Some(metadata), amount: None, description,
196 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
197 supported_quantity: Quantity::One, signing_pubkey: node_id,
199 metadata_strategy: core::marker::PhantomData,
200 secp_ctx: Some(secp_ctx),
205 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
206 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
207 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
209 /// See [`Offer::chains`] on how this relates to the payment currency.
211 /// Successive calls to this method will add another chain hash.
212 pub fn chain(self, network: Network) -> Self {
213 self.chain_hash(ChainHash::using_genesis_block(network))
216 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
217 /// [`Network::Bitcoin`] is assumed to be the only one supported.
219 /// See [`Offer::chains`] on how this relates to the payment currency.
221 /// Successive calls to this method will add another chain hash.
222 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Self {
223 let chains = self.offer.chains.get_or_insert_with(Vec::new);
224 if !chains.contains(&chain) {
231 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
233 /// Successive calls to this method will override the previous setting.
234 pub fn amount_msats(self, amount_msats: u64) -> Self {
235 self.amount(Amount::Bitcoin { amount_msats })
238 /// Sets the [`Offer::amount`].
240 /// Successive calls to this method will override the previous setting.
241 pub(super) fn amount(mut self, amount: Amount) -> Self {
242 self.offer.amount = Some(amount);
246 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
247 /// already passed is valid and can be checked for using [`Offer::is_expired`].
249 /// Successive calls to this method will override the previous setting.
250 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
251 self.offer.absolute_expiry = Some(absolute_expiry);
255 /// Sets the [`Offer::issuer`].
257 /// Successive calls to this method will override the previous setting.
258 pub fn issuer(mut self, issuer: String) -> Self {
259 self.offer.issuer = Some(issuer);
263 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
264 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
266 /// Successive calls to this method will add another blinded path. Caller is responsible for not
267 /// adding duplicate paths.
268 pub fn path(mut self, path: BlindedPath) -> Self {
269 self.offer.paths.get_or_insert_with(Vec::new).push(path);
273 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
274 /// [`Quantity::One`].
276 /// Successive calls to this method will override the previous setting.
277 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
278 self.offer.supported_quantity = quantity;
282 /// Builds an [`Offer`] from the builder's settings.
283 pub fn build(mut self) -> Result<Offer, Bolt12SemanticError> {
284 match self.offer.amount {
285 Some(Amount::Bitcoin { amount_msats }) => {
286 if amount_msats > MAX_VALUE_MSAT {
287 return Err(Bolt12SemanticError::InvalidAmount);
290 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
294 if let Some(chains) = &self.offer.chains {
295 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
296 self.offer.chains = None;
300 Ok(self.build_without_checks())
303 fn build_without_checks(mut self) -> Offer {
304 // Create the metadata for stateless verification of an InvoiceRequest.
305 if let Some(mut metadata) = self.offer.metadata.take() {
306 if metadata.has_derivation_material() {
307 if self.offer.paths.is_none() {
308 metadata = metadata.without_keys();
311 let mut tlv_stream = self.offer.as_tlv_stream();
312 debug_assert_eq!(tlv_stream.metadata, None);
313 tlv_stream.metadata = None;
314 if metadata.derives_recipient_keys() {
315 tlv_stream.node_id = None;
318 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
319 metadata = derived_metadata;
320 if let Some(keys) = keys {
321 self.offer.signing_pubkey = keys.public_key();
325 self.offer.metadata = Some(metadata);
328 let mut bytes = Vec::new();
329 self.offer.write(&mut bytes).unwrap();
331 Offer { bytes, contents: self.offer }
336 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
337 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
338 self.offer.features = features;
342 pub(crate) fn clear_paths(mut self) -> Self {
343 self.offer.paths = None;
347 pub(super) fn build_unchecked(self) -> Offer {
348 self.build_without_checks()
352 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
354 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
355 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
356 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
358 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
361 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
363 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
364 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
365 #[derive(Clone, Debug)]
366 #[cfg_attr(test, derive(PartialEq))]
368 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
370 pub(super) bytes: Vec<u8>,
371 pub(super) contents: OfferContents,
374 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
375 /// [`Bolt12Invoice`].
377 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
378 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
379 #[derive(Clone, Debug)]
380 #[cfg_attr(test, derive(PartialEq))]
381 pub(super) struct OfferContents {
382 chains: Option<Vec<ChainHash>>,
383 metadata: Option<Metadata>,
384 amount: Option<Amount>,
386 features: OfferFeatures,
387 absolute_expiry: Option<Duration>,
388 issuer: Option<String>,
389 paths: Option<Vec<BlindedPath>>,
390 supported_quantity: Quantity,
391 signing_pubkey: PublicKey,
394 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
395 // TODO: Return a slice once ChainHash has constants.
396 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
397 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
398 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
399 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
400 /// for the selected chain.
401 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
405 // TODO: Link to corresponding method in `InvoiceRequest`.
406 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
407 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
408 pub fn metadata(&$self) -> Option<&Vec<u8>> {
412 /// The minimum amount required for a successful payment of a single item.
413 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
417 /// A complete description of the purpose of the payment. Intended to be displayed to the user
418 /// but with the caveat that it has not been verified in any way.
419 pub fn description(&$self) -> $crate::util::string::PrintableString {
420 $contents.description()
423 /// Features pertaining to the offer.
424 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
425 &$contents.features()
428 /// Duration since the Unix epoch when an invoice should no longer be requested.
430 /// If `None`, the offer does not expire.
431 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
432 $contents.absolute_expiry()
435 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
436 /// displayed to the user but with the caveat that it has not been verified in any way.
437 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
441 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
442 /// recipient privacy by obfuscating its node id.
443 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
447 /// The quantity of items supported.
448 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
449 $contents.supported_quantity()
452 /// The public key used by the recipient to sign invoices.
453 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
454 $contents.signing_pubkey()
459 offer_accessors!(self, self.contents);
461 pub(super) fn implied_chain(&self) -> ChainHash {
462 self.contents.implied_chain()
465 /// Returns whether the given chain is supported by the offer.
466 pub fn supports_chain(&self, chain: ChainHash) -> bool {
467 self.contents.supports_chain(chain)
470 /// Whether the offer has expired.
471 #[cfg(feature = "std")]
472 pub fn is_expired(&self) -> bool {
473 self.contents.is_expired()
476 /// Whether the offer has expired given the duration since the Unix epoch.
477 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
478 self.contents.is_expired_no_std(duration_since_epoch)
481 /// Returns whether the given quantity is valid for the offer.
482 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
483 self.contents.is_valid_quantity(quantity)
486 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
488 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
489 pub fn expects_quantity(&self) -> bool {
490 self.contents.expects_quantity()
493 /// Similar to [`Offer::request_invoice`] except it:
494 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
496 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
497 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
498 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
499 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
500 /// be used when sending the payment for the requested invoice.
502 /// Useful to protect the sender's privacy.
504 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
506 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
507 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
508 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
509 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
510 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
511 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>,
512 payment_id: PaymentId
513 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, Bolt12SemanticError>
515 ES::Target: EntropySource,
517 if self.offer_features().requires_unknown_bits() {
518 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
521 Ok(InvoiceRequestBuilder::deriving_payer_id(
522 self, expanded_key, entropy_source, secp_ctx, payment_id
526 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
527 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
529 /// Useful for recurring payments using the same `payer_id` with different invoices.
531 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
533 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
534 pub fn request_invoice_deriving_metadata<ES: Deref>(
535 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
536 payment_id: PaymentId
537 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError>
539 ES::Target: EntropySource,
541 if self.offer_features().requires_unknown_bits() {
542 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
545 Ok(InvoiceRequestBuilder::deriving_metadata(
546 self, payer_id, expanded_key, entropy_source, payment_id
550 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
551 /// which will be reflected in the `Bolt12Invoice` response.
553 /// The `metadata` is useful for including information about the derivation of `payer_id` such
554 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
555 /// hashing in the signature calculation.
557 /// This should not leak any information such as by using a simple BIP-32 derivation path.
558 /// Otherwise, payments may be correlated.
560 /// Errors if the offer contains unknown required features.
562 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
564 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
565 pub fn request_invoice(
566 &self, metadata: Vec<u8>, payer_id: PublicKey
567 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError> {
568 if self.offer_features().requires_unknown_bits() {
569 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
572 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
576 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
577 self.contents.as_tlv_stream()
581 impl AsRef<[u8]> for Offer {
582 fn as_ref(&self) -> &[u8] {
588 pub fn chains(&self) -> Vec<ChainHash> {
589 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
592 pub fn implied_chain(&self) -> ChainHash {
593 ChainHash::using_genesis_block(Network::Bitcoin)
596 pub fn supports_chain(&self, chain: ChainHash) -> bool {
597 self.chains().contains(&chain)
600 pub fn metadata(&self) -> Option<&Vec<u8>> {
601 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
604 pub fn amount(&self) -> Option<&Amount> {
608 pub fn description(&self) -> PrintableString {
609 PrintableString(&self.description)
612 pub fn features(&self) -> &OfferFeatures {
616 pub fn absolute_expiry(&self) -> Option<Duration> {
620 #[cfg(feature = "std")]
621 pub(super) fn is_expired(&self) -> bool {
622 SystemTime::UNIX_EPOCH
624 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
628 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
630 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
634 pub fn issuer(&self) -> Option<PrintableString> {
635 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
638 pub fn paths(&self) -> &[BlindedPath] {
639 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
642 pub(super) fn check_amount_msats_for_quantity(
643 &self, amount_msats: Option<u64>, quantity: Option<u64>
644 ) -> Result<(), Bolt12SemanticError> {
645 let offer_amount_msats = match self.amount {
647 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
648 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
651 if !self.expects_quantity() || quantity.is_some() {
652 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
653 .ok_or(Bolt12SemanticError::InvalidAmount)?;
654 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
656 if amount_msats < expected_amount_msats {
657 return Err(Bolt12SemanticError::InsufficientAmount);
660 if amount_msats > MAX_VALUE_MSAT {
661 return Err(Bolt12SemanticError::InvalidAmount);
668 pub fn supported_quantity(&self) -> Quantity {
669 self.supported_quantity
672 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
673 let expects_quantity = self.expects_quantity();
675 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
676 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
677 Some(quantity) if !self.is_valid_quantity(quantity) => {
678 Err(Bolt12SemanticError::InvalidQuantity)
684 fn is_valid_quantity(&self, quantity: u64) -> bool {
685 match self.supported_quantity {
686 Quantity::Bounded(n) => quantity <= n.get(),
687 Quantity::Unbounded => quantity > 0,
688 Quantity::One => quantity == 1,
692 fn expects_quantity(&self) -> bool {
693 match self.supported_quantity {
694 Quantity::Bounded(_) => true,
695 Quantity::Unbounded => true,
696 Quantity::One => false,
700 pub(super) fn signing_pubkey(&self) -> PublicKey {
704 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
705 pub(super) fn verify<T: secp256k1::Signing>(
706 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
707 ) -> Result<Option<KeyPair>, ()> {
708 match self.metadata() {
710 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
711 match record.r#type {
712 OFFER_METADATA_TYPE => false,
713 OFFER_NODE_ID_TYPE => {
714 !self.metadata.as_ref().unwrap().derives_recipient_keys()
719 signer::verify_recipient_metadata(
720 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
727 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
728 let (currency, amount) = match &self.amount {
729 None => (None, None),
730 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
731 Some(Amount::Currency { iso4217_code, amount }) => (
732 Some(iso4217_code), Some(*amount)
737 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
741 chains: self.chains.as_ref(),
742 metadata: self.metadata(),
745 description: Some(&self.description),
747 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
748 paths: self.paths.as_ref(),
749 issuer: self.issuer.as_ref(),
750 quantity_max: self.supported_quantity.to_tlv_record(),
751 node_id: Some(&self.signing_pubkey),
756 impl Writeable for Offer {
757 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
758 WithoutLength(&self.bytes).write(writer)
762 impl Writeable for OfferContents {
763 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
764 self.as_tlv_stream().write(writer)
768 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
769 /// another currency.
770 #[derive(Clone, Debug, PartialEq)]
772 /// An amount of bitcoin.
774 /// The amount in millisatoshi.
777 /// An amount of currency specified using ISO 4712.
779 /// The currency that the amount is denominated in.
780 iso4217_code: CurrencyCode,
781 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
786 /// An ISO 4712 three-letter currency code (e.g., USD).
787 pub type CurrencyCode = [u8; 3];
789 /// Quantity of items supported by an [`Offer`].
790 #[derive(Clone, Copy, Debug, PartialEq)]
792 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
793 /// but is limited (e.g., because of per customer or inventory limits).
795 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
798 /// One or more items. Use when more than one item can be requested without any limit.
800 /// Only one item. Use when only a single item can be requested.
805 fn to_tlv_record(&self) -> Option<u64> {
807 Quantity::Bounded(n) => Some(n.get()),
808 Quantity::Unbounded => Some(0),
809 Quantity::One => None,
814 /// Valid type range for offer TLV records.
815 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
817 /// TLV record type for [`Offer::metadata`].
818 const OFFER_METADATA_TYPE: u64 = 4;
820 /// TLV record type for [`Offer::signing_pubkey`].
821 const OFFER_NODE_ID_TYPE: u64 = 22;
823 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
824 (2, chains: (Vec<ChainHash>, WithoutLength)),
825 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
826 (6, currency: CurrencyCode),
827 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
828 (10, description: (String, WithoutLength)),
829 (12, features: (OfferFeatures, WithoutLength)),
830 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
831 (16, paths: (Vec<BlindedPath>, WithoutLength)),
832 (18, issuer: (String, WithoutLength)),
833 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
834 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
837 impl Bech32Encode for Offer {
838 const BECH32_HRP: &'static str = "lno";
841 impl FromStr for Offer {
842 type Err = Bolt12ParseError;
844 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
845 Self::from_bech32_str(s)
849 impl TryFrom<Vec<u8>> for Offer {
850 type Error = Bolt12ParseError;
852 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
853 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
854 let ParsedMessage { bytes, tlv_stream } = offer;
855 let contents = OfferContents::try_from(tlv_stream)?;
856 Ok(Offer { bytes, contents })
860 impl TryFrom<OfferTlvStream> for OfferContents {
861 type Error = Bolt12SemanticError;
863 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
865 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
866 issuer, quantity_max, node_id,
869 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
871 let amount = match (currency, amount) {
872 (None, None) => None,
873 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
874 return Err(Bolt12SemanticError::InvalidAmount);
876 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
877 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
878 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
881 let description = match description {
882 None => return Err(Bolt12SemanticError::MissingDescription),
883 Some(description) => description,
886 let features = features.unwrap_or_else(OfferFeatures::empty);
888 let absolute_expiry = absolute_expiry
889 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
891 let supported_quantity = match quantity_max {
892 None => Quantity::One,
893 Some(0) => Quantity::Unbounded,
894 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
897 let signing_pubkey = match node_id {
898 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
899 Some(node_id) => node_id,
903 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
904 supported_quantity, signing_pubkey,
909 impl core::fmt::Display for Offer {
910 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
911 self.fmt_bech32_str(f)
917 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
919 use bitcoin::blockdata::constants::ChainHash;
920 use bitcoin::network::constants::Network;
921 use bitcoin::secp256k1::Secp256k1;
922 use core::convert::TryFrom;
923 use core::num::NonZeroU64;
924 use core::time::Duration;
925 use crate::blinded_path::{BlindedHop, BlindedPath};
926 use crate::sign::KeyMaterial;
927 use crate::ln::features::OfferFeatures;
928 use crate::ln::inbound_payment::ExpandedKey;
929 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
930 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
931 use crate::offers::test_utils::*;
932 use crate::util::ser::{BigSize, Writeable};
933 use crate::util::string::PrintableString;
936 fn builds_offer_with_defaults() {
937 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
939 let mut buffer = Vec::new();
940 offer.write(&mut buffer).unwrap();
942 assert_eq!(offer.bytes, buffer.as_slice());
943 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
944 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
945 assert_eq!(offer.metadata(), None);
946 assert_eq!(offer.amount(), None);
947 assert_eq!(offer.description(), PrintableString("foo"));
948 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
949 assert_eq!(offer.absolute_expiry(), None);
950 #[cfg(feature = "std")]
951 assert!(!offer.is_expired());
952 assert_eq!(offer.paths(), &[]);
953 assert_eq!(offer.issuer(), None);
954 assert_eq!(offer.supported_quantity(), Quantity::One);
955 assert_eq!(offer.signing_pubkey(), pubkey(42));
958 offer.as_tlv_stream(),
964 description: Some(&String::from("foo")),
966 absolute_expiry: None,
970 node_id: Some(&pubkey(42)),
974 if let Err(e) = Offer::try_from(buffer) {
975 panic!("error parsing offer: {:?}", e);
980 fn builds_offer_with_chains() {
981 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
982 let testnet = ChainHash::using_genesis_block(Network::Testnet);
984 let offer = OfferBuilder::new("foo".into(), pubkey(42))
985 .chain(Network::Bitcoin)
988 assert!(offer.supports_chain(mainnet));
989 assert_eq!(offer.chains(), vec![mainnet]);
990 assert_eq!(offer.as_tlv_stream().chains, None);
992 let offer = OfferBuilder::new("foo".into(), pubkey(42))
993 .chain(Network::Testnet)
996 assert!(offer.supports_chain(testnet));
997 assert_eq!(offer.chains(), vec![testnet]);
998 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1000 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1001 .chain(Network::Testnet)
1002 .chain(Network::Testnet)
1005 assert!(offer.supports_chain(testnet));
1006 assert_eq!(offer.chains(), vec![testnet]);
1007 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1009 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1010 .chain(Network::Bitcoin)
1011 .chain(Network::Testnet)
1014 assert!(offer.supports_chain(mainnet));
1015 assert!(offer.supports_chain(testnet));
1016 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1017 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1021 fn builds_offer_with_metadata() {
1022 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1023 .metadata(vec![42; 32]).unwrap()
1026 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1027 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1029 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1030 .metadata(vec![42; 32]).unwrap()
1031 .metadata(vec![43; 32]).unwrap()
1034 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1035 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1039 fn builds_offer_with_metadata_derived() {
1040 let desc = "foo".to_string();
1041 let node_id = recipient_pubkey();
1042 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1043 let entropy = FixedEntropy {};
1044 let secp_ctx = Secp256k1::new();
1046 let offer = OfferBuilder
1047 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1050 assert_eq!(offer.signing_pubkey(), node_id);
1052 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1054 .sign(payer_sign).unwrap();
1055 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1057 // Fails verification with altered offer field
1058 let mut tlv_stream = offer.as_tlv_stream();
1059 tlv_stream.amount = Some(100);
1061 let mut encoded_offer = Vec::new();
1062 tlv_stream.write(&mut encoded_offer).unwrap();
1064 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1065 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1067 .sign(payer_sign).unwrap();
1068 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1070 // Fails verification with altered metadata
1071 let mut tlv_stream = offer.as_tlv_stream();
1072 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1073 tlv_stream.metadata = Some(&metadata);
1075 let mut encoded_offer = Vec::new();
1076 tlv_stream.write(&mut encoded_offer).unwrap();
1078 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1079 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1081 .sign(payer_sign).unwrap();
1082 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1086 fn builds_offer_with_derived_signing_pubkey() {
1087 let desc = "foo".to_string();
1088 let node_id = recipient_pubkey();
1089 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1090 let entropy = FixedEntropy {};
1091 let secp_ctx = Secp256k1::new();
1093 let blinded_path = BlindedPath {
1094 introduction_node_id: pubkey(40),
1095 blinding_point: pubkey(41),
1097 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1098 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1102 let offer = OfferBuilder
1103 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1107 assert_ne!(offer.signing_pubkey(), node_id);
1109 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1111 .sign(payer_sign).unwrap();
1112 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1114 // Fails verification with altered offer field
1115 let mut tlv_stream = offer.as_tlv_stream();
1116 tlv_stream.amount = Some(100);
1118 let mut encoded_offer = Vec::new();
1119 tlv_stream.write(&mut encoded_offer).unwrap();
1121 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1122 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1124 .sign(payer_sign).unwrap();
1125 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1127 // Fails verification with altered signing pubkey
1128 let mut tlv_stream = offer.as_tlv_stream();
1129 let signing_pubkey = pubkey(1);
1130 tlv_stream.node_id = Some(&signing_pubkey);
1132 let mut encoded_offer = Vec::new();
1133 tlv_stream.write(&mut encoded_offer).unwrap();
1135 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1136 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1138 .sign(payer_sign).unwrap();
1139 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1143 fn builds_offer_with_amount() {
1144 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1145 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1147 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1151 let tlv_stream = offer.as_tlv_stream();
1152 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1153 assert_eq!(tlv_stream.amount, Some(1000));
1154 assert_eq!(tlv_stream.currency, None);
1156 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1157 .amount(currency_amount.clone());
1158 let tlv_stream = builder.offer.as_tlv_stream();
1159 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1160 assert_eq!(tlv_stream.amount, Some(10));
1161 assert_eq!(tlv_stream.currency, Some(b"USD"));
1162 match builder.build() {
1163 Ok(_) => panic!("expected error"),
1164 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1167 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1168 .amount(currency_amount.clone())
1169 .amount(bitcoin_amount.clone())
1172 let tlv_stream = offer.as_tlv_stream();
1173 assert_eq!(tlv_stream.amount, Some(1000));
1174 assert_eq!(tlv_stream.currency, None);
1176 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1177 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1178 Ok(_) => panic!("expected error"),
1179 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1184 fn builds_offer_with_features() {
1185 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1186 .features_unchecked(OfferFeatures::unknown())
1189 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1190 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1192 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1193 .features_unchecked(OfferFeatures::unknown())
1194 .features_unchecked(OfferFeatures::empty())
1197 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1198 assert_eq!(offer.as_tlv_stream().features, None);
1202 fn builds_offer_with_absolute_expiry() {
1203 let future_expiry = Duration::from_secs(u64::max_value());
1204 let past_expiry = Duration::from_secs(0);
1205 let now = future_expiry - Duration::from_secs(1_000);
1207 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1208 .absolute_expiry(future_expiry)
1211 #[cfg(feature = "std")]
1212 assert!(!offer.is_expired());
1213 assert!(!offer.is_expired_no_std(now));
1214 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1215 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1217 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1218 .absolute_expiry(future_expiry)
1219 .absolute_expiry(past_expiry)
1222 #[cfg(feature = "std")]
1223 assert!(offer.is_expired());
1224 assert!(offer.is_expired_no_std(now));
1225 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1226 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1230 fn builds_offer_with_paths() {
1233 introduction_node_id: pubkey(40),
1234 blinding_point: pubkey(41),
1236 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1237 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1241 introduction_node_id: pubkey(40),
1242 blinding_point: pubkey(41),
1244 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1245 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1250 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1251 .path(paths[0].clone())
1252 .path(paths[1].clone())
1255 let tlv_stream = offer.as_tlv_stream();
1256 assert_eq!(offer.paths(), paths.as_slice());
1257 assert_eq!(offer.signing_pubkey(), pubkey(42));
1258 assert_ne!(pubkey(42), pubkey(44));
1259 assert_eq!(tlv_stream.paths, Some(&paths));
1260 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1264 fn builds_offer_with_issuer() {
1265 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1266 .issuer("bar".into())
1269 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1270 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1272 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1273 .issuer("bar".into())
1274 .issuer("baz".into())
1277 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1278 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1282 fn builds_offer_with_supported_quantity() {
1283 let one = NonZeroU64::new(1).unwrap();
1284 let ten = NonZeroU64::new(10).unwrap();
1286 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1287 .supported_quantity(Quantity::One)
1290 let tlv_stream = offer.as_tlv_stream();
1291 assert_eq!(offer.supported_quantity(), Quantity::One);
1292 assert_eq!(tlv_stream.quantity_max, None);
1294 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1295 .supported_quantity(Quantity::Unbounded)
1298 let tlv_stream = offer.as_tlv_stream();
1299 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1300 assert_eq!(tlv_stream.quantity_max, Some(0));
1302 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1303 .supported_quantity(Quantity::Bounded(ten))
1306 let tlv_stream = offer.as_tlv_stream();
1307 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1308 assert_eq!(tlv_stream.quantity_max, Some(10));
1310 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1311 .supported_quantity(Quantity::Bounded(one))
1314 let tlv_stream = offer.as_tlv_stream();
1315 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1316 assert_eq!(tlv_stream.quantity_max, Some(1));
1318 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1319 .supported_quantity(Quantity::Bounded(ten))
1320 .supported_quantity(Quantity::One)
1323 let tlv_stream = offer.as_tlv_stream();
1324 assert_eq!(offer.supported_quantity(), Quantity::One);
1325 assert_eq!(tlv_stream.quantity_max, None);
1329 fn fails_requesting_invoice_with_unknown_required_features() {
1330 match OfferBuilder::new("foo".into(), pubkey(42))
1331 .features_unchecked(OfferFeatures::unknown())
1333 .request_invoice(vec![1; 32], pubkey(43))
1335 Ok(_) => panic!("expected error"),
1336 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1341 fn parses_offer_with_chains() {
1342 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1343 .chain(Network::Bitcoin)
1344 .chain(Network::Testnet)
1347 if let Err(e) = offer.to_string().parse::<Offer>() {
1348 panic!("error parsing offer: {:?}", e);
1353 fn parses_offer_with_amount() {
1354 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1355 .amount(Amount::Bitcoin { amount_msats: 1000 })
1358 if let Err(e) = offer.to_string().parse::<Offer>() {
1359 panic!("error parsing offer: {:?}", e);
1362 let mut tlv_stream = offer.as_tlv_stream();
1363 tlv_stream.amount = Some(1000);
1364 tlv_stream.currency = Some(b"USD");
1366 let mut encoded_offer = Vec::new();
1367 tlv_stream.write(&mut encoded_offer).unwrap();
1369 if let Err(e) = Offer::try_from(encoded_offer) {
1370 panic!("error parsing offer: {:?}", e);
1373 let mut tlv_stream = offer.as_tlv_stream();
1374 tlv_stream.amount = None;
1375 tlv_stream.currency = Some(b"USD");
1377 let mut encoded_offer = Vec::new();
1378 tlv_stream.write(&mut encoded_offer).unwrap();
1380 match Offer::try_from(encoded_offer) {
1381 Ok(_) => panic!("expected error"),
1382 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1385 let mut tlv_stream = offer.as_tlv_stream();
1386 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1387 tlv_stream.currency = None;
1389 let mut encoded_offer = Vec::new();
1390 tlv_stream.write(&mut encoded_offer).unwrap();
1392 match Offer::try_from(encoded_offer) {
1393 Ok(_) => panic!("expected error"),
1394 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1399 fn parses_offer_with_description() {
1400 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1401 if let Err(e) = offer.to_string().parse::<Offer>() {
1402 panic!("error parsing offer: {:?}", e);
1405 let mut tlv_stream = offer.as_tlv_stream();
1406 tlv_stream.description = None;
1408 let mut encoded_offer = Vec::new();
1409 tlv_stream.write(&mut encoded_offer).unwrap();
1411 match Offer::try_from(encoded_offer) {
1412 Ok(_) => panic!("expected error"),
1414 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1420 fn parses_offer_with_paths() {
1421 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1423 introduction_node_id: pubkey(40),
1424 blinding_point: pubkey(41),
1426 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1427 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1431 introduction_node_id: pubkey(40),
1432 blinding_point: pubkey(41),
1434 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1435 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1440 if let Err(e) = offer.to_string().parse::<Offer>() {
1441 panic!("error parsing offer: {:?}", e);
1444 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1445 builder.offer.paths = Some(vec![]);
1447 let offer = builder.build().unwrap();
1448 if let Err(e) = offer.to_string().parse::<Offer>() {
1449 panic!("error parsing offer: {:?}", e);
1454 fn parses_offer_with_quantity() {
1455 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1456 .supported_quantity(Quantity::One)
1459 if let Err(e) = offer.to_string().parse::<Offer>() {
1460 panic!("error parsing offer: {:?}", e);
1463 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1464 .supported_quantity(Quantity::Unbounded)
1467 if let Err(e) = offer.to_string().parse::<Offer>() {
1468 panic!("error parsing offer: {:?}", e);
1471 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1472 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1475 if let Err(e) = offer.to_string().parse::<Offer>() {
1476 panic!("error parsing offer: {:?}", e);
1479 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1480 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1483 if let Err(e) = offer.to_string().parse::<Offer>() {
1484 panic!("error parsing offer: {:?}", e);
1489 fn parses_offer_with_node_id() {
1490 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1491 if let Err(e) = offer.to_string().parse::<Offer>() {
1492 panic!("error parsing offer: {:?}", e);
1495 let mut tlv_stream = offer.as_tlv_stream();
1496 tlv_stream.node_id = None;
1498 let mut encoded_offer = Vec::new();
1499 tlv_stream.write(&mut encoded_offer).unwrap();
1501 match Offer::try_from(encoded_offer) {
1502 Ok(_) => panic!("expected error"),
1504 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1510 fn fails_parsing_offer_with_extra_tlv_records() {
1511 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1513 let mut encoded_offer = Vec::new();
1514 offer.write(&mut encoded_offer).unwrap();
1515 BigSize(80).write(&mut encoded_offer).unwrap();
1516 BigSize(32).write(&mut encoded_offer).unwrap();
1517 [42u8; 32].write(&mut encoded_offer).unwrap();
1519 match Offer::try_from(encoded_offer) {
1520 Ok(_) => panic!("expected error"),
1521 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1528 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1529 use crate::ln::msgs::DecodeError;
1532 fn parses_bech32_encoded_offers() {
1534 // Minimal bolt12 offer
1535 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1538 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1540 // for bitcoin (redundant)
1541 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1543 // for bitcoin or liquidv1
1544 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1547 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1550 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1553 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1556 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1559 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1562 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1564 // with unlimited (or unknown) quantity
1565 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1567 // with single quantity (weird but valid)
1568 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1571 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1573 // with blinded path via Bob (0x424242...), blinding 020202...
1574 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1576 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1577 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1579 // unknown odd field
1580 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1582 for encoded_offer in &offers {
1583 if let Err(e) = encoded_offer.parse::<Offer>() {
1584 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1590 fn fails_parsing_bech32_encoded_offers() {
1591 // Malformed: fields out of order
1593 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1594 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1597 // Malformed: unknown even TLV type 78
1599 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1600 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1605 "lno1".parse::<Offer>(),
1606 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1609 // Malformed: truncated at type
1611 "lno1pg".parse::<Offer>(),
1612 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1615 // Malformed: truncated in length
1617 "lno1pt7s".parse::<Offer>(),
1618 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1621 // Malformed: truncated after length
1623 "lno1pgpq".parse::<Offer>(),
1624 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1627 // Malformed: truncated in description
1629 "lno1pgpyz".parse::<Offer>(),
1630 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1633 // Malformed: invalid offer_chains length
1635 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1636 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1639 // Malformed: truncated currency UTF-8
1641 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1642 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1645 // Malformed: invalid currency UTF-8
1647 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1648 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1651 // Malformed: truncated description UTF-8
1653 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1654 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1657 // Malformed: invalid description UTF-8
1659 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1660 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1663 // Malformed: truncated offer_paths
1665 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1666 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1669 // Malformed: zero num_hops in blinded_path
1671 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1672 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1675 // Malformed: truncated onionmsg_hop in blinded_path
1677 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1678 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1681 // Malformed: bad first_node_id in blinded_path
1683 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1684 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1687 // Malformed: bad blinding in blinded_path
1689 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1690 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1693 // Malformed: bad blinded_node_id in onionmsg_hop
1695 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1696 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1699 // Malformed: truncated issuer UTF-8
1701 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1702 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1705 // Malformed: invalid issuer UTF-8
1707 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1708 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1711 // Malformed: invalid offer_node_id
1713 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1714 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1717 // Contains type >= 80
1719 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1720 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1723 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1724 // Contains unknown feature 22
1726 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1729 // Missing offer_description
1731 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1732 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1735 // Missing offer_node_id"
1737 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1738 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),