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.
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
25 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
26 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
27 //! use lightning::offers::parse::Bolt12ParseError;
28 //! use lightning::util::ser::{Readable, Writeable};
30 //! # use lightning::blinded_path::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # #[cfg(feature = "std")]
38 //! # fn build() -> Result<(), Bolt12ParseError> {
39 //! let secp_ctx = Secp256k1::new();
40 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
41 //! let pubkey = PublicKey::from(keys);
43 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
44 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
45 //! .amount_msats(20_000)
46 //! .supported_quantity(Quantity::Unbounded)
47 //! .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
48 //! .issuer("Foo Bar".to_string())
49 //! .path(create_blinded_path())
50 //! .path(create_another_blinded_path())
53 //! // Encode as a bech32 string for use in a QR code.
54 //! let encoded_offer = offer.to_string();
56 //! // Parse from a bech32 string after scanning from a QR code.
57 //! let offer = encoded_offer.parse::<Offer>()?;
59 //! // Encode offer as raw bytes.
60 //! let mut bytes = Vec::new();
61 //! offer.write(&mut bytes).unwrap();
63 //! // Decode raw bytes into an offer.
64 //! let offer = Offer::try_from(bytes)?;
69 use bitcoin::blockdata::constants::ChainHash;
70 use bitcoin::network::constants::Network;
71 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
72 use core::convert::TryFrom;
73 use core::num::NonZeroU64;
75 use core::str::FromStr;
76 use core::time::Duration;
77 use crate::sign::EntropySource;
79 use crate::blinded_path::BlindedPath;
80 use crate::ln::channelmanager::PaymentId;
81 use crate::ln::features::OfferFeatures;
82 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
83 use crate::ln::msgs::MAX_VALUE_MSAT;
84 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
85 use crate::offers::merkle::TlvStream;
86 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
87 use crate::offers::signer::{Metadata, MetadataMaterial, self};
88 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
89 use crate::util::string::PrintableString;
91 use crate::prelude::*;
93 #[cfg(feature = "std")]
94 use std::time::SystemTime;
96 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
98 /// Builds an [`Offer`] for the "offer to be paid" flow.
100 /// See [module-level documentation] for usage.
102 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
104 /// [module-level documentation]: self
105 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
106 offer: OfferContents,
107 metadata_strategy: core::marker::PhantomData<M>,
108 secp_ctx: Option<&'a Secp256k1<T>>,
111 /// Indicates how [`Offer::metadata`] may be set.
113 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
114 pub trait MetadataStrategy {}
116 /// [`Offer::metadata`] may be explicitly set or left empty.
118 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
119 pub struct ExplicitMetadata {}
121 /// [`Offer::metadata`] will be derived.
123 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
124 pub struct DerivedMetadata {}
126 impl MetadataStrategy for ExplicitMetadata {}
127 impl MetadataStrategy for DerivedMetadata {}
129 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
130 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
131 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
132 /// while the offer is valid.
134 /// Use a different pubkey per offer to avoid correlating offers.
135 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
137 offer: OfferContents {
138 chains: None, metadata: None, amount: None, description,
139 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
140 supported_quantity: Quantity::One, signing_pubkey,
142 metadata_strategy: core::marker::PhantomData,
147 /// Sets the [`Offer::metadata`] to the given bytes.
149 /// Successive calls to this method will override the previous setting.
150 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, Bolt12SemanticError> {
151 self.offer.metadata = Some(Metadata::Bytes(metadata));
156 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
157 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
158 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
159 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
160 /// provided `node_id` is used for the signing pubkey.
162 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
163 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
166 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
167 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
168 pub fn deriving_signing_pubkey<ES: Deref>(
169 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
170 secp_ctx: &'a Secp256k1<T>
171 ) -> Self where ES::Target: EntropySource {
172 let nonce = Nonce::from_entropy_source(entropy_source);
173 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
174 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
176 offer: OfferContents {
177 chains: None, metadata: Some(metadata), amount: None, description,
178 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
179 supported_quantity: Quantity::One, signing_pubkey: node_id,
181 metadata_strategy: core::marker::PhantomData,
182 secp_ctx: Some(secp_ctx),
187 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
188 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
189 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
191 /// See [`Offer::chains`] on how this relates to the payment currency.
193 /// Successive calls to this method will add another chain hash.
194 pub fn chain(mut self, network: Network) -> Self {
195 let chains = self.offer.chains.get_or_insert_with(Vec::new);
196 let chain = ChainHash::using_genesis_block(network);
197 if !chains.contains(&chain) {
204 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
206 /// Successive calls to this method will override the previous setting.
207 pub fn amount_msats(self, amount_msats: u64) -> Self {
208 self.amount(Amount::Bitcoin { amount_msats })
211 /// Sets the [`Offer::amount`].
213 /// Successive calls to this method will override the previous setting.
214 pub(super) fn amount(mut self, amount: Amount) -> Self {
215 self.offer.amount = Some(amount);
219 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
220 /// already passed is valid and can be checked for using [`Offer::is_expired`].
222 /// Successive calls to this method will override the previous setting.
223 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
224 self.offer.absolute_expiry = Some(absolute_expiry);
228 /// Sets the [`Offer::issuer`].
230 /// Successive calls to this method will override the previous setting.
231 pub fn issuer(mut self, issuer: String) -> Self {
232 self.offer.issuer = Some(issuer);
236 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
237 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
239 /// Successive calls to this method will add another blinded path. Caller is responsible for not
240 /// adding duplicate paths.
241 pub fn path(mut self, path: BlindedPath) -> Self {
242 self.offer.paths.get_or_insert_with(Vec::new).push(path);
246 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
247 /// [`Quantity::One`].
249 /// Successive calls to this method will override the previous setting.
250 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
251 self.offer.supported_quantity = quantity;
255 /// Builds an [`Offer`] from the builder's settings.
256 pub fn build(mut self) -> Result<Offer, Bolt12SemanticError> {
257 match self.offer.amount {
258 Some(Amount::Bitcoin { amount_msats }) => {
259 if amount_msats > MAX_VALUE_MSAT {
260 return Err(Bolt12SemanticError::InvalidAmount);
263 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
267 if let Some(chains) = &self.offer.chains {
268 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
269 self.offer.chains = None;
273 Ok(self.build_without_checks())
276 fn build_without_checks(mut self) -> Offer {
277 // Create the metadata for stateless verification of an InvoiceRequest.
278 if let Some(mut metadata) = self.offer.metadata.take() {
279 if metadata.has_derivation_material() {
280 if self.offer.paths.is_none() {
281 metadata = metadata.without_keys();
284 let mut tlv_stream = self.offer.as_tlv_stream();
285 debug_assert_eq!(tlv_stream.metadata, None);
286 tlv_stream.metadata = None;
287 if metadata.derives_recipient_keys() {
288 tlv_stream.node_id = None;
291 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
292 metadata = derived_metadata;
293 if let Some(keys) = keys {
294 self.offer.signing_pubkey = keys.public_key();
298 self.offer.metadata = Some(metadata);
301 let mut bytes = Vec::new();
302 self.offer.write(&mut bytes).unwrap();
304 Offer { bytes, contents: self.offer }
309 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
310 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
311 self.offer.features = features;
315 pub(super) fn build_unchecked(self) -> Offer {
316 self.build_without_checks()
320 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
322 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
323 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
324 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
326 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
329 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
331 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
332 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
333 #[derive(Clone, Debug)]
334 #[cfg_attr(test, derive(PartialEq))]
336 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
338 pub(super) bytes: Vec<u8>,
339 pub(super) contents: OfferContents,
342 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
343 /// [`Bolt12Invoice`].
345 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
346 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
347 #[derive(Clone, Debug)]
348 #[cfg_attr(test, derive(PartialEq))]
349 pub(super) struct OfferContents {
350 chains: Option<Vec<ChainHash>>,
351 metadata: Option<Metadata>,
352 amount: Option<Amount>,
354 features: OfferFeatures,
355 absolute_expiry: Option<Duration>,
356 issuer: Option<String>,
357 paths: Option<Vec<BlindedPath>>,
358 supported_quantity: Quantity,
359 signing_pubkey: PublicKey,
362 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
363 // TODO: Return a slice once ChainHash has constants.
364 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
365 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
366 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
367 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
368 /// for the selected chain.
369 pub fn chains(&$self) -> Vec<$crate::bitcoin::blockdata::constants::ChainHash> {
373 // TODO: Link to corresponding method in `InvoiceRequest`.
374 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
375 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
376 pub fn metadata(&$self) -> Option<&Vec<u8>> {
380 /// The minimum amount required for a successful payment of a single item.
381 pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
385 /// A complete description of the purpose of the payment. Intended to be displayed to the user
386 /// but with the caveat that it has not been verified in any way.
387 pub fn description(&$self) -> $crate::util::string::PrintableString {
388 $contents.description()
391 /// Features pertaining to the offer.
392 pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
393 &$contents.features()
396 /// Duration since the Unix epoch when an invoice should no longer be requested.
398 /// If `None`, the offer does not expire.
399 pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
400 $contents.absolute_expiry()
403 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
404 /// displayed to the user but with the caveat that it has not been verified in any way.
405 pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
409 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
410 /// recipient privacy by obfuscating its node id.
411 pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
415 /// The quantity of items supported.
416 pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
417 $contents.supported_quantity()
420 /// The public key used by the recipient to sign invoices.
421 pub fn signing_pubkey(&$self) -> $crate::bitcoin::secp256k1::PublicKey {
422 $contents.signing_pubkey()
427 offer_accessors!(self, self.contents);
429 pub(super) fn implied_chain(&self) -> ChainHash {
430 self.contents.implied_chain()
433 /// Returns whether the given chain is supported by the offer.
434 pub fn supports_chain(&self, chain: ChainHash) -> bool {
435 self.contents.supports_chain(chain)
438 /// Whether the offer has expired.
439 #[cfg(feature = "std")]
440 pub fn is_expired(&self) -> bool {
441 self.contents.is_expired()
444 /// Returns whether the given quantity is valid for the offer.
445 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
446 self.contents.is_valid_quantity(quantity)
449 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
451 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
452 pub fn expects_quantity(&self) -> bool {
453 self.contents.expects_quantity()
456 /// Similar to [`Offer::request_invoice`] except it:
457 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
459 /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
460 /// such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
461 /// requested using a base [`ExpandedKey`] from which the payer id was derived, and
462 /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
463 /// be used when sending the payment for the requested invoice.
465 /// Useful to protect the sender's privacy.
467 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
469 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
470 /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
471 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
472 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
473 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
474 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>,
475 payment_id: PaymentId
476 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, Bolt12SemanticError>
478 ES::Target: EntropySource,
480 if self.offer_features().requires_unknown_bits() {
481 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
484 Ok(InvoiceRequestBuilder::deriving_payer_id(
485 self, expanded_key, entropy_source, secp_ctx, payment_id
489 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
490 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
492 /// Useful for recurring payments using the same `payer_id` with different invoices.
494 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
496 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
497 pub fn request_invoice_deriving_metadata<ES: Deref>(
498 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
499 payment_id: PaymentId
500 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError>
502 ES::Target: EntropySource,
504 if self.offer_features().requires_unknown_bits() {
505 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
508 Ok(InvoiceRequestBuilder::deriving_metadata(
509 self, payer_id, expanded_key, entropy_source, payment_id
513 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
514 /// which will be reflected in the `Bolt12Invoice` response.
516 /// The `metadata` is useful for including information about the derivation of `payer_id` such
517 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
518 /// hashing in the signature calculation.
520 /// This should not leak any information such as by using a simple BIP-32 derivation path.
521 /// Otherwise, payments may be correlated.
523 /// Errors if the offer contains unknown required features.
525 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
527 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
528 pub fn request_invoice(
529 &self, metadata: Vec<u8>, payer_id: PublicKey
530 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError> {
531 if self.offer_features().requires_unknown_bits() {
532 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
535 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
539 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
540 self.contents.as_tlv_stream()
544 impl AsRef<[u8]> for Offer {
545 fn as_ref(&self) -> &[u8] {
551 pub fn chains(&self) -> Vec<ChainHash> {
552 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
555 pub fn implied_chain(&self) -> ChainHash {
556 ChainHash::using_genesis_block(Network::Bitcoin)
559 pub fn supports_chain(&self, chain: ChainHash) -> bool {
560 self.chains().contains(&chain)
563 pub fn metadata(&self) -> Option<&Vec<u8>> {
564 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
567 pub fn amount(&self) -> Option<&Amount> {
571 pub fn description(&self) -> PrintableString {
572 PrintableString(&self.description)
575 pub fn features(&self) -> &OfferFeatures {
579 pub fn absolute_expiry(&self) -> Option<Duration> {
583 #[cfg(feature = "std")]
584 pub(super) fn is_expired(&self) -> bool {
585 match self.absolute_expiry {
586 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
587 Ok(elapsed) => elapsed > seconds_from_epoch,
594 pub fn issuer(&self) -> Option<PrintableString> {
595 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
598 pub fn paths(&self) -> &[BlindedPath] {
599 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
602 pub(super) fn check_amount_msats_for_quantity(
603 &self, amount_msats: Option<u64>, quantity: Option<u64>
604 ) -> Result<(), Bolt12SemanticError> {
605 let offer_amount_msats = match self.amount {
607 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
608 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
611 if !self.expects_quantity() || quantity.is_some() {
612 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
613 .ok_or(Bolt12SemanticError::InvalidAmount)?;
614 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
616 if amount_msats < expected_amount_msats {
617 return Err(Bolt12SemanticError::InsufficientAmount);
620 if amount_msats > MAX_VALUE_MSAT {
621 return Err(Bolt12SemanticError::InvalidAmount);
628 pub fn supported_quantity(&self) -> Quantity {
629 self.supported_quantity
632 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
633 let expects_quantity = self.expects_quantity();
635 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
636 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
637 Some(quantity) if !self.is_valid_quantity(quantity) => {
638 Err(Bolt12SemanticError::InvalidQuantity)
644 fn is_valid_quantity(&self, quantity: u64) -> bool {
645 match self.supported_quantity {
646 Quantity::Bounded(n) => quantity <= n.get(),
647 Quantity::Unbounded => quantity > 0,
648 Quantity::One => quantity == 1,
652 fn expects_quantity(&self) -> bool {
653 match self.supported_quantity {
654 Quantity::Bounded(_) => true,
655 Quantity::Unbounded => true,
656 Quantity::One => false,
660 pub(super) fn signing_pubkey(&self) -> PublicKey {
664 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
665 pub(super) fn verify<T: secp256k1::Signing>(
666 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
667 ) -> Result<Option<KeyPair>, ()> {
668 match self.metadata() {
670 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
671 match record.r#type {
672 OFFER_METADATA_TYPE => false,
673 OFFER_NODE_ID_TYPE => {
674 !self.metadata.as_ref().unwrap().derives_recipient_keys()
679 signer::verify_recipient_metadata(
680 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
687 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
688 let (currency, amount) = match &self.amount {
689 None => (None, None),
690 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
691 Some(Amount::Currency { iso4217_code, amount }) => (
692 Some(iso4217_code), Some(*amount)
697 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
701 chains: self.chains.as_ref(),
702 metadata: self.metadata(),
705 description: Some(&self.description),
707 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
708 paths: self.paths.as_ref(),
709 issuer: self.issuer.as_ref(),
710 quantity_max: self.supported_quantity.to_tlv_record(),
711 node_id: Some(&self.signing_pubkey),
716 impl Writeable for Offer {
717 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
718 WithoutLength(&self.bytes).write(writer)
722 impl Writeable for OfferContents {
723 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
724 self.as_tlv_stream().write(writer)
728 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
729 /// another currency.
730 #[derive(Clone, Debug, PartialEq)]
732 /// An amount of bitcoin.
734 /// The amount in millisatoshi.
737 /// An amount of currency specified using ISO 4712.
739 /// The currency that the amount is denominated in.
740 iso4217_code: CurrencyCode,
741 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
746 /// An ISO 4712 three-letter currency code (e.g., USD).
747 pub type CurrencyCode = [u8; 3];
749 /// Quantity of items supported by an [`Offer`].
750 #[derive(Clone, Copy, Debug, PartialEq)]
752 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
753 /// but is limited (e.g., because of per customer or inventory limits).
755 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
758 /// One or more items. Use when more than one item can be requested without any limit.
760 /// Only one item. Use when only a single item can be requested.
765 fn to_tlv_record(&self) -> Option<u64> {
767 Quantity::Bounded(n) => Some(n.get()),
768 Quantity::Unbounded => Some(0),
769 Quantity::One => None,
774 /// Valid type range for offer TLV records.
775 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
777 /// TLV record type for [`Offer::metadata`].
778 const OFFER_METADATA_TYPE: u64 = 4;
780 /// TLV record type for [`Offer::signing_pubkey`].
781 const OFFER_NODE_ID_TYPE: u64 = 22;
783 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
784 (2, chains: (Vec<ChainHash>, WithoutLength)),
785 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
786 (6, currency: CurrencyCode),
787 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
788 (10, description: (String, WithoutLength)),
789 (12, features: (OfferFeatures, WithoutLength)),
790 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
791 (16, paths: (Vec<BlindedPath>, WithoutLength)),
792 (18, issuer: (String, WithoutLength)),
793 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
794 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
797 impl Bech32Encode for Offer {
798 const BECH32_HRP: &'static str = "lno";
801 impl FromStr for Offer {
802 type Err = Bolt12ParseError;
804 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
805 Self::from_bech32_str(s)
809 impl TryFrom<Vec<u8>> for Offer {
810 type Error = Bolt12ParseError;
812 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
813 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
814 let ParsedMessage { bytes, tlv_stream } = offer;
815 let contents = OfferContents::try_from(tlv_stream)?;
816 Ok(Offer { bytes, contents })
820 impl TryFrom<OfferTlvStream> for OfferContents {
821 type Error = Bolt12SemanticError;
823 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
825 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
826 issuer, quantity_max, node_id,
829 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
831 let amount = match (currency, amount) {
832 (None, None) => None,
833 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
834 return Err(Bolt12SemanticError::InvalidAmount);
836 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
837 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
838 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
841 let description = match description {
842 None => return Err(Bolt12SemanticError::MissingDescription),
843 Some(description) => description,
846 let features = features.unwrap_or_else(OfferFeatures::empty);
848 let absolute_expiry = absolute_expiry
849 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
851 let supported_quantity = match quantity_max {
852 None => Quantity::One,
853 Some(0) => Quantity::Unbounded,
854 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
857 let signing_pubkey = match node_id {
858 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
859 Some(node_id) => node_id,
863 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
864 supported_quantity, signing_pubkey,
869 impl core::fmt::Display for Offer {
870 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
871 self.fmt_bech32_str(f)
877 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
879 use bitcoin::blockdata::constants::ChainHash;
880 use bitcoin::network::constants::Network;
881 use bitcoin::secp256k1::Secp256k1;
882 use core::convert::TryFrom;
883 use core::num::NonZeroU64;
884 use core::time::Duration;
885 use crate::blinded_path::{BlindedHop, BlindedPath};
886 use crate::sign::KeyMaterial;
887 use crate::ln::features::OfferFeatures;
888 use crate::ln::inbound_payment::ExpandedKey;
889 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
890 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
891 use crate::offers::test_utils::*;
892 use crate::util::ser::{BigSize, Writeable};
893 use crate::util::string::PrintableString;
896 fn builds_offer_with_defaults() {
897 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
899 let mut buffer = Vec::new();
900 offer.write(&mut buffer).unwrap();
902 assert_eq!(offer.bytes, buffer.as_slice());
903 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
904 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
905 assert_eq!(offer.metadata(), None);
906 assert_eq!(offer.amount(), None);
907 assert_eq!(offer.description(), PrintableString("foo"));
908 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
909 assert_eq!(offer.absolute_expiry(), None);
910 #[cfg(feature = "std")]
911 assert!(!offer.is_expired());
912 assert_eq!(offer.paths(), &[]);
913 assert_eq!(offer.issuer(), None);
914 assert_eq!(offer.supported_quantity(), Quantity::One);
915 assert_eq!(offer.signing_pubkey(), pubkey(42));
918 offer.as_tlv_stream(),
924 description: Some(&String::from("foo")),
926 absolute_expiry: None,
930 node_id: Some(&pubkey(42)),
934 if let Err(e) = Offer::try_from(buffer) {
935 panic!("error parsing offer: {:?}", e);
940 fn builds_offer_with_chains() {
941 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
942 let testnet = ChainHash::using_genesis_block(Network::Testnet);
944 let offer = OfferBuilder::new("foo".into(), pubkey(42))
945 .chain(Network::Bitcoin)
948 assert!(offer.supports_chain(mainnet));
949 assert_eq!(offer.chains(), vec![mainnet]);
950 assert_eq!(offer.as_tlv_stream().chains, None);
952 let offer = OfferBuilder::new("foo".into(), pubkey(42))
953 .chain(Network::Testnet)
956 assert!(offer.supports_chain(testnet));
957 assert_eq!(offer.chains(), vec![testnet]);
958 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
960 let offer = OfferBuilder::new("foo".into(), pubkey(42))
961 .chain(Network::Testnet)
962 .chain(Network::Testnet)
965 assert!(offer.supports_chain(testnet));
966 assert_eq!(offer.chains(), vec![testnet]);
967 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
969 let offer = OfferBuilder::new("foo".into(), pubkey(42))
970 .chain(Network::Bitcoin)
971 .chain(Network::Testnet)
974 assert!(offer.supports_chain(mainnet));
975 assert!(offer.supports_chain(testnet));
976 assert_eq!(offer.chains(), vec![mainnet, testnet]);
977 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
981 fn builds_offer_with_metadata() {
982 let offer = OfferBuilder::new("foo".into(), pubkey(42))
983 .metadata(vec![42; 32]).unwrap()
986 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
987 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
989 let offer = OfferBuilder::new("foo".into(), pubkey(42))
990 .metadata(vec![42; 32]).unwrap()
991 .metadata(vec![43; 32]).unwrap()
994 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
995 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
999 fn builds_offer_with_metadata_derived() {
1000 let desc = "foo".to_string();
1001 let node_id = recipient_pubkey();
1002 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1003 let entropy = FixedEntropy {};
1004 let secp_ctx = Secp256k1::new();
1006 let offer = OfferBuilder
1007 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1010 assert_eq!(offer.signing_pubkey(), node_id);
1012 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1014 .sign(payer_sign).unwrap();
1015 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1017 // Fails verification with altered offer field
1018 let mut tlv_stream = offer.as_tlv_stream();
1019 tlv_stream.amount = Some(100);
1021 let mut encoded_offer = Vec::new();
1022 tlv_stream.write(&mut encoded_offer).unwrap();
1024 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1025 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1027 .sign(payer_sign).unwrap();
1028 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1030 // Fails verification with altered metadata
1031 let mut tlv_stream = offer.as_tlv_stream();
1032 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1033 tlv_stream.metadata = Some(&metadata);
1035 let mut encoded_offer = Vec::new();
1036 tlv_stream.write(&mut encoded_offer).unwrap();
1038 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1039 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1041 .sign(payer_sign).unwrap();
1042 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1046 fn builds_offer_with_derived_signing_pubkey() {
1047 let desc = "foo".to_string();
1048 let node_id = recipient_pubkey();
1049 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1050 let entropy = FixedEntropy {};
1051 let secp_ctx = Secp256k1::new();
1053 let blinded_path = BlindedPath {
1054 introduction_node_id: pubkey(40),
1055 blinding_point: pubkey(41),
1057 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1058 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1062 let offer = OfferBuilder
1063 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1067 assert_ne!(offer.signing_pubkey(), node_id);
1069 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 .sign(payer_sign).unwrap();
1072 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1074 // Fails verification with altered offer field
1075 let mut tlv_stream = offer.as_tlv_stream();
1076 tlv_stream.amount = Some(100);
1078 let mut encoded_offer = Vec::new();
1079 tlv_stream.write(&mut encoded_offer).unwrap();
1081 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1082 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1084 .sign(payer_sign).unwrap();
1085 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1087 // Fails verification with altered signing pubkey
1088 let mut tlv_stream = offer.as_tlv_stream();
1089 let signing_pubkey = pubkey(1);
1090 tlv_stream.node_id = Some(&signing_pubkey);
1092 let mut encoded_offer = Vec::new();
1093 tlv_stream.write(&mut encoded_offer).unwrap();
1095 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1096 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1098 .sign(payer_sign).unwrap();
1099 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1103 fn builds_offer_with_amount() {
1104 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1105 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1107 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1111 let tlv_stream = offer.as_tlv_stream();
1112 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1113 assert_eq!(tlv_stream.amount, Some(1000));
1114 assert_eq!(tlv_stream.currency, None);
1116 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1117 .amount(currency_amount.clone());
1118 let tlv_stream = builder.offer.as_tlv_stream();
1119 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1120 assert_eq!(tlv_stream.amount, Some(10));
1121 assert_eq!(tlv_stream.currency, Some(b"USD"));
1122 match builder.build() {
1123 Ok(_) => panic!("expected error"),
1124 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1127 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1128 .amount(currency_amount.clone())
1129 .amount(bitcoin_amount.clone())
1132 let tlv_stream = offer.as_tlv_stream();
1133 assert_eq!(tlv_stream.amount, Some(1000));
1134 assert_eq!(tlv_stream.currency, None);
1136 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1137 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1138 Ok(_) => panic!("expected error"),
1139 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1144 fn builds_offer_with_features() {
1145 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1146 .features_unchecked(OfferFeatures::unknown())
1149 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1150 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1152 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1153 .features_unchecked(OfferFeatures::unknown())
1154 .features_unchecked(OfferFeatures::empty())
1157 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1158 assert_eq!(offer.as_tlv_stream().features, None);
1162 fn builds_offer_with_absolute_expiry() {
1163 let future_expiry = Duration::from_secs(u64::max_value());
1164 let past_expiry = Duration::from_secs(0);
1166 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1167 .absolute_expiry(future_expiry)
1170 #[cfg(feature = "std")]
1171 assert!(!offer.is_expired());
1172 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1173 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1175 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1176 .absolute_expiry(future_expiry)
1177 .absolute_expiry(past_expiry)
1180 #[cfg(feature = "std")]
1181 assert!(offer.is_expired());
1182 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1183 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1187 fn builds_offer_with_paths() {
1190 introduction_node_id: pubkey(40),
1191 blinding_point: pubkey(41),
1193 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1194 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1198 introduction_node_id: pubkey(40),
1199 blinding_point: pubkey(41),
1201 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1202 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1207 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1208 .path(paths[0].clone())
1209 .path(paths[1].clone())
1212 let tlv_stream = offer.as_tlv_stream();
1213 assert_eq!(offer.paths(), paths.as_slice());
1214 assert_eq!(offer.signing_pubkey(), pubkey(42));
1215 assert_ne!(pubkey(42), pubkey(44));
1216 assert_eq!(tlv_stream.paths, Some(&paths));
1217 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1221 fn builds_offer_with_issuer() {
1222 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1223 .issuer("bar".into())
1226 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1227 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1229 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1230 .issuer("bar".into())
1231 .issuer("baz".into())
1234 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1235 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1239 fn builds_offer_with_supported_quantity() {
1240 let one = NonZeroU64::new(1).unwrap();
1241 let ten = NonZeroU64::new(10).unwrap();
1243 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1244 .supported_quantity(Quantity::One)
1247 let tlv_stream = offer.as_tlv_stream();
1248 assert_eq!(offer.supported_quantity(), Quantity::One);
1249 assert_eq!(tlv_stream.quantity_max, None);
1251 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1252 .supported_quantity(Quantity::Unbounded)
1255 let tlv_stream = offer.as_tlv_stream();
1256 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1257 assert_eq!(tlv_stream.quantity_max, Some(0));
1259 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1260 .supported_quantity(Quantity::Bounded(ten))
1263 let tlv_stream = offer.as_tlv_stream();
1264 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1265 assert_eq!(tlv_stream.quantity_max, Some(10));
1267 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1268 .supported_quantity(Quantity::Bounded(one))
1271 let tlv_stream = offer.as_tlv_stream();
1272 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1273 assert_eq!(tlv_stream.quantity_max, Some(1));
1275 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1276 .supported_quantity(Quantity::Bounded(ten))
1277 .supported_quantity(Quantity::One)
1280 let tlv_stream = offer.as_tlv_stream();
1281 assert_eq!(offer.supported_quantity(), Quantity::One);
1282 assert_eq!(tlv_stream.quantity_max, None);
1286 fn fails_requesting_invoice_with_unknown_required_features() {
1287 match OfferBuilder::new("foo".into(), pubkey(42))
1288 .features_unchecked(OfferFeatures::unknown())
1290 .request_invoice(vec![1; 32], pubkey(43))
1292 Ok(_) => panic!("expected error"),
1293 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1298 fn parses_offer_with_chains() {
1299 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1300 .chain(Network::Bitcoin)
1301 .chain(Network::Testnet)
1304 if let Err(e) = offer.to_string().parse::<Offer>() {
1305 panic!("error parsing offer: {:?}", e);
1310 fn parses_offer_with_amount() {
1311 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1312 .amount(Amount::Bitcoin { amount_msats: 1000 })
1315 if let Err(e) = offer.to_string().parse::<Offer>() {
1316 panic!("error parsing offer: {:?}", e);
1319 let mut tlv_stream = offer.as_tlv_stream();
1320 tlv_stream.amount = Some(1000);
1321 tlv_stream.currency = Some(b"USD");
1323 let mut encoded_offer = Vec::new();
1324 tlv_stream.write(&mut encoded_offer).unwrap();
1326 if let Err(e) = Offer::try_from(encoded_offer) {
1327 panic!("error parsing offer: {:?}", e);
1330 let mut tlv_stream = offer.as_tlv_stream();
1331 tlv_stream.amount = None;
1332 tlv_stream.currency = Some(b"USD");
1334 let mut encoded_offer = Vec::new();
1335 tlv_stream.write(&mut encoded_offer).unwrap();
1337 match Offer::try_from(encoded_offer) {
1338 Ok(_) => panic!("expected error"),
1339 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1342 let mut tlv_stream = offer.as_tlv_stream();
1343 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1344 tlv_stream.currency = None;
1346 let mut encoded_offer = Vec::new();
1347 tlv_stream.write(&mut encoded_offer).unwrap();
1349 match Offer::try_from(encoded_offer) {
1350 Ok(_) => panic!("expected error"),
1351 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1356 fn parses_offer_with_description() {
1357 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1358 if let Err(e) = offer.to_string().parse::<Offer>() {
1359 panic!("error parsing offer: {:?}", e);
1362 let mut tlv_stream = offer.as_tlv_stream();
1363 tlv_stream.description = None;
1365 let mut encoded_offer = Vec::new();
1366 tlv_stream.write(&mut encoded_offer).unwrap();
1368 match Offer::try_from(encoded_offer) {
1369 Ok(_) => panic!("expected error"),
1371 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1377 fn parses_offer_with_paths() {
1378 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1380 introduction_node_id: pubkey(40),
1381 blinding_point: pubkey(41),
1383 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1384 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1388 introduction_node_id: pubkey(40),
1389 blinding_point: pubkey(41),
1391 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1392 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1397 if let Err(e) = offer.to_string().parse::<Offer>() {
1398 panic!("error parsing offer: {:?}", e);
1401 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1402 builder.offer.paths = Some(vec![]);
1404 let offer = builder.build().unwrap();
1405 if let Err(e) = offer.to_string().parse::<Offer>() {
1406 panic!("error parsing offer: {:?}", e);
1411 fn parses_offer_with_quantity() {
1412 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1413 .supported_quantity(Quantity::One)
1416 if let Err(e) = offer.to_string().parse::<Offer>() {
1417 panic!("error parsing offer: {:?}", e);
1420 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1421 .supported_quantity(Quantity::Unbounded)
1424 if let Err(e) = offer.to_string().parse::<Offer>() {
1425 panic!("error parsing offer: {:?}", e);
1428 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1429 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1432 if let Err(e) = offer.to_string().parse::<Offer>() {
1433 panic!("error parsing offer: {:?}", e);
1436 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1437 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1440 if let Err(e) = offer.to_string().parse::<Offer>() {
1441 panic!("error parsing offer: {:?}", e);
1446 fn parses_offer_with_node_id() {
1447 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1448 if let Err(e) = offer.to_string().parse::<Offer>() {
1449 panic!("error parsing offer: {:?}", e);
1452 let mut tlv_stream = offer.as_tlv_stream();
1453 tlv_stream.node_id = None;
1455 let mut encoded_offer = Vec::new();
1456 tlv_stream.write(&mut encoded_offer).unwrap();
1458 match Offer::try_from(encoded_offer) {
1459 Ok(_) => panic!("expected error"),
1461 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1467 fn fails_parsing_offer_with_extra_tlv_records() {
1468 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1470 let mut encoded_offer = Vec::new();
1471 offer.write(&mut encoded_offer).unwrap();
1472 BigSize(80).write(&mut encoded_offer).unwrap();
1473 BigSize(32).write(&mut encoded_offer).unwrap();
1474 [42u8; 32].write(&mut encoded_offer).unwrap();
1476 match Offer::try_from(encoded_offer) {
1477 Ok(_) => panic!("expected error"),
1478 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1485 use super::{Bolt12ParseError, Offer};
1486 use bitcoin::bech32;
1487 use crate::ln::msgs::DecodeError;
1490 fn encodes_offer_as_bech32_without_checksum() {
1491 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
1492 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1493 let reencoded_offer = offer.to_string();
1494 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1495 assert_eq!(reencoded_offer, encoded_offer);
1499 fn parses_bech32_encoded_offers() {
1501 // BOLT 12 test vectors
1502 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1503 "l+no1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1504 "lno1pqps7sjqpgt+yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+5k7msjzfpy7nz5yqcn+ygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+5xvxg",
1505 "lno1pqps7sjqpgt+ yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+ 5k7msjzfpy7nz5yqcn+\nygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+\r\n 5xvxg",
1507 for encoded_offer in &offers {
1508 if let Err(e) = encoded_offer.parse::<Offer>() {
1509 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1515 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1517 // BOLT 12 test vectors
1518 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+",
1519 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+ ",
1520 "+lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1521 "+ lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1522 "ln++o1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1524 for encoded_offer in &offers {
1525 match encoded_offer.parse::<Offer>() {
1526 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1527 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidContinuation),
1534 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1535 let encoded_offer = "lni1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
1536 match encoded_offer.parse::<Offer>() {
1537 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1538 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidBech32Hrp),
1543 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1544 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxo";
1545 match encoded_offer.parse::<Offer>() {
1546 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1547 Err(e) => assert_eq!(e, Bolt12ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1552 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1553 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxgqqqqq";
1554 match encoded_offer.parse::<Offer>() {
1555 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1556 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),