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::hash::{Hash, Hasher};
84 use core::num::NonZeroU64;
86 use core::str::FromStr;
87 use core::time::Duration;
88 use crate::sign::EntropySource;
90 use crate::blinded_path::BlindedPath;
91 use crate::ln::channelmanager::PaymentId;
92 use crate::ln::features::OfferFeatures;
93 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
94 use crate::ln::msgs::MAX_VALUE_MSAT;
95 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
96 use crate::offers::merkle::TlvStream;
97 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
98 use crate::offers::signer::{Metadata, MetadataMaterial, self};
99 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
100 use crate::util::string::PrintableString;
102 use crate::prelude::*;
104 #[cfg(feature = "std")]
105 use std::time::SystemTime;
107 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
109 /// Builds an [`Offer`] for the "offer to be paid" flow.
111 /// See [module-level documentation] for usage.
113 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
115 /// [module-level documentation]: self
116 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
117 offer: OfferContents,
118 metadata_strategy: core::marker::PhantomData<M>,
119 secp_ctx: Option<&'a Secp256k1<T>>,
122 /// Indicates how [`Offer::metadata`] may be set.
124 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
125 pub trait MetadataStrategy {}
127 /// [`Offer::metadata`] may be explicitly set or left empty.
129 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
130 pub struct ExplicitMetadata {}
132 /// [`Offer::metadata`] will be derived.
134 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
135 pub struct DerivedMetadata {}
137 impl MetadataStrategy for ExplicitMetadata {}
138 impl MetadataStrategy for DerivedMetadata {}
140 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
141 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
142 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
143 /// while the offer is valid.
145 /// Use a different pubkey per offer to avoid correlating offers.
149 /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
150 /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
152 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
153 /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
154 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
156 offer: OfferContents {
157 chains: None, metadata: None, amount: None, description,
158 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
159 supported_quantity: Quantity::One, signing_pubkey,
161 metadata_strategy: core::marker::PhantomData,
166 /// Sets the [`Offer::metadata`] to the given bytes.
168 /// Successive calls to this method will override the previous setting.
169 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, Bolt12SemanticError> {
170 self.offer.metadata = Some(Metadata::Bytes(metadata));
175 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
176 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
177 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
178 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
179 /// provided `node_id` is used for the signing pubkey.
181 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
182 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
185 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
186 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
187 pub fn deriving_signing_pubkey<ES: Deref>(
188 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
189 secp_ctx: &'a Secp256k1<T>
190 ) -> Self where ES::Target: EntropySource {
191 let nonce = Nonce::from_entropy_source(entropy_source);
192 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
193 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
195 offer: OfferContents {
196 chains: None, metadata: Some(metadata), amount: None, description,
197 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
198 supported_quantity: Quantity::One, signing_pubkey: node_id,
200 metadata_strategy: core::marker::PhantomData,
201 secp_ctx: Some(secp_ctx),
206 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
207 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
208 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
210 /// See [`Offer::chains`] on how this relates to the payment currency.
212 /// Successive calls to this method will add another chain hash.
213 pub fn chain(self, network: Network) -> Self {
214 self.chain_hash(ChainHash::using_genesis_block(network))
217 /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
218 /// [`Network::Bitcoin`] is assumed to be the only one supported.
220 /// See [`Offer::chains`] on how this relates to the payment currency.
222 /// Successive calls to this method will add another chain hash.
223 pub(crate) fn chain_hash(mut self, chain: ChainHash) -> Self {
224 let chains = self.offer.chains.get_or_insert_with(Vec::new);
225 if !chains.contains(&chain) {
232 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
234 /// Successive calls to this method will override the previous setting.
235 pub fn amount_msats(self, amount_msats: u64) -> Self {
236 self.amount(Amount::Bitcoin { amount_msats })
239 /// Sets the [`Offer::amount`].
241 /// Successive calls to this method will override the previous setting.
242 pub(super) fn amount(mut self, amount: Amount) -> Self {
243 self.offer.amount = Some(amount);
247 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
248 /// already passed is valid and can be checked for using [`Offer::is_expired`].
250 /// Successive calls to this method will override the previous setting.
251 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
252 self.offer.absolute_expiry = Some(absolute_expiry);
256 /// Sets the [`Offer::issuer`].
258 /// Successive calls to this method will override the previous setting.
259 pub fn issuer(mut self, issuer: String) -> Self {
260 self.offer.issuer = Some(issuer);
264 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
265 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
267 /// Successive calls to this method will add another blinded path. Caller is responsible for not
268 /// adding duplicate paths.
269 pub fn path(mut self, path: BlindedPath) -> Self {
270 self.offer.paths.get_or_insert_with(Vec::new).push(path);
274 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
275 /// [`Quantity::One`].
277 /// Successive calls to this method will override the previous setting.
278 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
279 self.offer.supported_quantity = quantity;
283 /// Builds an [`Offer`] from the builder's settings.
284 pub fn build(mut self) -> Result<Offer, Bolt12SemanticError> {
285 match self.offer.amount {
286 Some(Amount::Bitcoin { amount_msats }) => {
287 if amount_msats > MAX_VALUE_MSAT {
288 return Err(Bolt12SemanticError::InvalidAmount);
291 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
295 if let Some(chains) = &self.offer.chains {
296 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
297 self.offer.chains = None;
301 Ok(self.build_without_checks())
304 fn build_without_checks(mut self) -> Offer {
305 // Create the metadata for stateless verification of an InvoiceRequest.
306 if let Some(mut metadata) = self.offer.metadata.take() {
307 if metadata.has_derivation_material() {
308 if self.offer.paths.is_none() {
309 metadata = metadata.without_keys();
312 let mut tlv_stream = self.offer.as_tlv_stream();
313 debug_assert_eq!(tlv_stream.metadata, None);
314 tlv_stream.metadata = None;
315 if metadata.derives_recipient_keys() {
316 tlv_stream.node_id = None;
319 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
320 metadata = derived_metadata;
321 if let Some(keys) = keys {
322 self.offer.signing_pubkey = keys.public_key();
326 self.offer.metadata = Some(metadata);
329 let mut bytes = Vec::new();
330 self.offer.write(&mut bytes).unwrap();
332 Offer { bytes, contents: self.offer }
337 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
338 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
339 self.offer.features = features;
343 pub(crate) fn clear_paths(mut self) -> Self {
344 self.offer.paths = None;
348 pub(super) fn build_unchecked(self) -> Offer {
349 self.build_without_checks()
353 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
355 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
356 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
357 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
359 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
362 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
364 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
365 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
366 #[derive(Clone, Debug)]
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] {
587 impl PartialEq for Offer {
588 fn eq(&self, other: &Self) -> bool {
589 self.bytes.eq(&other.bytes)
595 impl Hash for Offer {
596 fn hash<H: Hasher>(&self, state: &mut H) {
597 self.bytes.hash(state);
602 pub fn chains(&self) -> Vec<ChainHash> {
603 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
606 pub fn implied_chain(&self) -> ChainHash {
607 ChainHash::using_genesis_block(Network::Bitcoin)
610 pub fn supports_chain(&self, chain: ChainHash) -> bool {
611 self.chains().contains(&chain)
614 pub fn metadata(&self) -> Option<&Vec<u8>> {
615 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
618 pub fn amount(&self) -> Option<&Amount> {
622 pub fn description(&self) -> PrintableString {
623 PrintableString(&self.description)
626 pub fn features(&self) -> &OfferFeatures {
630 pub fn absolute_expiry(&self) -> Option<Duration> {
634 #[cfg(feature = "std")]
635 pub(super) fn is_expired(&self) -> bool {
636 SystemTime::UNIX_EPOCH
638 .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
642 pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
644 .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
648 pub fn issuer(&self) -> Option<PrintableString> {
649 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
652 pub fn paths(&self) -> &[BlindedPath] {
653 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
656 pub(super) fn check_amount_msats_for_quantity(
657 &self, amount_msats: Option<u64>, quantity: Option<u64>
658 ) -> Result<(), Bolt12SemanticError> {
659 let offer_amount_msats = match self.amount {
661 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
662 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
665 if !self.expects_quantity() || quantity.is_some() {
666 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
667 .ok_or(Bolt12SemanticError::InvalidAmount)?;
668 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
670 if amount_msats < expected_amount_msats {
671 return Err(Bolt12SemanticError::InsufficientAmount);
674 if amount_msats > MAX_VALUE_MSAT {
675 return Err(Bolt12SemanticError::InvalidAmount);
682 pub fn supported_quantity(&self) -> Quantity {
683 self.supported_quantity
686 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
687 let expects_quantity = self.expects_quantity();
689 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
690 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
691 Some(quantity) if !self.is_valid_quantity(quantity) => {
692 Err(Bolt12SemanticError::InvalidQuantity)
698 fn is_valid_quantity(&self, quantity: u64) -> bool {
699 match self.supported_quantity {
700 Quantity::Bounded(n) => quantity <= n.get(),
701 Quantity::Unbounded => quantity > 0,
702 Quantity::One => quantity == 1,
706 fn expects_quantity(&self) -> bool {
707 match self.supported_quantity {
708 Quantity::Bounded(_) => true,
709 Quantity::Unbounded => true,
710 Quantity::One => false,
714 pub(super) fn signing_pubkey(&self) -> PublicKey {
718 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
719 pub(super) fn verify<T: secp256k1::Signing>(
720 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
721 ) -> Result<Option<KeyPair>, ()> {
722 match self.metadata() {
724 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
725 match record.r#type {
726 OFFER_METADATA_TYPE => false,
727 OFFER_NODE_ID_TYPE => {
728 !self.metadata.as_ref().unwrap().derives_recipient_keys()
733 signer::verify_recipient_metadata(
734 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
741 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
742 let (currency, amount) = match &self.amount {
743 None => (None, None),
744 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
745 Some(Amount::Currency { iso4217_code, amount }) => (
746 Some(iso4217_code), Some(*amount)
751 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
755 chains: self.chains.as_ref(),
756 metadata: self.metadata(),
759 description: Some(&self.description),
761 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
762 paths: self.paths.as_ref(),
763 issuer: self.issuer.as_ref(),
764 quantity_max: self.supported_quantity.to_tlv_record(),
765 node_id: Some(&self.signing_pubkey),
770 impl Writeable for Offer {
771 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
772 WithoutLength(&self.bytes).write(writer)
776 impl Writeable for OfferContents {
777 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
778 self.as_tlv_stream().write(writer)
782 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
783 /// another currency.
784 #[derive(Clone, Debug, PartialEq)]
786 /// An amount of bitcoin.
788 /// The amount in millisatoshi.
791 /// An amount of currency specified using ISO 4712.
793 /// The currency that the amount is denominated in.
794 iso4217_code: CurrencyCode,
795 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
800 /// An ISO 4712 three-letter currency code (e.g., USD).
801 pub type CurrencyCode = [u8; 3];
803 /// Quantity of items supported by an [`Offer`].
804 #[derive(Clone, Copy, Debug, PartialEq)]
806 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
807 /// but is limited (e.g., because of per customer or inventory limits).
809 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
812 /// One or more items. Use when more than one item can be requested without any limit.
814 /// Only one item. Use when only a single item can be requested.
819 fn to_tlv_record(&self) -> Option<u64> {
821 Quantity::Bounded(n) => Some(n.get()),
822 Quantity::Unbounded => Some(0),
823 Quantity::One => None,
828 /// Valid type range for offer TLV records.
829 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
831 /// TLV record type for [`Offer::metadata`].
832 const OFFER_METADATA_TYPE: u64 = 4;
834 /// TLV record type for [`Offer::signing_pubkey`].
835 const OFFER_NODE_ID_TYPE: u64 = 22;
837 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
838 (2, chains: (Vec<ChainHash>, WithoutLength)),
839 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
840 (6, currency: CurrencyCode),
841 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
842 (10, description: (String, WithoutLength)),
843 (12, features: (OfferFeatures, WithoutLength)),
844 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
845 (16, paths: (Vec<BlindedPath>, WithoutLength)),
846 (18, issuer: (String, WithoutLength)),
847 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
848 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
851 impl Bech32Encode for Offer {
852 const BECH32_HRP: &'static str = "lno";
855 impl FromStr for Offer {
856 type Err = Bolt12ParseError;
858 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
859 Self::from_bech32_str(s)
863 impl TryFrom<Vec<u8>> for Offer {
864 type Error = Bolt12ParseError;
866 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
867 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
868 let ParsedMessage { bytes, tlv_stream } = offer;
869 let contents = OfferContents::try_from(tlv_stream)?;
870 Ok(Offer { bytes, contents })
874 impl TryFrom<OfferTlvStream> for OfferContents {
875 type Error = Bolt12SemanticError;
877 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
879 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
880 issuer, quantity_max, node_id,
883 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
885 let amount = match (currency, amount) {
886 (None, None) => None,
887 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
888 return Err(Bolt12SemanticError::InvalidAmount);
890 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
891 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
892 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
895 let description = match description {
896 None => return Err(Bolt12SemanticError::MissingDescription),
897 Some(description) => description,
900 let features = features.unwrap_or_else(OfferFeatures::empty);
902 let absolute_expiry = absolute_expiry
903 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
905 let supported_quantity = match quantity_max {
906 None => Quantity::One,
907 Some(0) => Quantity::Unbounded,
908 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
911 let signing_pubkey = match node_id {
912 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
913 Some(node_id) => node_id,
917 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
918 supported_quantity, signing_pubkey,
923 impl core::fmt::Display for Offer {
924 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
925 self.fmt_bech32_str(f)
931 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
933 use bitcoin::blockdata::constants::ChainHash;
934 use bitcoin::network::constants::Network;
935 use bitcoin::secp256k1::Secp256k1;
936 use core::convert::TryFrom;
937 use core::num::NonZeroU64;
938 use core::time::Duration;
939 use crate::blinded_path::{BlindedHop, BlindedPath};
940 use crate::sign::KeyMaterial;
941 use crate::ln::features::OfferFeatures;
942 use crate::ln::inbound_payment::ExpandedKey;
943 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
944 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
945 use crate::offers::test_utils::*;
946 use crate::util::ser::{BigSize, Writeable};
947 use crate::util::string::PrintableString;
950 fn builds_offer_with_defaults() {
951 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
953 let mut buffer = Vec::new();
954 offer.write(&mut buffer).unwrap();
956 assert_eq!(offer.bytes, buffer.as_slice());
957 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
958 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
959 assert_eq!(offer.metadata(), None);
960 assert_eq!(offer.amount(), None);
961 assert_eq!(offer.description(), PrintableString("foo"));
962 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
963 assert_eq!(offer.absolute_expiry(), None);
964 #[cfg(feature = "std")]
965 assert!(!offer.is_expired());
966 assert_eq!(offer.paths(), &[]);
967 assert_eq!(offer.issuer(), None);
968 assert_eq!(offer.supported_quantity(), Quantity::One);
969 assert_eq!(offer.signing_pubkey(), pubkey(42));
972 offer.as_tlv_stream(),
978 description: Some(&String::from("foo")),
980 absolute_expiry: None,
984 node_id: Some(&pubkey(42)),
988 if let Err(e) = Offer::try_from(buffer) {
989 panic!("error parsing offer: {:?}", e);
994 fn builds_offer_with_chains() {
995 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
996 let testnet = ChainHash::using_genesis_block(Network::Testnet);
998 let offer = OfferBuilder::new("foo".into(), pubkey(42))
999 .chain(Network::Bitcoin)
1002 assert!(offer.supports_chain(mainnet));
1003 assert_eq!(offer.chains(), vec![mainnet]);
1004 assert_eq!(offer.as_tlv_stream().chains, None);
1006 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1007 .chain(Network::Testnet)
1010 assert!(offer.supports_chain(testnet));
1011 assert_eq!(offer.chains(), vec![testnet]);
1012 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1014 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1015 .chain(Network::Testnet)
1016 .chain(Network::Testnet)
1019 assert!(offer.supports_chain(testnet));
1020 assert_eq!(offer.chains(), vec![testnet]);
1021 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1023 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1024 .chain(Network::Bitcoin)
1025 .chain(Network::Testnet)
1028 assert!(offer.supports_chain(mainnet));
1029 assert!(offer.supports_chain(testnet));
1030 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1031 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1035 fn builds_offer_with_metadata() {
1036 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1037 .metadata(vec![42; 32]).unwrap()
1040 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1041 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1043 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1044 .metadata(vec![42; 32]).unwrap()
1045 .metadata(vec![43; 32]).unwrap()
1048 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1049 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1053 fn builds_offer_with_metadata_derived() {
1054 let desc = "foo".to_string();
1055 let node_id = recipient_pubkey();
1056 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1057 let entropy = FixedEntropy {};
1058 let secp_ctx = Secp256k1::new();
1060 let offer = OfferBuilder
1061 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1064 assert_eq!(offer.signing_pubkey(), node_id);
1066 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1068 .sign(payer_sign).unwrap();
1069 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1071 // Fails verification with altered offer field
1072 let mut tlv_stream = offer.as_tlv_stream();
1073 tlv_stream.amount = Some(100);
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());
1084 // Fails verification with altered metadata
1085 let mut tlv_stream = offer.as_tlv_stream();
1086 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1087 tlv_stream.metadata = Some(&metadata);
1089 let mut encoded_offer = Vec::new();
1090 tlv_stream.write(&mut encoded_offer).unwrap();
1092 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1093 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1095 .sign(payer_sign).unwrap();
1096 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1100 fn builds_offer_with_derived_signing_pubkey() {
1101 let desc = "foo".to_string();
1102 let node_id = recipient_pubkey();
1103 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1104 let entropy = FixedEntropy {};
1105 let secp_ctx = Secp256k1::new();
1107 let blinded_path = BlindedPath {
1108 introduction_node_id: pubkey(40),
1109 blinding_point: pubkey(41),
1111 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1112 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1116 let offer = OfferBuilder
1117 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1121 assert_ne!(offer.signing_pubkey(), node_id);
1123 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1125 .sign(payer_sign).unwrap();
1126 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1128 // Fails verification with altered offer field
1129 let mut tlv_stream = offer.as_tlv_stream();
1130 tlv_stream.amount = Some(100);
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());
1141 // Fails verification with altered signing pubkey
1142 let mut tlv_stream = offer.as_tlv_stream();
1143 let signing_pubkey = pubkey(1);
1144 tlv_stream.node_id = Some(&signing_pubkey);
1146 let mut encoded_offer = Vec::new();
1147 tlv_stream.write(&mut encoded_offer).unwrap();
1149 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1150 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1152 .sign(payer_sign).unwrap();
1153 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1157 fn builds_offer_with_amount() {
1158 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1159 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1161 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1165 let tlv_stream = offer.as_tlv_stream();
1166 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1167 assert_eq!(tlv_stream.amount, Some(1000));
1168 assert_eq!(tlv_stream.currency, None);
1170 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1171 .amount(currency_amount.clone());
1172 let tlv_stream = builder.offer.as_tlv_stream();
1173 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1174 assert_eq!(tlv_stream.amount, Some(10));
1175 assert_eq!(tlv_stream.currency, Some(b"USD"));
1176 match builder.build() {
1177 Ok(_) => panic!("expected error"),
1178 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1181 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1182 .amount(currency_amount.clone())
1183 .amount(bitcoin_amount.clone())
1186 let tlv_stream = offer.as_tlv_stream();
1187 assert_eq!(tlv_stream.amount, Some(1000));
1188 assert_eq!(tlv_stream.currency, None);
1190 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1191 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1192 Ok(_) => panic!("expected error"),
1193 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1198 fn builds_offer_with_features() {
1199 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1200 .features_unchecked(OfferFeatures::unknown())
1203 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1204 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1206 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1207 .features_unchecked(OfferFeatures::unknown())
1208 .features_unchecked(OfferFeatures::empty())
1211 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1212 assert_eq!(offer.as_tlv_stream().features, None);
1216 fn builds_offer_with_absolute_expiry() {
1217 let future_expiry = Duration::from_secs(u64::max_value());
1218 let past_expiry = Duration::from_secs(0);
1219 let now = future_expiry - Duration::from_secs(1_000);
1221 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1222 .absolute_expiry(future_expiry)
1225 #[cfg(feature = "std")]
1226 assert!(!offer.is_expired());
1227 assert!(!offer.is_expired_no_std(now));
1228 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1229 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1231 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1232 .absolute_expiry(future_expiry)
1233 .absolute_expiry(past_expiry)
1236 #[cfg(feature = "std")]
1237 assert!(offer.is_expired());
1238 assert!(offer.is_expired_no_std(now));
1239 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1240 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1244 fn builds_offer_with_paths() {
1247 introduction_node_id: pubkey(40),
1248 blinding_point: pubkey(41),
1250 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1251 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1255 introduction_node_id: pubkey(40),
1256 blinding_point: pubkey(41),
1258 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1259 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1264 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1265 .path(paths[0].clone())
1266 .path(paths[1].clone())
1269 let tlv_stream = offer.as_tlv_stream();
1270 assert_eq!(offer.paths(), paths.as_slice());
1271 assert_eq!(offer.signing_pubkey(), pubkey(42));
1272 assert_ne!(pubkey(42), pubkey(44));
1273 assert_eq!(tlv_stream.paths, Some(&paths));
1274 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1278 fn builds_offer_with_issuer() {
1279 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1280 .issuer("bar".into())
1283 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1284 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1286 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1287 .issuer("bar".into())
1288 .issuer("baz".into())
1291 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1292 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1296 fn builds_offer_with_supported_quantity() {
1297 let one = NonZeroU64::new(1).unwrap();
1298 let ten = NonZeroU64::new(10).unwrap();
1300 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1301 .supported_quantity(Quantity::One)
1304 let tlv_stream = offer.as_tlv_stream();
1305 assert_eq!(offer.supported_quantity(), Quantity::One);
1306 assert_eq!(tlv_stream.quantity_max, None);
1308 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1309 .supported_quantity(Quantity::Unbounded)
1312 let tlv_stream = offer.as_tlv_stream();
1313 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1314 assert_eq!(tlv_stream.quantity_max, Some(0));
1316 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1317 .supported_quantity(Quantity::Bounded(ten))
1320 let tlv_stream = offer.as_tlv_stream();
1321 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1322 assert_eq!(tlv_stream.quantity_max, Some(10));
1324 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1325 .supported_quantity(Quantity::Bounded(one))
1328 let tlv_stream = offer.as_tlv_stream();
1329 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1330 assert_eq!(tlv_stream.quantity_max, Some(1));
1332 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1333 .supported_quantity(Quantity::Bounded(ten))
1334 .supported_quantity(Quantity::One)
1337 let tlv_stream = offer.as_tlv_stream();
1338 assert_eq!(offer.supported_quantity(), Quantity::One);
1339 assert_eq!(tlv_stream.quantity_max, None);
1343 fn fails_requesting_invoice_with_unknown_required_features() {
1344 match OfferBuilder::new("foo".into(), pubkey(42))
1345 .features_unchecked(OfferFeatures::unknown())
1347 .request_invoice(vec![1; 32], pubkey(43))
1349 Ok(_) => panic!("expected error"),
1350 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1355 fn parses_offer_with_chains() {
1356 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1357 .chain(Network::Bitcoin)
1358 .chain(Network::Testnet)
1361 if let Err(e) = offer.to_string().parse::<Offer>() {
1362 panic!("error parsing offer: {:?}", e);
1367 fn parses_offer_with_amount() {
1368 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1369 .amount(Amount::Bitcoin { amount_msats: 1000 })
1372 if let Err(e) = offer.to_string().parse::<Offer>() {
1373 panic!("error parsing offer: {:?}", e);
1376 let mut tlv_stream = offer.as_tlv_stream();
1377 tlv_stream.amount = Some(1000);
1378 tlv_stream.currency = Some(b"USD");
1380 let mut encoded_offer = Vec::new();
1381 tlv_stream.write(&mut encoded_offer).unwrap();
1383 if let Err(e) = Offer::try_from(encoded_offer) {
1384 panic!("error parsing offer: {:?}", e);
1387 let mut tlv_stream = offer.as_tlv_stream();
1388 tlv_stream.amount = None;
1389 tlv_stream.currency = Some(b"USD");
1391 let mut encoded_offer = Vec::new();
1392 tlv_stream.write(&mut encoded_offer).unwrap();
1394 match Offer::try_from(encoded_offer) {
1395 Ok(_) => panic!("expected error"),
1396 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1399 let mut tlv_stream = offer.as_tlv_stream();
1400 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1401 tlv_stream.currency = None;
1403 let mut encoded_offer = Vec::new();
1404 tlv_stream.write(&mut encoded_offer).unwrap();
1406 match Offer::try_from(encoded_offer) {
1407 Ok(_) => panic!("expected error"),
1408 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1413 fn parses_offer_with_description() {
1414 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1415 if let Err(e) = offer.to_string().parse::<Offer>() {
1416 panic!("error parsing offer: {:?}", e);
1419 let mut tlv_stream = offer.as_tlv_stream();
1420 tlv_stream.description = None;
1422 let mut encoded_offer = Vec::new();
1423 tlv_stream.write(&mut encoded_offer).unwrap();
1425 match Offer::try_from(encoded_offer) {
1426 Ok(_) => panic!("expected error"),
1428 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1434 fn parses_offer_with_paths() {
1435 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1437 introduction_node_id: pubkey(40),
1438 blinding_point: pubkey(41),
1440 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1441 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1445 introduction_node_id: pubkey(40),
1446 blinding_point: pubkey(41),
1448 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1449 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1454 if let Err(e) = offer.to_string().parse::<Offer>() {
1455 panic!("error parsing offer: {:?}", e);
1458 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1459 builder.offer.paths = Some(vec![]);
1461 let offer = builder.build().unwrap();
1462 if let Err(e) = offer.to_string().parse::<Offer>() {
1463 panic!("error parsing offer: {:?}", e);
1468 fn parses_offer_with_quantity() {
1469 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1470 .supported_quantity(Quantity::One)
1473 if let Err(e) = offer.to_string().parse::<Offer>() {
1474 panic!("error parsing offer: {:?}", e);
1477 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1478 .supported_quantity(Quantity::Unbounded)
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::Bounded(NonZeroU64::new(10).unwrap()))
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(1).unwrap()))
1497 if let Err(e) = offer.to_string().parse::<Offer>() {
1498 panic!("error parsing offer: {:?}", e);
1503 fn parses_offer_with_node_id() {
1504 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1505 if let Err(e) = offer.to_string().parse::<Offer>() {
1506 panic!("error parsing offer: {:?}", e);
1509 let mut tlv_stream = offer.as_tlv_stream();
1510 tlv_stream.node_id = None;
1512 let mut encoded_offer = Vec::new();
1513 tlv_stream.write(&mut encoded_offer).unwrap();
1515 match Offer::try_from(encoded_offer) {
1516 Ok(_) => panic!("expected error"),
1518 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1524 fn fails_parsing_offer_with_extra_tlv_records() {
1525 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1527 let mut encoded_offer = Vec::new();
1528 offer.write(&mut encoded_offer).unwrap();
1529 BigSize(80).write(&mut encoded_offer).unwrap();
1530 BigSize(32).write(&mut encoded_offer).unwrap();
1531 [42u8; 32].write(&mut encoded_offer).unwrap();
1533 match Offer::try_from(encoded_offer) {
1534 Ok(_) => panic!("expected error"),
1535 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1542 use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1543 use crate::ln::msgs::DecodeError;
1546 fn parses_bech32_encoded_offers() {
1548 // Minimal bolt12 offer
1549 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1552 "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1554 // for bitcoin (redundant)
1555 "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1557 // for bitcoin or liquidv1
1558 "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1561 "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1564 "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1567 "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1570 "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1573 "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1576 "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1578 // with unlimited (or unknown) quantity
1579 "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1581 // with single quantity (weird but valid)
1582 "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1585 "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1587 // with blinded path via Bob (0x424242...), blinding 020202...
1588 "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1590 // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1591 "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1593 // unknown odd field
1594 "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1596 for encoded_offer in &offers {
1597 if let Err(e) = encoded_offer.parse::<Offer>() {
1598 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1604 fn fails_parsing_bech32_encoded_offers() {
1605 // Malformed: fields out of order
1607 "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1608 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1611 // Malformed: unknown even TLV type 78
1613 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1614 Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1619 "lno1".parse::<Offer>(),
1620 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1623 // Malformed: truncated at type
1625 "lno1pg".parse::<Offer>(),
1626 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1629 // Malformed: truncated in length
1631 "lno1pt7s".parse::<Offer>(),
1632 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1635 // Malformed: truncated after length
1637 "lno1pgpq".parse::<Offer>(),
1638 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1641 // Malformed: truncated in description
1643 "lno1pgpyz".parse::<Offer>(),
1644 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1647 // Malformed: invalid offer_chains length
1649 "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1650 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1653 // Malformed: truncated currency UTF-8
1655 "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1656 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1659 // Malformed: invalid currency UTF-8
1661 "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1662 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1665 // Malformed: truncated description UTF-8
1667 "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1668 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1671 // Malformed: invalid description UTF-8
1673 "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1674 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1677 // Malformed: truncated offer_paths
1679 "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1680 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1683 // Malformed: zero num_hops in blinded_path
1685 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1686 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1689 // Malformed: truncated onionmsg_hop in blinded_path
1691 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1692 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1695 // Malformed: bad first_node_id in blinded_path
1697 "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1698 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1701 // Malformed: bad blinding in blinded_path
1703 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1704 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1707 // Malformed: bad blinded_node_id in onionmsg_hop
1709 "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1710 Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1713 // Malformed: truncated issuer UTF-8
1715 "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1716 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1719 // Malformed: invalid issuer UTF-8
1721 "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1722 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1725 // Malformed: invalid offer_node_id
1727 "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1728 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1731 // Contains type >= 80
1733 "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1734 Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1737 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1738 // Contains unknown feature 22
1740 "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1743 // Missing offer_description
1745 "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1746 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1749 // Missing offer_node_id"
1751 "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1752 Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),