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::features::OfferFeatures;
81 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
82 use crate::ln::msgs::MAX_VALUE_MSAT;
83 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
84 use crate::offers::merkle::TlvStream;
85 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
86 use crate::offers::signer::{Metadata, MetadataMaterial, self};
87 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
88 use crate::util::string::PrintableString;
90 use crate::prelude::*;
92 #[cfg(feature = "std")]
93 use std::time::SystemTime;
95 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
97 /// Builds an [`Offer`] for the "offer to be paid" flow.
99 /// See [module-level documentation] for usage.
101 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
103 /// [module-level documentation]: self
104 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
105 offer: OfferContents,
106 metadata_strategy: core::marker::PhantomData<M>,
107 secp_ctx: Option<&'a Secp256k1<T>>,
110 /// Indicates how [`Offer::metadata`] may be set.
112 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
113 pub trait MetadataStrategy {}
115 /// [`Offer::metadata`] may be explicitly set or left empty.
117 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
118 pub struct ExplicitMetadata {}
120 /// [`Offer::metadata`] will be derived.
122 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
123 pub struct DerivedMetadata {}
125 impl MetadataStrategy for ExplicitMetadata {}
126 impl MetadataStrategy for DerivedMetadata {}
128 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
129 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
130 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
131 /// while the offer is valid.
133 /// Use a different pubkey per offer to avoid correlating offers.
134 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
136 offer: OfferContents {
137 chains: None, metadata: None, amount: None, description,
138 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
139 supported_quantity: Quantity::One, signing_pubkey,
141 metadata_strategy: core::marker::PhantomData,
146 /// Sets the [`Offer::metadata`] to the given bytes.
148 /// Successive calls to this method will override the previous setting.
149 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, Bolt12SemanticError> {
150 self.offer.metadata = Some(Metadata::Bytes(metadata));
155 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
156 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
157 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
158 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
159 /// provided `node_id` is used for the signing pubkey.
161 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
162 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
165 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
166 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
167 pub fn deriving_signing_pubkey<ES: Deref>(
168 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
169 secp_ctx: &'a Secp256k1<T>
170 ) -> Self where ES::Target: EntropySource {
171 let nonce = Nonce::from_entropy_source(entropy_source);
172 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
173 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
175 offer: OfferContents {
176 chains: None, metadata: Some(metadata), amount: None, description,
177 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
178 supported_quantity: Quantity::One, signing_pubkey: node_id,
180 metadata_strategy: core::marker::PhantomData,
181 secp_ctx: Some(secp_ctx),
186 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
187 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
188 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
190 /// See [`Offer::chains`] on how this relates to the payment currency.
192 /// Successive calls to this method will add another chain hash.
193 pub fn chain(mut self, network: Network) -> Self {
194 let chains = self.offer.chains.get_or_insert_with(Vec::new);
195 let chain = ChainHash::using_genesis_block(network);
196 if !chains.contains(&chain) {
203 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
205 /// Successive calls to this method will override the previous setting.
206 pub fn amount_msats(self, amount_msats: u64) -> Self {
207 self.amount(Amount::Bitcoin { amount_msats })
210 /// Sets the [`Offer::amount`].
212 /// Successive calls to this method will override the previous setting.
213 pub(super) fn amount(mut self, amount: Amount) -> Self {
214 self.offer.amount = Some(amount);
218 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
219 /// already passed is valid and can be checked for using [`Offer::is_expired`].
221 /// Successive calls to this method will override the previous setting.
222 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
223 self.offer.absolute_expiry = Some(absolute_expiry);
227 /// Sets the [`Offer::issuer`].
229 /// Successive calls to this method will override the previous setting.
230 pub fn issuer(mut self, issuer: String) -> Self {
231 self.offer.issuer = Some(issuer);
235 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
236 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
238 /// Successive calls to this method will add another blinded path. Caller is responsible for not
239 /// adding duplicate paths.
240 pub fn path(mut self, path: BlindedPath) -> Self {
241 self.offer.paths.get_or_insert_with(Vec::new).push(path);
245 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
246 /// [`Quantity::One`].
248 /// Successive calls to this method will override the previous setting.
249 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
250 self.offer.supported_quantity = quantity;
254 /// Builds an [`Offer`] from the builder's settings.
255 pub fn build(mut self) -> Result<Offer, Bolt12SemanticError> {
256 match self.offer.amount {
257 Some(Amount::Bitcoin { amount_msats }) => {
258 if amount_msats > MAX_VALUE_MSAT {
259 return Err(Bolt12SemanticError::InvalidAmount);
262 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
266 if let Some(chains) = &self.offer.chains {
267 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
268 self.offer.chains = None;
272 Ok(self.build_without_checks())
275 fn build_without_checks(mut self) -> Offer {
276 // Create the metadata for stateless verification of an InvoiceRequest.
277 if let Some(mut metadata) = self.offer.metadata.take() {
278 if metadata.has_derivation_material() {
279 if self.offer.paths.is_none() {
280 metadata = metadata.without_keys();
283 let mut tlv_stream = self.offer.as_tlv_stream();
284 debug_assert_eq!(tlv_stream.metadata, None);
285 tlv_stream.metadata = None;
286 if metadata.derives_keys() {
287 tlv_stream.node_id = None;
290 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
291 metadata = derived_metadata;
292 if let Some(keys) = keys {
293 self.offer.signing_pubkey = keys.public_key();
297 self.offer.metadata = Some(metadata);
300 let mut bytes = Vec::new();
301 self.offer.write(&mut bytes).unwrap();
303 Offer { bytes, contents: self.offer }
308 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
309 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
310 self.offer.features = features;
314 pub(super) fn build_unchecked(self) -> Offer {
315 self.build_without_checks()
319 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
321 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
322 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
323 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
325 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
328 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
330 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
331 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
332 #[derive(Clone, Debug)]
333 #[cfg_attr(test, derive(PartialEq))]
335 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
337 pub(super) bytes: Vec<u8>,
338 pub(super) contents: OfferContents,
341 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
342 /// [`Bolt12Invoice`].
344 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
345 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
346 #[derive(Clone, Debug)]
347 #[cfg_attr(test, derive(PartialEq))]
348 pub(super) struct OfferContents {
349 chains: Option<Vec<ChainHash>>,
350 metadata: Option<Metadata>,
351 amount: Option<Amount>,
353 features: OfferFeatures,
354 absolute_expiry: Option<Duration>,
355 issuer: Option<String>,
356 paths: Option<Vec<BlindedPath>>,
357 supported_quantity: Quantity,
358 signing_pubkey: PublicKey,
362 // TODO: Return a slice once ChainHash has constants.
363 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
364 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
365 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
366 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
367 /// for the selected chain.
368 pub fn chains(&self) -> Vec<ChainHash> {
369 self.contents.chains()
372 pub(super) fn implied_chain(&self) -> ChainHash {
373 self.contents.implied_chain()
376 /// Returns whether the given chain is supported by the offer.
377 pub fn supports_chain(&self, chain: ChainHash) -> bool {
378 self.contents.supports_chain(chain)
381 // TODO: Link to corresponding method in `InvoiceRequest`.
382 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
383 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
384 pub fn metadata(&self) -> Option<&Vec<u8>> {
385 self.contents.metadata()
388 /// The minimum amount required for a successful payment of a single item.
389 pub fn amount(&self) -> Option<&Amount> {
390 self.contents.amount()
393 /// A complete description of the purpose of the payment. Intended to be displayed to the user
394 /// but with the caveat that it has not been verified in any way.
395 pub fn description(&self) -> PrintableString {
396 self.contents.description()
399 /// Features pertaining to the offer.
400 pub fn features(&self) -> &OfferFeatures {
401 &self.contents.features
404 /// Duration since the Unix epoch when an invoice should no longer be requested.
406 /// If `None`, the offer does not expire.
407 pub fn absolute_expiry(&self) -> Option<Duration> {
408 self.contents.absolute_expiry
411 /// Whether the offer has expired.
412 #[cfg(feature = "std")]
413 pub fn is_expired(&self) -> bool {
414 self.contents.is_expired()
417 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
418 /// displayed to the user but with the caveat that it has not been verified in any way.
419 pub fn issuer(&self) -> Option<PrintableString> {
420 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
423 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
424 /// recipient privacy by obfuscating its node id.
425 pub fn paths(&self) -> &[BlindedPath] {
426 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
429 /// The quantity of items supported.
430 pub fn supported_quantity(&self) -> Quantity {
431 self.contents.supported_quantity()
434 /// Returns whether the given quantity is valid for the offer.
435 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
436 self.contents.is_valid_quantity(quantity)
439 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
441 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
442 pub fn expects_quantity(&self) -> bool {
443 self.contents.expects_quantity()
446 /// The public key used by the recipient to sign invoices.
447 pub fn signing_pubkey(&self) -> PublicKey {
448 self.contents.signing_pubkey()
451 /// Similar to [`Offer::request_invoice`] except it:
452 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
454 /// - sets the [`InvoiceRequest::metadata`] when [`InvoiceRequestBuilder::build`] is called such
455 /// that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was requested
456 /// using a base [`ExpandedKey`] from which the payer id was derived.
458 /// Useful to protect the sender's privacy.
460 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
462 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
463 /// [`InvoiceRequest::metadata`]: crate::offers::invoice_request::InvoiceRequest::metadata
464 /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
465 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
466 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
467 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
468 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, Bolt12SemanticError>
470 ES::Target: EntropySource,
472 if self.features().requires_unknown_bits() {
473 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
476 Ok(InvoiceRequestBuilder::deriving_payer_id(self, expanded_key, entropy_source, secp_ctx))
479 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
480 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
482 /// Useful for recurring payments using the same `payer_id` with different invoices.
484 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
486 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
487 pub fn request_invoice_deriving_metadata<ES: Deref>(
488 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
489 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError>
491 ES::Target: EntropySource,
493 if self.features().requires_unknown_bits() {
494 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
497 Ok(InvoiceRequestBuilder::deriving_metadata(self, payer_id, expanded_key, entropy_source))
500 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
501 /// which will be reflected in the `Bolt12Invoice` response.
503 /// The `metadata` is useful for including information about the derivation of `payer_id` such
504 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
505 /// hashing in the signature calculation.
507 /// This should not leak any information such as by using a simple BIP-32 derivation path.
508 /// Otherwise, payments may be correlated.
510 /// Errors if the offer contains unknown required features.
512 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
514 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
515 pub fn request_invoice(
516 &self, metadata: Vec<u8>, payer_id: PublicKey
517 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, Bolt12SemanticError> {
518 if self.features().requires_unknown_bits() {
519 return Err(Bolt12SemanticError::UnknownRequiredFeatures);
522 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
526 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
527 self.contents.as_tlv_stream()
531 impl AsRef<[u8]> for Offer {
532 fn as_ref(&self) -> &[u8] {
538 pub fn chains(&self) -> Vec<ChainHash> {
539 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
542 pub fn implied_chain(&self) -> ChainHash {
543 ChainHash::using_genesis_block(Network::Bitcoin)
546 pub fn supports_chain(&self, chain: ChainHash) -> bool {
547 self.chains().contains(&chain)
550 pub fn metadata(&self) -> Option<&Vec<u8>> {
551 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
554 pub fn description(&self) -> PrintableString {
555 PrintableString(&self.description)
558 #[cfg(feature = "std")]
559 pub(super) fn is_expired(&self) -> bool {
560 match self.absolute_expiry {
561 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
562 Ok(elapsed) => elapsed > seconds_from_epoch,
569 pub fn amount(&self) -> Option<&Amount> {
573 pub(super) fn check_amount_msats_for_quantity(
574 &self, amount_msats: Option<u64>, quantity: Option<u64>
575 ) -> Result<(), Bolt12SemanticError> {
576 let offer_amount_msats = match self.amount {
578 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
579 Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
582 if !self.expects_quantity() || quantity.is_some() {
583 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
584 .ok_or(Bolt12SemanticError::InvalidAmount)?;
585 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
587 if amount_msats < expected_amount_msats {
588 return Err(Bolt12SemanticError::InsufficientAmount);
591 if amount_msats > MAX_VALUE_MSAT {
592 return Err(Bolt12SemanticError::InvalidAmount);
599 pub fn supported_quantity(&self) -> Quantity {
600 self.supported_quantity
603 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
604 let expects_quantity = self.expects_quantity();
606 None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
607 Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
608 Some(quantity) if !self.is_valid_quantity(quantity) => {
609 Err(Bolt12SemanticError::InvalidQuantity)
615 fn is_valid_quantity(&self, quantity: u64) -> bool {
616 match self.supported_quantity {
617 Quantity::Bounded(n) => quantity <= n.get(),
618 Quantity::Unbounded => quantity > 0,
619 Quantity::One => quantity == 1,
623 fn expects_quantity(&self) -> bool {
624 match self.supported_quantity {
625 Quantity::Bounded(_) => true,
626 Quantity::Unbounded => true,
627 Quantity::One => false,
631 pub(super) fn signing_pubkey(&self) -> PublicKey {
635 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
636 pub(super) fn verify<T: secp256k1::Signing>(
637 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
638 ) -> Result<Option<KeyPair>, ()> {
639 match self.metadata() {
641 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
642 match record.r#type {
643 OFFER_METADATA_TYPE => false,
644 OFFER_NODE_ID_TYPE => !self.metadata.as_ref().unwrap().derives_keys(),
648 signer::verify_metadata(
649 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
656 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
657 let (currency, amount) = match &self.amount {
658 None => (None, None),
659 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
660 Some(Amount::Currency { iso4217_code, amount }) => (
661 Some(iso4217_code), Some(*amount)
666 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
670 chains: self.chains.as_ref(),
671 metadata: self.metadata(),
674 description: Some(&self.description),
676 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
677 paths: self.paths.as_ref(),
678 issuer: self.issuer.as_ref(),
679 quantity_max: self.supported_quantity.to_tlv_record(),
680 node_id: Some(&self.signing_pubkey),
685 impl Writeable for Offer {
686 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
687 WithoutLength(&self.bytes).write(writer)
691 impl Writeable for OfferContents {
692 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
693 self.as_tlv_stream().write(writer)
697 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
698 /// another currency.
699 #[derive(Clone, Debug, PartialEq)]
701 /// An amount of bitcoin.
703 /// The amount in millisatoshi.
706 /// An amount of currency specified using ISO 4712.
708 /// The currency that the amount is denominated in.
710 /// This is not exported to bindings users as bindings have troubles with type aliases to
712 iso4217_code: CurrencyCode,
713 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
718 /// An ISO 4712 three-letter currency code (e.g., USD).
719 pub(crate) type CurrencyCode = [u8; 3];
721 /// Quantity of items supported by an [`Offer`].
722 #[derive(Clone, Copy, Debug, PartialEq)]
724 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
725 /// but is limited (e.g., because of per customer or inventory limits).
727 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
729 Bounded(/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
731 /// One or more items. Use when more than one item can be requested without any limit.
733 /// Only one item. Use when only a single item can be requested.
738 fn to_tlv_record(&self) -> Option<u64> {
740 Quantity::Bounded(n) => Some(n.get()),
741 Quantity::Unbounded => Some(0),
742 Quantity::One => None,
747 /// Valid type range for offer TLV records.
748 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
750 /// TLV record type for [`Offer::metadata`].
751 const OFFER_METADATA_TYPE: u64 = 4;
753 /// TLV record type for [`Offer::signing_pubkey`].
754 const OFFER_NODE_ID_TYPE: u64 = 22;
756 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
757 (2, chains: (Vec<ChainHash>, WithoutLength)),
758 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
759 (6, currency: CurrencyCode),
760 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
761 (10, description: (String, WithoutLength)),
762 (12, features: (OfferFeatures, WithoutLength)),
763 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
764 (16, paths: (Vec<BlindedPath>, WithoutLength)),
765 (18, issuer: (String, WithoutLength)),
766 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
767 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
770 impl Bech32Encode for Offer {
771 const BECH32_HRP: &'static str = "lno";
774 impl FromStr for Offer {
775 type Err = Bolt12ParseError;
777 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
778 Self::from_bech32_str(s)
782 impl TryFrom<Vec<u8>> for Offer {
783 type Error = Bolt12ParseError;
785 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
786 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
787 let ParsedMessage { bytes, tlv_stream } = offer;
788 let contents = OfferContents::try_from(tlv_stream)?;
789 Ok(Offer { bytes, contents })
793 impl TryFrom<OfferTlvStream> for OfferContents {
794 type Error = Bolt12SemanticError;
796 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
798 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
799 issuer, quantity_max, node_id,
802 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
804 let amount = match (currency, amount) {
805 (None, None) => None,
806 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
807 return Err(Bolt12SemanticError::InvalidAmount);
809 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
810 (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
811 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
814 let description = match description {
815 None => return Err(Bolt12SemanticError::MissingDescription),
816 Some(description) => description,
819 let features = features.unwrap_or_else(OfferFeatures::empty);
821 let absolute_expiry = absolute_expiry
822 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
824 let supported_quantity = match quantity_max {
825 None => Quantity::One,
826 Some(0) => Quantity::Unbounded,
827 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
830 let signing_pubkey = match node_id {
831 None => return Err(Bolt12SemanticError::MissingSigningPubkey),
832 Some(node_id) => node_id,
836 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
837 supported_quantity, signing_pubkey,
842 impl core::fmt::Display for Offer {
843 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
844 self.fmt_bech32_str(f)
850 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
852 use bitcoin::blockdata::constants::ChainHash;
853 use bitcoin::network::constants::Network;
854 use bitcoin::secp256k1::Secp256k1;
855 use core::convert::TryFrom;
856 use core::num::NonZeroU64;
857 use core::time::Duration;
858 use crate::blinded_path::{BlindedHop, BlindedPath};
859 use crate::sign::KeyMaterial;
860 use crate::ln::features::OfferFeatures;
861 use crate::ln::inbound_payment::ExpandedKey;
862 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
863 use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
864 use crate::offers::test_utils::*;
865 use crate::util::ser::{BigSize, Writeable};
866 use crate::util::string::PrintableString;
869 fn builds_offer_with_defaults() {
870 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
872 let mut buffer = Vec::new();
873 offer.write(&mut buffer).unwrap();
875 assert_eq!(offer.bytes, buffer.as_slice());
876 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
877 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
878 assert_eq!(offer.metadata(), None);
879 assert_eq!(offer.amount(), None);
880 assert_eq!(offer.description(), PrintableString("foo"));
881 assert_eq!(offer.features(), &OfferFeatures::empty());
882 assert_eq!(offer.absolute_expiry(), None);
883 #[cfg(feature = "std")]
884 assert!(!offer.is_expired());
885 assert_eq!(offer.paths(), &[]);
886 assert_eq!(offer.issuer(), None);
887 assert_eq!(offer.supported_quantity(), Quantity::One);
888 assert_eq!(offer.signing_pubkey(), pubkey(42));
891 offer.as_tlv_stream(),
897 description: Some(&String::from("foo")),
899 absolute_expiry: None,
903 node_id: Some(&pubkey(42)),
907 if let Err(e) = Offer::try_from(buffer) {
908 panic!("error parsing offer: {:?}", e);
913 fn builds_offer_with_chains() {
914 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
915 let testnet = ChainHash::using_genesis_block(Network::Testnet);
917 let offer = OfferBuilder::new("foo".into(), pubkey(42))
918 .chain(Network::Bitcoin)
921 assert!(offer.supports_chain(mainnet));
922 assert_eq!(offer.chains(), vec![mainnet]);
923 assert_eq!(offer.as_tlv_stream().chains, None);
925 let offer = OfferBuilder::new("foo".into(), pubkey(42))
926 .chain(Network::Testnet)
929 assert!(offer.supports_chain(testnet));
930 assert_eq!(offer.chains(), vec![testnet]);
931 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
933 let offer = OfferBuilder::new("foo".into(), pubkey(42))
934 .chain(Network::Testnet)
935 .chain(Network::Testnet)
938 assert!(offer.supports_chain(testnet));
939 assert_eq!(offer.chains(), vec![testnet]);
940 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
942 let offer = OfferBuilder::new("foo".into(), pubkey(42))
943 .chain(Network::Bitcoin)
944 .chain(Network::Testnet)
947 assert!(offer.supports_chain(mainnet));
948 assert!(offer.supports_chain(testnet));
949 assert_eq!(offer.chains(), vec![mainnet, testnet]);
950 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
954 fn builds_offer_with_metadata() {
955 let offer = OfferBuilder::new("foo".into(), pubkey(42))
956 .metadata(vec![42; 32]).unwrap()
959 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
960 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
962 let offer = OfferBuilder::new("foo".into(), pubkey(42))
963 .metadata(vec![42; 32]).unwrap()
964 .metadata(vec![43; 32]).unwrap()
967 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
968 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
972 fn builds_offer_with_metadata_derived() {
973 let desc = "foo".to_string();
974 let node_id = recipient_pubkey();
975 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
976 let entropy = FixedEntropy {};
977 let secp_ctx = Secp256k1::new();
979 let offer = OfferBuilder
980 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
983 assert_eq!(offer.signing_pubkey(), node_id);
985 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
987 .sign(payer_sign).unwrap();
988 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
990 // Fails verification with altered offer field
991 let mut tlv_stream = offer.as_tlv_stream();
992 tlv_stream.amount = Some(100);
994 let mut encoded_offer = Vec::new();
995 tlv_stream.write(&mut encoded_offer).unwrap();
997 let invoice_request = Offer::try_from(encoded_offer).unwrap()
998 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1000 .sign(payer_sign).unwrap();
1001 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1003 // Fails verification with altered metadata
1004 let mut tlv_stream = offer.as_tlv_stream();
1005 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1006 tlv_stream.metadata = Some(&metadata);
1008 let mut encoded_offer = Vec::new();
1009 tlv_stream.write(&mut encoded_offer).unwrap();
1011 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1012 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1014 .sign(payer_sign).unwrap();
1015 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1019 fn builds_offer_with_derived_signing_pubkey() {
1020 let desc = "foo".to_string();
1021 let node_id = recipient_pubkey();
1022 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1023 let entropy = FixedEntropy {};
1024 let secp_ctx = Secp256k1::new();
1026 let blinded_path = BlindedPath {
1027 introduction_node_id: pubkey(40),
1028 blinding_point: pubkey(41),
1030 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1031 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1035 let offer = OfferBuilder
1036 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1040 assert_ne!(offer.signing_pubkey(), node_id);
1042 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1044 .sign(payer_sign).unwrap();
1045 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1047 // Fails verification with altered offer field
1048 let mut tlv_stream = offer.as_tlv_stream();
1049 tlv_stream.amount = Some(100);
1051 let mut encoded_offer = Vec::new();
1052 tlv_stream.write(&mut encoded_offer).unwrap();
1054 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1055 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1057 .sign(payer_sign).unwrap();
1058 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1060 // Fails verification with altered signing pubkey
1061 let mut tlv_stream = offer.as_tlv_stream();
1062 let signing_pubkey = pubkey(1);
1063 tlv_stream.node_id = Some(&signing_pubkey);
1065 let mut encoded_offer = Vec::new();
1066 tlv_stream.write(&mut encoded_offer).unwrap();
1068 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1069 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1071 .sign(payer_sign).unwrap();
1072 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1076 fn builds_offer_with_amount() {
1077 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1078 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1080 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1084 let tlv_stream = offer.as_tlv_stream();
1085 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1086 assert_eq!(tlv_stream.amount, Some(1000));
1087 assert_eq!(tlv_stream.currency, None);
1089 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1090 .amount(currency_amount.clone());
1091 let tlv_stream = builder.offer.as_tlv_stream();
1092 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1093 assert_eq!(tlv_stream.amount, Some(10));
1094 assert_eq!(tlv_stream.currency, Some(b"USD"));
1095 match builder.build() {
1096 Ok(_) => panic!("expected error"),
1097 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1100 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1101 .amount(currency_amount.clone())
1102 .amount(bitcoin_amount.clone())
1105 let tlv_stream = offer.as_tlv_stream();
1106 assert_eq!(tlv_stream.amount, Some(1000));
1107 assert_eq!(tlv_stream.currency, None);
1109 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1110 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1111 Ok(_) => panic!("expected error"),
1112 Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1117 fn builds_offer_with_features() {
1118 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1119 .features_unchecked(OfferFeatures::unknown())
1122 assert_eq!(offer.features(), &OfferFeatures::unknown());
1123 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1125 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1126 .features_unchecked(OfferFeatures::unknown())
1127 .features_unchecked(OfferFeatures::empty())
1130 assert_eq!(offer.features(), &OfferFeatures::empty());
1131 assert_eq!(offer.as_tlv_stream().features, None);
1135 fn builds_offer_with_absolute_expiry() {
1136 let future_expiry = Duration::from_secs(u64::max_value());
1137 let past_expiry = Duration::from_secs(0);
1139 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1140 .absolute_expiry(future_expiry)
1143 #[cfg(feature = "std")]
1144 assert!(!offer.is_expired());
1145 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1146 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1148 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1149 .absolute_expiry(future_expiry)
1150 .absolute_expiry(past_expiry)
1153 #[cfg(feature = "std")]
1154 assert!(offer.is_expired());
1155 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1156 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1160 fn builds_offer_with_paths() {
1163 introduction_node_id: pubkey(40),
1164 blinding_point: pubkey(41),
1166 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1167 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1171 introduction_node_id: pubkey(40),
1172 blinding_point: pubkey(41),
1174 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1175 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1180 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1181 .path(paths[0].clone())
1182 .path(paths[1].clone())
1185 let tlv_stream = offer.as_tlv_stream();
1186 assert_eq!(offer.paths(), paths.as_slice());
1187 assert_eq!(offer.signing_pubkey(), pubkey(42));
1188 assert_ne!(pubkey(42), pubkey(44));
1189 assert_eq!(tlv_stream.paths, Some(&paths));
1190 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1194 fn builds_offer_with_issuer() {
1195 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1196 .issuer("bar".into())
1199 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1200 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1202 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1203 .issuer("bar".into())
1204 .issuer("baz".into())
1207 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1208 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1212 fn builds_offer_with_supported_quantity() {
1213 let one = NonZeroU64::new(1).unwrap();
1214 let ten = NonZeroU64::new(10).unwrap();
1216 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1217 .supported_quantity(Quantity::One)
1220 let tlv_stream = offer.as_tlv_stream();
1221 assert_eq!(offer.supported_quantity(), Quantity::One);
1222 assert_eq!(tlv_stream.quantity_max, None);
1224 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1225 .supported_quantity(Quantity::Unbounded)
1228 let tlv_stream = offer.as_tlv_stream();
1229 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1230 assert_eq!(tlv_stream.quantity_max, Some(0));
1232 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1233 .supported_quantity(Quantity::Bounded(ten))
1236 let tlv_stream = offer.as_tlv_stream();
1237 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1238 assert_eq!(tlv_stream.quantity_max, Some(10));
1240 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1241 .supported_quantity(Quantity::Bounded(one))
1244 let tlv_stream = offer.as_tlv_stream();
1245 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1246 assert_eq!(tlv_stream.quantity_max, Some(1));
1248 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1249 .supported_quantity(Quantity::Bounded(ten))
1250 .supported_quantity(Quantity::One)
1253 let tlv_stream = offer.as_tlv_stream();
1254 assert_eq!(offer.supported_quantity(), Quantity::One);
1255 assert_eq!(tlv_stream.quantity_max, None);
1259 fn fails_requesting_invoice_with_unknown_required_features() {
1260 match OfferBuilder::new("foo".into(), pubkey(42))
1261 .features_unchecked(OfferFeatures::unknown())
1263 .request_invoice(vec![1; 32], pubkey(43))
1265 Ok(_) => panic!("expected error"),
1266 Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1271 fn parses_offer_with_chains() {
1272 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1273 .chain(Network::Bitcoin)
1274 .chain(Network::Testnet)
1277 if let Err(e) = offer.to_string().parse::<Offer>() {
1278 panic!("error parsing offer: {:?}", e);
1283 fn parses_offer_with_amount() {
1284 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1285 .amount(Amount::Bitcoin { amount_msats: 1000 })
1288 if let Err(e) = offer.to_string().parse::<Offer>() {
1289 panic!("error parsing offer: {:?}", e);
1292 let mut tlv_stream = offer.as_tlv_stream();
1293 tlv_stream.amount = Some(1000);
1294 tlv_stream.currency = Some(b"USD");
1296 let mut encoded_offer = Vec::new();
1297 tlv_stream.write(&mut encoded_offer).unwrap();
1299 if let Err(e) = Offer::try_from(encoded_offer) {
1300 panic!("error parsing offer: {:?}", e);
1303 let mut tlv_stream = offer.as_tlv_stream();
1304 tlv_stream.amount = None;
1305 tlv_stream.currency = Some(b"USD");
1307 let mut encoded_offer = Vec::new();
1308 tlv_stream.write(&mut encoded_offer).unwrap();
1310 match Offer::try_from(encoded_offer) {
1311 Ok(_) => panic!("expected error"),
1312 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1315 let mut tlv_stream = offer.as_tlv_stream();
1316 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1317 tlv_stream.currency = None;
1319 let mut encoded_offer = Vec::new();
1320 tlv_stream.write(&mut encoded_offer).unwrap();
1322 match Offer::try_from(encoded_offer) {
1323 Ok(_) => panic!("expected error"),
1324 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1329 fn parses_offer_with_description() {
1330 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1331 if let Err(e) = offer.to_string().parse::<Offer>() {
1332 panic!("error parsing offer: {:?}", e);
1335 let mut tlv_stream = offer.as_tlv_stream();
1336 tlv_stream.description = None;
1338 let mut encoded_offer = Vec::new();
1339 tlv_stream.write(&mut encoded_offer).unwrap();
1341 match Offer::try_from(encoded_offer) {
1342 Ok(_) => panic!("expected error"),
1344 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1350 fn parses_offer_with_paths() {
1351 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1353 introduction_node_id: pubkey(40),
1354 blinding_point: pubkey(41),
1356 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1357 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1361 introduction_node_id: pubkey(40),
1362 blinding_point: pubkey(41),
1364 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1365 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1370 if let Err(e) = offer.to_string().parse::<Offer>() {
1371 panic!("error parsing offer: {:?}", e);
1374 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1375 builder.offer.paths = Some(vec![]);
1377 let offer = builder.build().unwrap();
1378 if let Err(e) = offer.to_string().parse::<Offer>() {
1379 panic!("error parsing offer: {:?}", e);
1384 fn parses_offer_with_quantity() {
1385 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1386 .supported_quantity(Quantity::One)
1389 if let Err(e) = offer.to_string().parse::<Offer>() {
1390 panic!("error parsing offer: {:?}", e);
1393 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1394 .supported_quantity(Quantity::Unbounded)
1397 if let Err(e) = offer.to_string().parse::<Offer>() {
1398 panic!("error parsing offer: {:?}", e);
1401 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1402 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1405 if let Err(e) = offer.to_string().parse::<Offer>() {
1406 panic!("error parsing offer: {:?}", e);
1409 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1410 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1413 if let Err(e) = offer.to_string().parse::<Offer>() {
1414 panic!("error parsing offer: {:?}", e);
1419 fn parses_offer_with_node_id() {
1420 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1421 if let Err(e) = offer.to_string().parse::<Offer>() {
1422 panic!("error parsing offer: {:?}", e);
1425 let mut tlv_stream = offer.as_tlv_stream();
1426 tlv_stream.node_id = None;
1428 let mut encoded_offer = Vec::new();
1429 tlv_stream.write(&mut encoded_offer).unwrap();
1431 match Offer::try_from(encoded_offer) {
1432 Ok(_) => panic!("expected error"),
1434 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1440 fn fails_parsing_offer_with_extra_tlv_records() {
1441 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1443 let mut encoded_offer = Vec::new();
1444 offer.write(&mut encoded_offer).unwrap();
1445 BigSize(80).write(&mut encoded_offer).unwrap();
1446 BigSize(32).write(&mut encoded_offer).unwrap();
1447 [42u8; 32].write(&mut encoded_offer).unwrap();
1449 match Offer::try_from(encoded_offer) {
1450 Ok(_) => panic!("expected error"),
1451 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1458 use super::{Bolt12ParseError, Offer};
1459 use bitcoin::bech32;
1460 use crate::ln::msgs::DecodeError;
1463 fn encodes_offer_as_bech32_without_checksum() {
1464 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
1465 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1466 let reencoded_offer = offer.to_string();
1467 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1468 assert_eq!(reencoded_offer, encoded_offer);
1472 fn parses_bech32_encoded_offers() {
1474 // BOLT 12 test vectors
1475 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1476 "l+no1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1477 "lno1pqps7sjqpgt+yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+5k7msjzfpy7nz5yqcn+ygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+5xvxg",
1478 "lno1pqps7sjqpgt+ yzm3qv4uxzmtsd3jjqer9wd3hy6tsw3+ 5k7msjzfpy7nz5yqcn+\nygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd+\r\n 5xvxg",
1480 for encoded_offer in &offers {
1481 if let Err(e) = encoded_offer.parse::<Offer>() {
1482 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1488 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1490 // BOLT 12 test vectors
1491 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+",
1492 "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg+ ",
1493 "+lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1494 "+ lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1495 "ln++o1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1497 for encoded_offer in &offers {
1498 match encoded_offer.parse::<Offer>() {
1499 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1500 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidContinuation),
1507 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1508 let encoded_offer = "lni1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg";
1509 match encoded_offer.parse::<Offer>() {
1510 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1511 Err(e) => assert_eq!(e, Bolt12ParseError::InvalidBech32Hrp),
1516 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1517 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxo";
1518 match encoded_offer.parse::<Offer>() {
1519 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1520 Err(e) => assert_eq!(e, Bolt12ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1525 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1526 let encoded_offer = "lno1pqps7sjqpgtyzm3qv4uxzmtsd3jjqer9wd3hy6tsw35k7msjzfpy7nz5yqcnygrfdej82um5wf5k2uckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxgqqqqq";
1527 match encoded_offer.parse::<Offer>() {
1528 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1529 Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),