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 {}
138 impl MetadataStrategy for DerivedMetadata {}
140 macro_rules! offer_explicit_metadata_builder_methods { (
141 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
143 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
144 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
145 /// while the offer is valid.
147 /// Use a different pubkey per offer to avoid correlating offers.
151 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
152 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
154 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
155 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
156 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
158 offer: OfferContents {
159 chains: None, metadata: None, amount: None, description,
160 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
161 supported_quantity: Quantity::One, signing_pubkey,
163 metadata_strategy: core::marker::PhantomData,
168 /// Sets the [`Offer::metadata`] to the given bytes.
170 /// Successive calls to this method will override the previous setting.
171 pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
172 $self.offer.metadata = Some(Metadata::Bytes(metadata));
177 macro_rules! offer_derived_metadata_builder_methods { () => {
178 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
179 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
180 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
181 /// provided `node_id` is used for the signing pubkey.
183 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
184 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
187 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
188 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
189 pub fn deriving_signing_pubkey<ES: Deref>(
190 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
191 secp_ctx: &'a Secp256k1<T>
192 ) -> Self where ES::Target: EntropySource {
193 let nonce = Nonce::from_entropy_source(entropy_source);
194 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
195 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
197 offer: OfferContents {
198 chains: None, metadata: Some(metadata), amount: None, description,
199 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
200 supported_quantity: Quantity::One, signing_pubkey: node_id,
202 metadata_strategy: core::marker::PhantomData,
203 secp_ctx: Some(secp_ctx),
208 macro_rules! offer_builder_methods { (
209 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
211 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
212 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
214 /// See [`Offer::chains`] on how this relates to the payment currency.
216 /// Successive calls to this method will add another chain hash.
217 pub fn chain($self: $self_type, network: Network) -> $return_type {
218 $self.chain_hash(ChainHash::using_genesis_block(network))
221 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
222 /// [`Network::Bitcoin`] is assumed to be the only one supported.
224 /// See [`Offer::chains`] on how this relates to the payment currency.
226 /// Successive calls to this method will add another chain hash.
227 pub(crate) fn chain_hash(mut $self: $self_type, chain: ChainHash) -> $return_type {
228 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
229 if !chains.contains(&chain) {
236 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
238 /// Successive calls to this method will override the previous setting.
239 pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
240 $self.amount(Amount::Bitcoin { amount_msats })
243 /// Sets the [`Offer::amount`].
245 /// Successive calls to this method will override the previous setting.
246 pub(super) fn amount(mut $self: $self_type, amount: Amount) -> $return_type {
247 $self.offer.amount = Some(amount);
251 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
252 /// already passed is valid and can be checked for using [`Offer::is_expired`].
254 /// Successive calls to this method will override the previous setting.
255 pub fn absolute_expiry(mut $self: $self_type, absolute_expiry: Duration) -> $return_type {
256 $self.offer.absolute_expiry = Some(absolute_expiry);
260 /// Sets the [`Offer::issuer`].
262 /// Successive calls to this method will override the previous setting.
263 pub fn issuer(mut $self: $self_type, issuer: String) -> $return_type {
264 $self.offer.issuer = Some(issuer);
268 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
269 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
271 /// Successive calls to this method will add another blinded path. Caller is responsible for not
272 /// adding duplicate paths.
273 pub fn path(mut $self: $self_type, path: BlindedPath) -> $return_type {
274 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
278 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
279 /// [`Quantity::One`].
281 /// Successive calls to this method will override the previous setting.
282 pub fn supported_quantity(mut $self: $self_type, quantity: Quantity) -> $return_type {
283 $self.offer.supported_quantity = quantity;
287 /// Builds an [`Offer`] from the builder's settings.
288 pub fn build(mut $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
289 match $self.offer.amount {
290 Some(Amount::Bitcoin { amount_msats }) => {
291 if amount_msats > MAX_VALUE_MSAT {
292 return Err(Bolt12SemanticError::InvalidAmount);
295 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
299 if let Some(chains) = &$self.offer.chains {
300 if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
301 $self.offer.chains = None;
305 Ok($self.build_without_checks())
308 fn build_without_checks(mut $self: $self_type) -> Offer {
309 // Create the metadata for stateless verification of an InvoiceRequest.
310 if let Some(mut metadata) = $self.offer.metadata.take() {
311 if metadata.has_derivation_material() {
312 if $self.offer.paths.is_none() {
313 metadata = metadata.without_keys();
316 let mut tlv_stream = $self.offer.as_tlv_stream();
317 debug_assert_eq!(tlv_stream.metadata, None);
318 tlv_stream.metadata = None;
319 if metadata.derives_recipient_keys() {
320 tlv_stream.node_id = None;
323 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
324 metadata = derived_metadata;
325 if let Some(keys) = keys {
326 $self.offer.signing_pubkey = keys.public_key();
330 $self.offer.metadata = Some(metadata);
333 let mut bytes = Vec::new();
334 $self.offer.write(&mut bytes).unwrap();
336 Offer { bytes, contents: $self.offer }
341 macro_rules! offer_builder_test_methods { (
342 $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
344 fn features_unchecked(mut $self: $self_type, features: OfferFeatures) -> $return_type {
345 $self.offer.features = features;
349 pub(crate) fn clear_paths(mut $self: $self_type) -> $return_type {
350 $self.offer.paths = None;
354 pub(super) fn build_unchecked($self: $self_type) -> Offer {
355 $self.build_without_checks()
359 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
360 offer_builder_methods!(self, Self, Self, self);
363 offer_builder_test_methods!(self, Self, Self, self);
366 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
367 offer_explicit_metadata_builder_methods!(self, Self, Self, self);
370 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
371 offer_derived_metadata_builder_methods!();
374 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
376 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
377 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
378 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
380 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
383 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
385 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
386 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
387 #[derive(Clone, Debug)]
388 #[cfg_attr(test, derive(PartialEq))]
390 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
392 pub(super) bytes: Vec<u8>,
393 pub(super) contents: OfferContents,
396 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
397 /// [`Bolt12Invoice`].
399 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
400 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
401 #[derive(Clone, Debug)]
402 #[cfg_attr(test, derive(PartialEq))]
403 pub(super) struct OfferContents {
404 chains: Option<Vec<ChainHash>>,
405 metadata: Option<Metadata>,
406 amount: Option<Amount>,
408 features: OfferFeatures,
409 absolute_expiry: Option<Duration>,
410 issuer: Option<String>,
411 paths: Option<Vec<BlindedPath>>,
412 supported_quantity: Quantity,
413 signing_pubkey: PublicKey,
416 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
417 // TODO: Return a slice once ChainHash has constants.
418 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
419 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
420 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
421 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
422 /// for the selected chain.
423 pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
427 // TODO: Link to corresponding method in `InvoiceRequest`.
428 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
429 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
430 pub fn metadata(&$self) -> Option<&Vec<u8>> {
434 /// The minimum amount required for a successful payment of a single item.
435 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
439 /// A complete description of the purpose of the payment. Intended to be displayed to the user
440 /// but with the caveat that it has not been verified in any way.
441 pub fn description(&$self) -> $crate::util::string::PrintableString {
442 $contents.description()
445 /// Features pertaining to the offer.
446 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
447 &$contents.features()
450 /// Duration since the Unix epoch when an invoice should no longer be requested.
452 /// If `None`, the offer does not expire.
453 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
454 $contents.absolute_expiry()
457 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
458 /// displayed to the user but with the caveat that it has not been verified in any way.
459 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
463 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
464 /// recipient privacy by obfuscating its node id.
465 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
469 /// The quantity of items supported.
470 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
471 $contents.supported_quantity()
474 /// The public key used by the recipient to sign invoices.
475 pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
476 $contents.signing_pubkey()
481 offer_accessors!(self, self.contents);
483 pub(super) fn implied_chain(&self) -> ChainHash {
484 self.contents.implied_chain()
487 /// Returns whether the given chain is supported by the offer.
488 pub fn supports_chain(&self, chain: ChainHash) -> bool {
489 self.contents.supports_chain(chain)
492 /// Whether the offer has expired.
493 #[cfg(feature = "std")]
494 pub fn is_expired(&self) -> bool {
495 self.contents.is_expired()
498 /// Whether the offer has expired given the duration since the Unix epoch.
499 pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
500 self.contents.is_expired_no_std(duration_since_epoch)
503 /// Returns whether the given quantity is valid for the offer.
504 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
505 self.contents.is_valid_quantity(quantity)
508 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
510 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
511 pub fn expects_quantity(&self) -> bool {
512 self.contents.expects_quantity()
515 /// Similar to [`Offer::request_invoice`] except it:
516 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
518 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
519 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
520 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
521 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
522 /// be used when sending the payment for the requested invoice.
524 /// Useful to protect the sender's privacy.
526 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
528 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
529 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
530 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
531 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
532 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
533 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>,
534 payment_id: PaymentId
535 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, Bolt12SemanticError>
537 ES::Target: EntropySource,
539 if self.offer_features().requires_unknown_bits() {
540 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
543 Ok(InvoiceRequestBuilder::deriving_payer_id(
544 self, expanded_key, entropy_source, secp_ctx, payment_id
548 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
549 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
551 /// Useful for recurring payments using the same `payer_id` with different invoices.
553 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
555 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
556 pub fn request_invoice_deriving_metadata<ES: Deref>(
557 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
558 payment_id: PaymentId
559 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError>
561 ES::Target: EntropySource,
563 if self.offer_features().requires_unknown_bits() {
564 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
567 Ok(InvoiceRequestBuilder::deriving_metadata(
568 self, payer_id, expanded_key, entropy_source, payment_id
572 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
573 /// which will be reflected in the `Bolt12Invoice` response.
575 /// The `metadata` is useful for including information about the derivation of `payer_id` such
576 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
577 /// hashing in the signature calculation.
579 /// This should not leak any information such as by using a simple BIP-32 derivation path.
580 /// Otherwise, payments may be correlated.
582 /// Errors if the offer contains unknown required features.
584 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
586 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
587 pub fn request_invoice(
588 &self, metadata: Vec<u8>, payer_id: PublicKey
589 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError> {
590 if self.offer_features().requires_unknown_bits() {
591 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
594 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
598 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
599 self.contents.as_tlv_stream()
603 impl AsRef<[u8]> for Offer {
604 fn as_ref(&self) -> &[u8] {
610 pub fn chains(&self) -> Vec<ChainHash> {
611 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
614 pub fn implied_chain(&self) -> ChainHash {
615 ChainHash::using_genesis_block(Network::Bitcoin)
618 pub fn supports_chain(&self, chain: ChainHash) -> bool {
619 self.chains().contains(&chain)
622 pub fn metadata(&self) -> Option<&Vec<u8>> {
623 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
626 pub fn amount(&self) -> Option<&Amount> {
630 pub fn description(&self) -> PrintableString {
631 PrintableString(&self.description)
634 pub fn features(&self) -> &OfferFeatures {
638 pub fn absolute_expiry(&self) -> Option<Duration> {
642 #[cfg(feature = "std")]
643 pub(super) fn is_expired(&self) -> bool {
644 SystemTime::UNIX_EPOCH
646 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
650 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
652 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
656 pub fn issuer(&self) -> Option<PrintableString> {
657 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
660 pub fn paths(&self) -> &[BlindedPath] {
661 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
664 pub(super) fn check_amount_msats_for_quantity(
665 &self, amount_msats: Option<u64>, quantity: Option<u64>
666 ) -> Result<(), Bolt12SemanticError> {
667 let offer_amount_msats = match self.amount {
669 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
670 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
673 if !self.expects_quantity() || quantity.is_some() {
674 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
675 .ok_or(Bolt12SemanticError::InvalidAmount)?;
676 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
678 if amount_msats < expected_amount_msats {
679 return Err(Bolt12SemanticError::InsufficientAmount);
682 if amount_msats > MAX_VALUE_MSAT {
683 return Err(Bolt12SemanticError::InvalidAmount);
690 pub fn supported_quantity(&self) -> Quantity {
691 self.supported_quantity
694 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
695 let expects_quantity = self.expects_quantity();
697 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
698 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
699 Some(quantity) if !self.is_valid_quantity(quantity) => {
700 Err(Bolt12SemanticError::InvalidQuantity)
706 fn is_valid_quantity(&self, quantity: u64) -> bool {
707 match self.supported_quantity {
708 Quantity::Bounded(n) => quantity <= n.get(),
709 Quantity::Unbounded => quantity > 0,
710 Quantity::One => quantity == 1,
714 fn expects_quantity(&self) -> bool {
715 match self.supported_quantity {
716 Quantity::Bounded(_) => true,
717 Quantity::Unbounded => true,
718 Quantity::One => false,
722 pub(super) fn signing_pubkey(&self) -> PublicKey {
726 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
727 pub(super) fn verify<T: secp256k1::Signing>(
728 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
729 ) -> Result<Option<KeyPair>, ()> {
730 match self.metadata() {
732 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
733 match record.r#type {
734 OFFER_METADATA_TYPE => false,
735 OFFER_NODE_ID_TYPE => {
736 !self.metadata.as_ref().unwrap().derives_recipient_keys()
741 signer::verify_recipient_metadata(
742 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
749 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
750 let (currency, amount) = match &self.amount {
751 None => (None, None),
752 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
753 Some(Amount::Currency { iso4217_code, amount }) => (
754 Some(iso4217_code), Some(*amount)
759 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
763 chains: self.chains.as_ref(),
764 metadata: self.metadata(),
767 description: Some(&self.description),
769 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
770 paths: self.paths.as_ref(),
771 issuer: self.issuer.as_ref(),
772 quantity_max: self.supported_quantity.to_tlv_record(),
773 node_id: Some(&self.signing_pubkey),
778 impl Writeable for Offer {
779 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
780 WithoutLength(&self.bytes).write(writer)
784 impl Writeable for OfferContents {
785 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
786 self.as_tlv_stream().write(writer)
790 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
791 /// another currency.
792 #[derive(Clone, Debug, PartialEq)]
794 /// An amount of bitcoin.
796 /// The amount in millisatoshi.
799 /// An amount of currency specified using ISO 4712.
801 /// The currency that the amount is denominated in.
802 iso4217_code: CurrencyCode,
803 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
808 /// An ISO 4712 three-letter currency code (e.g., USD).
809 pub type CurrencyCode = [u8; 3];
811 /// Quantity of items supported by an [`Offer`].
812 #[derive(Clone, Copy, Debug, PartialEq)]
814 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
815 /// but is limited (e.g., because of per customer or inventory limits).
817 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
820 /// One or more items. Use when more than one item can be requested without any limit.
822 /// Only one item. Use when only a single item can be requested.
827 fn to_tlv_record(&self) -> Option<u64> {
829 Quantity::Bounded(n) => Some(n.get()),
830 Quantity::Unbounded => Some(0),
831 Quantity::One => None,
836 /// Valid type range for offer TLV records.
837 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
839 /// TLV record type for [`Offer::metadata`].
840 const OFFER_METADATA_TYPE: u64 = 4;
842 /// TLV record type for [`Offer::signing_pubkey`].
843 const OFFER_NODE_ID_TYPE: u64 = 22;
845 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
846 (2, chains: (Vec<ChainHash>, WithoutLength)),
847 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
848 (6, currency: CurrencyCode),
849 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
850 (10, description: (String, WithoutLength)),
851 (12, features: (OfferFeatures, WithoutLength)),
852 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
853 (16, paths: (Vec<BlindedPath>, WithoutLength)),
854 (18, issuer: (String, WithoutLength)),
855 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
856 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
859 impl Bech32Encode for Offer {
860 const BECH32_HRP: &'static str = "lno";
863 impl FromStr for Offer {
864 type Err = Bolt12ParseError;
866 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
867 Self::from_bech32_str(s)
871 impl TryFrom<Vec<u8>> for Offer {
872 type Error = Bolt12ParseError;
874 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
875 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
876 let ParsedMessage { bytes, tlv_stream } = offer;
877 let contents = OfferContents::try_from(tlv_stream)?;
878 Ok(Offer { bytes, contents })
882 impl TryFrom<OfferTlvStream> for OfferContents {
883 type Error = Bolt12SemanticError;
885 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
887 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
888 issuer, quantity_max, node_id,
891 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
893 let amount = match (currency, amount) {
894 (None, None) => None,
895 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
896 return Err(Bolt12SemanticError::InvalidAmount);
898 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
899 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
900 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
903 let description = match description {
904 None => return Err(Bolt12SemanticError::MissingDescription),
905 Some(description) => description,
908 let features = features.unwrap_or_else(OfferFeatures::empty);
910 let absolute_expiry = absolute_expiry
911 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
913 let supported_quantity = match quantity_max {
914 None => Quantity::One,
915 Some(0) => Quantity::Unbounded,
916 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
919 let signing_pubkey = match node_id {
920 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
921 Some(node_id) => node_id,
925 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
926 supported_quantity, signing_pubkey,
931 impl core::fmt::Display for Offer {
932 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
933 self.fmt_bech32_str(f)
939 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
941 use bitcoin::blockdata::constants::ChainHash;
942 use bitcoin::network::constants::Network;
943 use bitcoin::secp256k1::Secp256k1;
944 use core::convert::TryFrom;
945 use core::num::NonZeroU64;
946 use core::time::Duration;
947 use crate::blinded_path::{BlindedHop, BlindedPath};
948 use crate::sign::KeyMaterial;
949 use crate::ln::features::OfferFeatures;
950 use crate::ln::inbound_payment::ExpandedKey;
951 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
952 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
953 use crate::offers::test_utils::*;
954 use crate::util::ser::{BigSize, Writeable};
955 use crate::util::string::PrintableString;
958 fn builds_offer_with_defaults() {
959 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
961 let mut buffer = Vec::new();
962 offer.write(&mut buffer).unwrap();
964 assert_eq!(offer.bytes, buffer.as_slice());
965 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
966 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
967 assert_eq!(offer.metadata(), None);
968 assert_eq!(offer.amount(), None);
969 assert_eq!(offer.description(), PrintableString("foo"));
970 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
971 assert_eq!(offer.absolute_expiry(), None);
972 #[cfg(feature = "std")]
973 assert!(!offer.is_expired());
974 assert_eq!(offer.paths(), &[]);
975 assert_eq!(offer.issuer(), None);
976 assert_eq!(offer.supported_quantity(), Quantity::One);
977 assert_eq!(offer.signing_pubkey(), pubkey(42));
980 offer.as_tlv_stream(),
986 description: Some(&String::from("foo")),
988 absolute_expiry: None,
992 node_id: Some(&pubkey(42)),
996 if let Err(e) = Offer::try_from(buffer) {
997 panic!("error parsing offer: {:?}", e);
1002 fn builds_offer_with_chains() {
1003 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1004 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1006 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1007 .chain(Network::Bitcoin)
1010 assert!(offer.supports_chain(mainnet));
1011 assert_eq!(offer.chains(), vec![mainnet]);
1012 assert_eq!(offer.as_tlv_stream().chains, None);
1014 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1015 .chain(Network::Testnet)
1018 assert!(offer.supports_chain(testnet));
1019 assert_eq!(offer.chains(), vec![testnet]);
1020 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1022 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1023 .chain(Network::Testnet)
1024 .chain(Network::Testnet)
1027 assert!(offer.supports_chain(testnet));
1028 assert_eq!(offer.chains(), vec![testnet]);
1029 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1031 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1032 .chain(Network::Bitcoin)
1033 .chain(Network::Testnet)
1036 assert!(offer.supports_chain(mainnet));
1037 assert!(offer.supports_chain(testnet));
1038 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1039 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1043 fn builds_offer_with_metadata() {
1044 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1045 .metadata(vec![42; 32]).unwrap()
1048 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1049 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1051 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1052 .metadata(vec![42; 32]).unwrap()
1053 .metadata(vec![43; 32]).unwrap()
1056 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1057 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1061 fn builds_offer_with_metadata_derived() {
1062 let desc = "foo".to_string();
1063 let node_id = recipient_pubkey();
1064 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1065 let entropy = FixedEntropy {};
1066 let secp_ctx = Secp256k1::new();
1068 let offer = OfferBuilder
1069 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1072 assert_eq!(offer.signing_pubkey(), node_id);
1074 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1076 .sign(payer_sign).unwrap();
1077 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1079 // Fails verification with altered offer field
1080 let mut tlv_stream = offer.as_tlv_stream();
1081 tlv_stream.amount = Some(100);
1083 let mut encoded_offer = Vec::new();
1084 tlv_stream.write(&mut encoded_offer).unwrap();
1086 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1087 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1089 .sign(payer_sign).unwrap();
1090 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1092 // Fails verification with altered metadata
1093 let mut tlv_stream = offer.as_tlv_stream();
1094 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1095 tlv_stream.metadata = Some(&metadata);
1097 let mut encoded_offer = Vec::new();
1098 tlv_stream.write(&mut encoded_offer).unwrap();
1100 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1101 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1103 .sign(payer_sign).unwrap();
1104 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1108 fn builds_offer_with_derived_signing_pubkey() {
1109 let desc = "foo".to_string();
1110 let node_id = recipient_pubkey();
1111 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1112 let entropy = FixedEntropy {};
1113 let secp_ctx = Secp256k1::new();
1115 let blinded_path = BlindedPath {
1116 introduction_node_id: pubkey(40),
1117 blinding_point: pubkey(41),
1119 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1120 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1124 let offer = OfferBuilder
1125 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1129 assert_ne!(offer.signing_pubkey(), node_id);
1131 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1133 .sign(payer_sign).unwrap();
1134 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1136 // Fails verification with altered offer field
1137 let mut tlv_stream = offer.as_tlv_stream();
1138 tlv_stream.amount = Some(100);
1140 let mut encoded_offer = Vec::new();
1141 tlv_stream.write(&mut encoded_offer).unwrap();
1143 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1144 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1146 .sign(payer_sign).unwrap();
1147 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1149 // Fails verification with altered signing pubkey
1150 let mut tlv_stream = offer.as_tlv_stream();
1151 let signing_pubkey = pubkey(1);
1152 tlv_stream.node_id = Some(&signing_pubkey);
1154 let mut encoded_offer = Vec::new();
1155 tlv_stream.write(&mut encoded_offer).unwrap();
1157 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1158 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1160 .sign(payer_sign).unwrap();
1161 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1165 fn builds_offer_with_amount() {
1166 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1167 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1169 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1173 let tlv_stream = offer.as_tlv_stream();
1174 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1175 assert_eq!(tlv_stream.amount, Some(1000));
1176 assert_eq!(tlv_stream.currency, None);
1178 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1179 .amount(currency_amount.clone());
1180 let tlv_stream = builder.offer.as_tlv_stream();
1181 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1182 assert_eq!(tlv_stream.amount, Some(10));
1183 assert_eq!(tlv_stream.currency, Some(b"USD"));
1184 match builder.build() {
1185 Ok(_) => panic!("expected error"),
1186 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1189 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1190 .amount(currency_amount.clone())
1191 .amount(bitcoin_amount.clone())
1194 let tlv_stream = offer.as_tlv_stream();
1195 assert_eq!(tlv_stream.amount, Some(1000));
1196 assert_eq!(tlv_stream.currency, None);
1198 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1199 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1200 Ok(_) => panic!("expected error"),
1201 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1206 fn builds_offer_with_features() {
1207 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1208 .features_unchecked(OfferFeatures::unknown())
1211 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1212 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1214 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1215 .features_unchecked(OfferFeatures::unknown())
1216 .features_unchecked(OfferFeatures::empty())
1219 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1220 assert_eq!(offer.as_tlv_stream().features, None);
1224 fn builds_offer_with_absolute_expiry() {
1225 let future_expiry = Duration::from_secs(u64::max_value());
1226 let past_expiry = Duration::from_secs(0);
1227 let now = future_expiry - Duration::from_secs(1_000);
1229 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1230 .absolute_expiry(future_expiry)
1233 #[cfg(feature = "std")]
1234 assert!(!offer.is_expired());
1235 assert!(!offer.is_expired_no_std(now));
1236 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1237 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1239 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1240 .absolute_expiry(future_expiry)
1241 .absolute_expiry(past_expiry)
1244 #[cfg(feature = "std")]
1245 assert!(offer.is_expired());
1246 assert!(offer.is_expired_no_std(now));
1247 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1248 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1252 fn builds_offer_with_paths() {
1255 introduction_node_id: pubkey(40),
1256 blinding_point: pubkey(41),
1258 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1259 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1263 introduction_node_id: pubkey(40),
1264 blinding_point: pubkey(41),
1266 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1267 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1272 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1273 .path(paths[0].clone())
1274 .path(paths[1].clone())
1277 let tlv_stream = offer.as_tlv_stream();
1278 assert_eq!(offer.paths(), paths.as_slice());
1279 assert_eq!(offer.signing_pubkey(), pubkey(42));
1280 assert_ne!(pubkey(42), pubkey(44));
1281 assert_eq!(tlv_stream.paths, Some(&paths));
1282 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1286 fn builds_offer_with_issuer() {
1287 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1288 .issuer("bar".into())
1291 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1292 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1294 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1295 .issuer("bar".into())
1296 .issuer("baz".into())
1299 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1300 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1304 fn builds_offer_with_supported_quantity() {
1305 let one = NonZeroU64::new(1).unwrap();
1306 let ten = NonZeroU64::new(10).unwrap();
1308 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1309 .supported_quantity(Quantity::One)
1312 let tlv_stream = offer.as_tlv_stream();
1313 assert_eq!(offer.supported_quantity(), Quantity::One);
1314 assert_eq!(tlv_stream.quantity_max, None);
1316 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1317 .supported_quantity(Quantity::Unbounded)
1320 let tlv_stream = offer.as_tlv_stream();
1321 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1322 assert_eq!(tlv_stream.quantity_max, Some(0));
1324 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1325 .supported_quantity(Quantity::Bounded(ten))
1328 let tlv_stream = offer.as_tlv_stream();
1329 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1330 assert_eq!(tlv_stream.quantity_max, Some(10));
1332 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1333 .supported_quantity(Quantity::Bounded(one))
1336 let tlv_stream = offer.as_tlv_stream();
1337 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1338 assert_eq!(tlv_stream.quantity_max, Some(1));
1340 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1341 .supported_quantity(Quantity::Bounded(ten))
1342 .supported_quantity(Quantity::One)
1345 let tlv_stream = offer.as_tlv_stream();
1346 assert_eq!(offer.supported_quantity(), Quantity::One);
1347 assert_eq!(tlv_stream.quantity_max, None);
1351 fn fails_requesting_invoice_with_unknown_required_features() {
1352 match OfferBuilder::new("foo".into(), pubkey(42))
1353 .features_unchecked(OfferFeatures::unknown())
1355 .request_invoice(vec![1; 32], pubkey(43))
1357 Ok(_) => panic!("expected error"),
1358 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1363 fn parses_offer_with_chains() {
1364 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1365 .chain(Network::Bitcoin)
1366 .chain(Network::Testnet)
1369 if let Err(e) = offer.to_string().parse::<Offer>() {
1370 panic!("error parsing offer: {:?}", e);
1375 fn parses_offer_with_amount() {
1376 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1377 .amount(Amount::Bitcoin { amount_msats: 1000 })
1380 if let Err(e) = offer.to_string().parse::<Offer>() {
1381 panic!("error parsing offer: {:?}", e);
1384 let mut tlv_stream = offer.as_tlv_stream();
1385 tlv_stream.amount = Some(1000);
1386 tlv_stream.currency = Some(b"USD");
1388 let mut encoded_offer = Vec::new();
1389 tlv_stream.write(&mut encoded_offer).unwrap();
1391 if let Err(e) = Offer::try_from(encoded_offer) {
1392 panic!("error parsing offer: {:?}", e);
1395 let mut tlv_stream = offer.as_tlv_stream();
1396 tlv_stream.amount = None;
1397 tlv_stream.currency = Some(b"USD");
1399 let mut encoded_offer = Vec::new();
1400 tlv_stream.write(&mut encoded_offer).unwrap();
1402 match Offer::try_from(encoded_offer) {
1403 Ok(_) => panic!("expected error"),
1404 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1407 let mut tlv_stream = offer.as_tlv_stream();
1408 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1409 tlv_stream.currency = None;
1411 let mut encoded_offer = Vec::new();
1412 tlv_stream.write(&mut encoded_offer).unwrap();
1414 match Offer::try_from(encoded_offer) {
1415 Ok(_) => panic!("expected error"),
1416 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1421 fn parses_offer_with_description() {
1422 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1423 if let Err(e) = offer.to_string().parse::<Offer>() {
1424 panic!("error parsing offer: {:?}", e);
1427 let mut tlv_stream = offer.as_tlv_stream();
1428 tlv_stream.description = None;
1430 let mut encoded_offer = Vec::new();
1431 tlv_stream.write(&mut encoded_offer).unwrap();
1433 match Offer::try_from(encoded_offer) {
1434 Ok(_) => panic!("expected error"),
1436 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1442 fn parses_offer_with_paths() {
1443 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1445 introduction_node_id: pubkey(40),
1446 blinding_point: pubkey(41),
1448 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1449 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1453 introduction_node_id: pubkey(40),
1454 blinding_point: pubkey(41),
1456 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1457 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1462 if let Err(e) = offer.to_string().parse::<Offer>() {
1463 panic!("error parsing offer: {:?}", e);
1466 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1467 builder.offer.paths = Some(vec![]);
1469 let offer = builder.build().unwrap();
1470 if let Err(e) = offer.to_string().parse::<Offer>() {
1471 panic!("error parsing offer: {:?}", e);
1476 fn parses_offer_with_quantity() {
1477 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1478 .supported_quantity(Quantity::One)
1481 if let Err(e) = offer.to_string().parse::<Offer>() {
1482 panic!("error parsing offer: {:?}", e);
1485 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1486 .supported_quantity(Quantity::Unbounded)
1489 if let Err(e) = offer.to_string().parse::<Offer>() {
1490 panic!("error parsing offer: {:?}", e);
1493 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1494 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1497 if let Err(e) = offer.to_string().parse::<Offer>() {
1498 panic!("error parsing offer: {:?}", e);
1501 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1502 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1505 if let Err(e) = offer.to_string().parse::<Offer>() {
1506 panic!("error parsing offer: {:?}", e);
1511 fn parses_offer_with_node_id() {
1512 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1513 if let Err(e) = offer.to_string().parse::<Offer>() {
1514 panic!("error parsing offer: {:?}", e);
1517 let mut tlv_stream = offer.as_tlv_stream();
1518 tlv_stream.node_id = None;
1520 let mut encoded_offer = Vec::new();
1521 tlv_stream.write(&mut encoded_offer).unwrap();
1523 match Offer::try_from(encoded_offer) {
1524 Ok(_) => panic!("expected error"),
1526 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1532 fn fails_parsing_offer_with_extra_tlv_records() {
1533 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1535 let mut encoded_offer = Vec::new();
1536 offer.write(&mut encoded_offer).unwrap();
1537 BigSize(80).write(&mut encoded_offer).unwrap();
1538 BigSize(32).write(&mut encoded_offer).unwrap();
1539 [42u8; 32].write(&mut encoded_offer).unwrap();
1541 match Offer::try_from(encoded_offer) {
1542 Ok(_) => panic!("expected error"),
1543 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1550 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1551 use crate::ln::msgs::DecodeError;
1554 fn parses_bech32_encoded_offers() {
1556 // Minimal bolt12 offer
1557 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1560 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1562 // for bitcoin (redundant)
1563 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1565 // for bitcoin or liquidv1
1566 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1569 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1572 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1575 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1578 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1581 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1584 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1586 // with unlimited (or unknown) quantity
1587 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1589 // with single quantity (weird but valid)
1590 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1593 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1595 // with blinded path via Bob (0x424242...), blinding 020202...
1596 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1598 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1599 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1601 // unknown odd field
1602 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1604 for encoded_offer in &offers {
1605 if let Err(e) = encoded_offer.parse::<Offer>() {
1606 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1612 fn fails_parsing_bech32_encoded_offers() {
1613 // Malformed: fields out of order
1615 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1616 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1619 // Malformed: unknown even TLV type 78
1621 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1622 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1627 "lno1".parse::<Offer>(),
1628 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1631 // Malformed: truncated at type
1633 "lno1pg".parse::<Offer>(),
1634 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1637 // Malformed: truncated in length
1639 "lno1pt7s".parse::<Offer>(),
1640 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1643 // Malformed: truncated after length
1645 "lno1pgpq".parse::<Offer>(),
1646 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1649 // Malformed: truncated in description
1651 "lno1pgpyz".parse::<Offer>(),
1652 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1655 // Malformed: invalid offer_chains length
1657 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1658 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1661 // Malformed: truncated currency UTF-8
1663 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1664 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1667 // Malformed: invalid currency UTF-8
1669 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1670 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1673 // Malformed: truncated description UTF-8
1675 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1676 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1679 // Malformed: invalid description UTF-8
1681 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1682 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1685 // Malformed: truncated offer_paths
1687 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1688 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1691 // Malformed: zero num_hops in blinded_path
1693 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1694 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1697 // Malformed: truncated onionmsg_hop in blinded_path
1699 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1700 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1703 // Malformed: bad first_node_id in blinded_path
1705 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1706 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1709 // Malformed: bad blinding in blinded_path
1711 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1712 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1715 // Malformed: bad blinded_node_id in onionmsg_hop
1717 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1718 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1721 // Malformed: truncated issuer UTF-8
1723 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1724 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1727 // Malformed: invalid issuer UTF-8
1729 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1730 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1733 // Malformed: invalid offer_node_id
1735 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1736 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1739 // Contains type >= 80
1741 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1742 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1745 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1746 // Contains unknown feature 22
1748 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1751 // Missing offer_description
1753 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1754 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1757 // Missing offer_node_id"
1759 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1760 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),