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::ParseError;
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<(), ParseError> {
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, ParseError, ParsedMessage, SemanticError};
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, SemanticError> {
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, SemanticError> {
256 match self.offer.amount {
257 Some(Amount::Bitcoin { amount_msats }) => {
258 if amount_msats > MAX_VALUE_MSAT {
259 return Err(SemanticError::InvalidAmount);
262 Some(Amount::Currency { .. }) => return Err(SemanticError::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 [`Invoice`] for a specific quantity and using an amount sufficient to
323 /// 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 /// [`Invoice`]: crate::offers::invoice::Invoice
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 an [`Invoice`].
343 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
344 /// [`Invoice`]: crate::offers::invoice::Invoice
345 #[derive(Clone, Debug)]
346 #[cfg_attr(test, derive(PartialEq))]
347 pub(super) struct OfferContents {
348 chains: Option<Vec<ChainHash>>,
349 metadata: Option<Metadata>,
350 amount: Option<Amount>,
352 features: OfferFeatures,
353 absolute_expiry: Option<Duration>,
354 issuer: Option<String>,
355 paths: Option<Vec<BlindedPath>>,
356 supported_quantity: Quantity,
357 signing_pubkey: PublicKey,
361 // TODO: Return a slice once ChainHash has constants.
362 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
363 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
364 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
365 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
366 /// for the selected chain.
367 pub fn chains(&self) -> Vec<ChainHash> {
368 self.contents.chains()
371 pub(super) fn implied_chain(&self) -> ChainHash {
372 self.contents.implied_chain()
375 /// Returns whether the given chain is supported by the offer.
376 pub fn supports_chain(&self, chain: ChainHash) -> bool {
377 self.contents.supports_chain(chain)
380 // TODO: Link to corresponding method in `InvoiceRequest`.
381 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
382 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
383 pub fn metadata(&self) -> Option<&Vec<u8>> {
384 self.contents.metadata()
387 /// The minimum amount required for a successful payment of a single item.
388 pub fn amount(&self) -> Option<&Amount> {
389 self.contents.amount()
392 /// A complete description of the purpose of the payment. Intended to be displayed to the user
393 /// but with the caveat that it has not been verified in any way.
394 pub fn description(&self) -> PrintableString {
395 self.contents.description()
398 /// Features pertaining to the offer.
399 pub fn features(&self) -> &OfferFeatures {
400 &self.contents.features
403 /// Duration since the Unix epoch when an invoice should no longer be requested.
405 /// If `None`, the offer does not expire.
406 pub fn absolute_expiry(&self) -> Option<Duration> {
407 self.contents.absolute_expiry
410 /// Whether the offer has expired.
411 #[cfg(feature = "std")]
412 pub fn is_expired(&self) -> bool {
413 self.contents.is_expired()
416 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
417 /// displayed to the user but with the caveat that it has not been verified in any way.
418 pub fn issuer(&self) -> Option<PrintableString> {
419 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
422 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
423 /// recipient privacy by obfuscating its node id.
424 pub fn paths(&self) -> &[BlindedPath] {
425 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
428 /// The quantity of items supported.
429 pub fn supported_quantity(&self) -> Quantity {
430 self.contents.supported_quantity()
433 /// Returns whether the given quantity is valid for the offer.
434 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
435 self.contents.is_valid_quantity(quantity)
438 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
440 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
441 pub fn expects_quantity(&self) -> bool {
442 self.contents.expects_quantity()
445 /// The public key used by the recipient to sign invoices.
446 pub fn signing_pubkey(&self) -> PublicKey {
447 self.contents.signing_pubkey()
450 /// Similar to [`Offer::request_invoice`] except it:
451 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
453 /// - sets the [`InvoiceRequest::metadata`] when [`InvoiceRequestBuilder::build`] is called such
454 /// that it can be used by [`Invoice::verify`] to determine if the invoice was requested using
455 /// a base [`ExpandedKey`] from which the payer id was derived.
457 /// Useful to protect the sender's privacy.
459 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
461 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
462 /// [`InvoiceRequest::metadata`]: crate::offers::invoice_request::InvoiceRequest::metadata
463 /// [`Invoice::verify`]: crate::offers::invoice::Invoice::verify
464 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
465 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
466 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
467 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, SemanticError>
469 ES::Target: EntropySource,
471 if self.features().requires_unknown_bits() {
472 return Err(SemanticError::UnknownRequiredFeatures);
475 Ok(InvoiceRequestBuilder::deriving_payer_id(self, expanded_key, entropy_source, secp_ctx))
478 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
479 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
481 /// Useful for recurring payments using the same `payer_id` with different invoices.
483 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
485 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
486 pub fn request_invoice_deriving_metadata<ES: Deref>(
487 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
488 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError>
490 ES::Target: EntropySource,
492 if self.features().requires_unknown_bits() {
493 return Err(SemanticError::UnknownRequiredFeatures);
496 Ok(InvoiceRequestBuilder::deriving_metadata(self, payer_id, expanded_key, entropy_source))
499 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
500 /// which will be reflected in the `Invoice` response.
502 /// The `metadata` is useful for including information about the derivation of `payer_id` such
503 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
504 /// hashing in the signature calculation.
506 /// This should not leak any information such as by using a simple BIP-32 derivation path.
507 /// Otherwise, payments may be correlated.
509 /// Errors if the offer contains unknown required features.
511 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
513 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
514 pub fn request_invoice(
515 &self, metadata: Vec<u8>, payer_id: PublicKey
516 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError> {
517 if self.features().requires_unknown_bits() {
518 return Err(SemanticError::UnknownRequiredFeatures);
521 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
525 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
526 self.contents.as_tlv_stream()
530 impl AsRef<[u8]> for Offer {
531 fn as_ref(&self) -> &[u8] {
537 pub fn chains(&self) -> Vec<ChainHash> {
538 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
541 pub fn implied_chain(&self) -> ChainHash {
542 ChainHash::using_genesis_block(Network::Bitcoin)
545 pub fn supports_chain(&self, chain: ChainHash) -> bool {
546 self.chains().contains(&chain)
549 pub fn metadata(&self) -> Option<&Vec<u8>> {
550 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
553 pub fn description(&self) -> PrintableString {
554 PrintableString(&self.description)
557 #[cfg(feature = "std")]
558 pub(super) fn is_expired(&self) -> bool {
559 match self.absolute_expiry {
560 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
561 Ok(elapsed) => elapsed > seconds_from_epoch,
568 pub fn amount(&self) -> Option<&Amount> {
572 pub(super) fn check_amount_msats_for_quantity(
573 &self, amount_msats: Option<u64>, quantity: Option<u64>
574 ) -> Result<(), SemanticError> {
575 let offer_amount_msats = match self.amount {
577 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
578 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
581 if !self.expects_quantity() || quantity.is_some() {
582 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
583 .ok_or(SemanticError::InvalidAmount)?;
584 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
586 if amount_msats < expected_amount_msats {
587 return Err(SemanticError::InsufficientAmount);
590 if amount_msats > MAX_VALUE_MSAT {
591 return Err(SemanticError::InvalidAmount);
598 pub fn supported_quantity(&self) -> Quantity {
599 self.supported_quantity
602 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
603 let expects_quantity = self.expects_quantity();
605 None if expects_quantity => Err(SemanticError::MissingQuantity),
606 Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
607 Some(quantity) if !self.is_valid_quantity(quantity) => {
608 Err(SemanticError::InvalidQuantity)
614 fn is_valid_quantity(&self, quantity: u64) -> bool {
615 match self.supported_quantity {
616 Quantity::Bounded(n) => quantity <= n.get(),
617 Quantity::Unbounded => quantity > 0,
618 Quantity::One => quantity == 1,
622 fn expects_quantity(&self) -> bool {
623 match self.supported_quantity {
624 Quantity::Bounded(_) => true,
625 Quantity::Unbounded => true,
626 Quantity::One => false,
630 pub(super) fn signing_pubkey(&self) -> PublicKey {
634 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
635 pub(super) fn verify<T: secp256k1::Signing>(
636 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
637 ) -> Result<Option<KeyPair>, ()> {
638 match self.metadata() {
640 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
641 match record.r#type {
642 OFFER_METADATA_TYPE => false,
643 OFFER_NODE_ID_TYPE => !self.metadata.as_ref().unwrap().derives_keys(),
647 signer::verify_metadata(
648 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
655 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
656 let (currency, amount) = match &self.amount {
657 None => (None, None),
658 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
659 Some(Amount::Currency { iso4217_code, amount }) => (
660 Some(iso4217_code), Some(*amount)
665 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
669 chains: self.chains.as_ref(),
670 metadata: self.metadata(),
673 description: Some(&self.description),
675 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
676 paths: self.paths.as_ref(),
677 issuer: self.issuer.as_ref(),
678 quantity_max: self.supported_quantity.to_tlv_record(),
679 node_id: Some(&self.signing_pubkey),
684 impl Writeable for Offer {
685 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
686 WithoutLength(&self.bytes).write(writer)
690 impl Writeable for OfferContents {
691 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692 self.as_tlv_stream().write(writer)
696 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
697 /// another currency.
698 #[derive(Clone, Debug, PartialEq)]
700 /// An amount of bitcoin.
702 /// The amount in millisatoshi.
705 /// An amount of currency specified using ISO 4712.
707 /// The currency that the amount is denominated in.
708 iso4217_code: CurrencyCode,
709 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
714 /// An ISO 4712 three-letter currency code (e.g., USD).
715 pub type CurrencyCode = [u8; 3];
717 /// Quantity of items supported by an [`Offer`].
718 #[derive(Clone, Copy, Debug, PartialEq)]
720 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
721 /// but is limited (e.g., because of per customer or inventory limits).
723 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
726 /// One or more items. Use when more than one item can be requested without any limit.
728 /// Only one item. Use when only a single item can be requested.
733 fn to_tlv_record(&self) -> Option<u64> {
735 Quantity::Bounded(n) => Some(n.get()),
736 Quantity::Unbounded => Some(0),
737 Quantity::One => None,
742 /// Valid type range for offer TLV records.
743 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
745 /// TLV record type for [`Offer::metadata`].
746 const OFFER_METADATA_TYPE: u64 = 4;
748 /// TLV record type for [`Offer::signing_pubkey`].
749 const OFFER_NODE_ID_TYPE: u64 = 22;
751 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
752 (2, chains: (Vec<ChainHash>, WithoutLength)),
753 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
754 (6, currency: CurrencyCode),
755 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
756 (10, description: (String, WithoutLength)),
757 (12, features: (OfferFeatures, WithoutLength)),
758 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
759 (16, paths: (Vec<BlindedPath>, WithoutLength)),
760 (18, issuer: (String, WithoutLength)),
761 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
762 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
765 impl Bech32Encode for Offer {
766 const BECH32_HRP: &'static str = "lno";
769 impl FromStr for Offer {
770 type Err = ParseError;
772 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
773 Self::from_bech32_str(s)
777 impl TryFrom<Vec<u8>> for Offer {
778 type Error = ParseError;
780 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
781 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
782 let ParsedMessage { bytes, tlv_stream } = offer;
783 let contents = OfferContents::try_from(tlv_stream)?;
784 Ok(Offer { bytes, contents })
788 impl TryFrom<OfferTlvStream> for OfferContents {
789 type Error = SemanticError;
791 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
793 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
794 issuer, quantity_max, node_id,
797 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
799 let amount = match (currency, amount) {
800 (None, None) => None,
801 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
802 return Err(SemanticError::InvalidAmount);
804 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
805 (Some(_), None) => return Err(SemanticError::MissingAmount),
806 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
809 let description = match description {
810 None => return Err(SemanticError::MissingDescription),
811 Some(description) => description,
814 let features = features.unwrap_or_else(OfferFeatures::empty);
816 let absolute_expiry = absolute_expiry
817 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
819 let supported_quantity = match quantity_max {
820 None => Quantity::One,
821 Some(0) => Quantity::Unbounded,
822 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
825 let signing_pubkey = match node_id {
826 None => return Err(SemanticError::MissingSigningPubkey),
827 Some(node_id) => node_id,
831 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
832 supported_quantity, signing_pubkey,
837 impl core::fmt::Display for Offer {
838 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
839 self.fmt_bech32_str(f)
845 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
847 use bitcoin::blockdata::constants::ChainHash;
848 use bitcoin::network::constants::Network;
849 use bitcoin::secp256k1::Secp256k1;
850 use core::convert::TryFrom;
851 use core::num::NonZeroU64;
852 use core::time::Duration;
853 use crate::blinded_path::{BlindedHop, BlindedPath};
854 use crate::sign::KeyMaterial;
855 use crate::ln::features::OfferFeatures;
856 use crate::ln::inbound_payment::ExpandedKey;
857 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
858 use crate::offers::parse::{ParseError, SemanticError};
859 use crate::offers::test_utils::*;
860 use crate::util::ser::{BigSize, Writeable};
861 use crate::util::string::PrintableString;
864 fn builds_offer_with_defaults() {
865 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
867 let mut buffer = Vec::new();
868 offer.write(&mut buffer).unwrap();
870 assert_eq!(offer.bytes, buffer.as_slice());
871 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
872 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
873 assert_eq!(offer.metadata(), None);
874 assert_eq!(offer.amount(), None);
875 assert_eq!(offer.description(), PrintableString("foo"));
876 assert_eq!(offer.features(), &OfferFeatures::empty());
877 assert_eq!(offer.absolute_expiry(), None);
878 #[cfg(feature = "std")]
879 assert!(!offer.is_expired());
880 assert_eq!(offer.paths(), &[]);
881 assert_eq!(offer.issuer(), None);
882 assert_eq!(offer.supported_quantity(), Quantity::One);
883 assert_eq!(offer.signing_pubkey(), pubkey(42));
886 offer.as_tlv_stream(),
892 description: Some(&String::from("foo")),
894 absolute_expiry: None,
898 node_id: Some(&pubkey(42)),
902 if let Err(e) = Offer::try_from(buffer) {
903 panic!("error parsing offer: {:?}", e);
908 fn builds_offer_with_chains() {
909 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
910 let testnet = ChainHash::using_genesis_block(Network::Testnet);
912 let offer = OfferBuilder::new("foo".into(), pubkey(42))
913 .chain(Network::Bitcoin)
916 assert!(offer.supports_chain(mainnet));
917 assert_eq!(offer.chains(), vec![mainnet]);
918 assert_eq!(offer.as_tlv_stream().chains, None);
920 let offer = OfferBuilder::new("foo".into(), pubkey(42))
921 .chain(Network::Testnet)
924 assert!(offer.supports_chain(testnet));
925 assert_eq!(offer.chains(), vec![testnet]);
926 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
928 let offer = OfferBuilder::new("foo".into(), pubkey(42))
929 .chain(Network::Testnet)
930 .chain(Network::Testnet)
933 assert!(offer.supports_chain(testnet));
934 assert_eq!(offer.chains(), vec![testnet]);
935 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
937 let offer = OfferBuilder::new("foo".into(), pubkey(42))
938 .chain(Network::Bitcoin)
939 .chain(Network::Testnet)
942 assert!(offer.supports_chain(mainnet));
943 assert!(offer.supports_chain(testnet));
944 assert_eq!(offer.chains(), vec![mainnet, testnet]);
945 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
949 fn builds_offer_with_metadata() {
950 let offer = OfferBuilder::new("foo".into(), pubkey(42))
951 .metadata(vec![42; 32]).unwrap()
954 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
955 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
957 let offer = OfferBuilder::new("foo".into(), pubkey(42))
958 .metadata(vec![42; 32]).unwrap()
959 .metadata(vec![43; 32]).unwrap()
962 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
963 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
967 fn builds_offer_with_metadata_derived() {
968 let desc = "foo".to_string();
969 let node_id = recipient_pubkey();
970 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
971 let entropy = FixedEntropy {};
972 let secp_ctx = Secp256k1::new();
974 let offer = OfferBuilder
975 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
978 assert_eq!(offer.signing_pubkey(), node_id);
980 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
982 .sign(payer_sign).unwrap();
983 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
985 // Fails verification with altered offer field
986 let mut tlv_stream = offer.as_tlv_stream();
987 tlv_stream.amount = Some(100);
989 let mut encoded_offer = Vec::new();
990 tlv_stream.write(&mut encoded_offer).unwrap();
992 let invoice_request = Offer::try_from(encoded_offer).unwrap()
993 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
995 .sign(payer_sign).unwrap();
996 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
998 // Fails verification with altered metadata
999 let mut tlv_stream = offer.as_tlv_stream();
1000 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1001 tlv_stream.metadata = Some(&metadata);
1003 let mut encoded_offer = Vec::new();
1004 tlv_stream.write(&mut encoded_offer).unwrap();
1006 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1007 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1009 .sign(payer_sign).unwrap();
1010 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1014 fn builds_offer_with_derived_signing_pubkey() {
1015 let desc = "foo".to_string();
1016 let node_id = recipient_pubkey();
1017 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1018 let entropy = FixedEntropy {};
1019 let secp_ctx = Secp256k1::new();
1021 let blinded_path = BlindedPath {
1022 introduction_node_id: pubkey(40),
1023 blinding_point: pubkey(41),
1025 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1026 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1030 let offer = OfferBuilder
1031 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1035 assert_ne!(offer.signing_pubkey(), node_id);
1037 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1039 .sign(payer_sign).unwrap();
1040 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1042 // Fails verification with altered offer field
1043 let mut tlv_stream = offer.as_tlv_stream();
1044 tlv_stream.amount = Some(100);
1046 let mut encoded_offer = Vec::new();
1047 tlv_stream.write(&mut encoded_offer).unwrap();
1049 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1050 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1052 .sign(payer_sign).unwrap();
1053 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1055 // Fails verification with altered signing pubkey
1056 let mut tlv_stream = offer.as_tlv_stream();
1057 let signing_pubkey = pubkey(1);
1058 tlv_stream.node_id = Some(&signing_pubkey);
1060 let mut encoded_offer = Vec::new();
1061 tlv_stream.write(&mut encoded_offer).unwrap();
1063 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1064 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1066 .sign(payer_sign).unwrap();
1067 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1071 fn builds_offer_with_amount() {
1072 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1073 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1075 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1079 let tlv_stream = offer.as_tlv_stream();
1080 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1081 assert_eq!(tlv_stream.amount, Some(1000));
1082 assert_eq!(tlv_stream.currency, None);
1084 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1085 .amount(currency_amount.clone());
1086 let tlv_stream = builder.offer.as_tlv_stream();
1087 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1088 assert_eq!(tlv_stream.amount, Some(10));
1089 assert_eq!(tlv_stream.currency, Some(b"USD"));
1090 match builder.build() {
1091 Ok(_) => panic!("expected error"),
1092 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
1095 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1096 .amount(currency_amount.clone())
1097 .amount(bitcoin_amount.clone())
1100 let tlv_stream = offer.as_tlv_stream();
1101 assert_eq!(tlv_stream.amount, Some(1000));
1102 assert_eq!(tlv_stream.currency, None);
1104 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1105 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1106 Ok(_) => panic!("expected error"),
1107 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1112 fn builds_offer_with_features() {
1113 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1114 .features_unchecked(OfferFeatures::unknown())
1117 assert_eq!(offer.features(), &OfferFeatures::unknown());
1118 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1120 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1121 .features_unchecked(OfferFeatures::unknown())
1122 .features_unchecked(OfferFeatures::empty())
1125 assert_eq!(offer.features(), &OfferFeatures::empty());
1126 assert_eq!(offer.as_tlv_stream().features, None);
1130 fn builds_offer_with_absolute_expiry() {
1131 let future_expiry = Duration::from_secs(u64::max_value());
1132 let past_expiry = Duration::from_secs(0);
1134 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1135 .absolute_expiry(future_expiry)
1138 #[cfg(feature = "std")]
1139 assert!(!offer.is_expired());
1140 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1141 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1143 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1144 .absolute_expiry(future_expiry)
1145 .absolute_expiry(past_expiry)
1148 #[cfg(feature = "std")]
1149 assert!(offer.is_expired());
1150 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1151 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1155 fn builds_offer_with_paths() {
1158 introduction_node_id: pubkey(40),
1159 blinding_point: pubkey(41),
1161 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1162 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1166 introduction_node_id: pubkey(40),
1167 blinding_point: pubkey(41),
1169 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1170 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1175 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1176 .path(paths[0].clone())
1177 .path(paths[1].clone())
1180 let tlv_stream = offer.as_tlv_stream();
1181 assert_eq!(offer.paths(), paths.as_slice());
1182 assert_eq!(offer.signing_pubkey(), pubkey(42));
1183 assert_ne!(pubkey(42), pubkey(44));
1184 assert_eq!(tlv_stream.paths, Some(&paths));
1185 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1189 fn builds_offer_with_issuer() {
1190 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1191 .issuer("bar".into())
1194 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1195 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1197 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1198 .issuer("bar".into())
1199 .issuer("baz".into())
1202 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1203 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1207 fn builds_offer_with_supported_quantity() {
1208 let one = NonZeroU64::new(1).unwrap();
1209 let ten = NonZeroU64::new(10).unwrap();
1211 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1212 .supported_quantity(Quantity::One)
1215 let tlv_stream = offer.as_tlv_stream();
1216 assert_eq!(offer.supported_quantity(), Quantity::One);
1217 assert_eq!(tlv_stream.quantity_max, None);
1219 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1220 .supported_quantity(Quantity::Unbounded)
1223 let tlv_stream = offer.as_tlv_stream();
1224 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1225 assert_eq!(tlv_stream.quantity_max, Some(0));
1227 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1228 .supported_quantity(Quantity::Bounded(ten))
1231 let tlv_stream = offer.as_tlv_stream();
1232 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1233 assert_eq!(tlv_stream.quantity_max, Some(10));
1235 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1236 .supported_quantity(Quantity::Bounded(one))
1239 let tlv_stream = offer.as_tlv_stream();
1240 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1241 assert_eq!(tlv_stream.quantity_max, Some(1));
1243 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1244 .supported_quantity(Quantity::Bounded(ten))
1245 .supported_quantity(Quantity::One)
1248 let tlv_stream = offer.as_tlv_stream();
1249 assert_eq!(offer.supported_quantity(), Quantity::One);
1250 assert_eq!(tlv_stream.quantity_max, None);
1254 fn fails_requesting_invoice_with_unknown_required_features() {
1255 match OfferBuilder::new("foo".into(), pubkey(42))
1256 .features_unchecked(OfferFeatures::unknown())
1258 .request_invoice(vec![1; 32], pubkey(43))
1260 Ok(_) => panic!("expected error"),
1261 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1266 fn parses_offer_with_chains() {
1267 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1268 .chain(Network::Bitcoin)
1269 .chain(Network::Testnet)
1272 if let Err(e) = offer.to_string().parse::<Offer>() {
1273 panic!("error parsing offer: {:?}", e);
1278 fn parses_offer_with_amount() {
1279 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1280 .amount(Amount::Bitcoin { amount_msats: 1000 })
1283 if let Err(e) = offer.to_string().parse::<Offer>() {
1284 panic!("error parsing offer: {:?}", e);
1287 let mut tlv_stream = offer.as_tlv_stream();
1288 tlv_stream.amount = Some(1000);
1289 tlv_stream.currency = Some(b"USD");
1291 let mut encoded_offer = Vec::new();
1292 tlv_stream.write(&mut encoded_offer).unwrap();
1294 if let Err(e) = Offer::try_from(encoded_offer) {
1295 panic!("error parsing offer: {:?}", e);
1298 let mut tlv_stream = offer.as_tlv_stream();
1299 tlv_stream.amount = None;
1300 tlv_stream.currency = Some(b"USD");
1302 let mut encoded_offer = Vec::new();
1303 tlv_stream.write(&mut encoded_offer).unwrap();
1305 match Offer::try_from(encoded_offer) {
1306 Ok(_) => panic!("expected error"),
1307 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1310 let mut tlv_stream = offer.as_tlv_stream();
1311 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1312 tlv_stream.currency = None;
1314 let mut encoded_offer = Vec::new();
1315 tlv_stream.write(&mut encoded_offer).unwrap();
1317 match Offer::try_from(encoded_offer) {
1318 Ok(_) => panic!("expected error"),
1319 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1324 fn parses_offer_with_description() {
1325 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1326 if let Err(e) = offer.to_string().parse::<Offer>() {
1327 panic!("error parsing offer: {:?}", e);
1330 let mut tlv_stream = offer.as_tlv_stream();
1331 tlv_stream.description = None;
1333 let mut encoded_offer = Vec::new();
1334 tlv_stream.write(&mut encoded_offer).unwrap();
1336 match Offer::try_from(encoded_offer) {
1337 Ok(_) => panic!("expected error"),
1339 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1345 fn parses_offer_with_paths() {
1346 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1348 introduction_node_id: pubkey(40),
1349 blinding_point: pubkey(41),
1351 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1352 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1356 introduction_node_id: pubkey(40),
1357 blinding_point: pubkey(41),
1359 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1360 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1365 if let Err(e) = offer.to_string().parse::<Offer>() {
1366 panic!("error parsing offer: {:?}", e);
1369 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1370 builder.offer.paths = Some(vec![]);
1372 let offer = builder.build().unwrap();
1373 if let Err(e) = offer.to_string().parse::<Offer>() {
1374 panic!("error parsing offer: {:?}", e);
1379 fn parses_offer_with_quantity() {
1380 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1381 .supported_quantity(Quantity::One)
1384 if let Err(e) = offer.to_string().parse::<Offer>() {
1385 panic!("error parsing offer: {:?}", e);
1388 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1389 .supported_quantity(Quantity::Unbounded)
1392 if let Err(e) = offer.to_string().parse::<Offer>() {
1393 panic!("error parsing offer: {:?}", e);
1396 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1397 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1400 if let Err(e) = offer.to_string().parse::<Offer>() {
1401 panic!("error parsing offer: {:?}", e);
1404 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1405 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1408 if let Err(e) = offer.to_string().parse::<Offer>() {
1409 panic!("error parsing offer: {:?}", e);
1414 fn parses_offer_with_node_id() {
1415 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1416 if let Err(e) = offer.to_string().parse::<Offer>() {
1417 panic!("error parsing offer: {:?}", e);
1420 let mut tlv_stream = offer.as_tlv_stream();
1421 tlv_stream.node_id = None;
1423 let mut encoded_offer = Vec::new();
1424 tlv_stream.write(&mut encoded_offer).unwrap();
1426 match Offer::try_from(encoded_offer) {
1427 Ok(_) => panic!("expected error"),
1429 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1435 fn fails_parsing_offer_with_extra_tlv_records() {
1436 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1438 let mut encoded_offer = Vec::new();
1439 offer.write(&mut encoded_offer).unwrap();
1440 BigSize(80).write(&mut encoded_offer).unwrap();
1441 BigSize(32).write(&mut encoded_offer).unwrap();
1442 [42u8; 32].write(&mut encoded_offer).unwrap();
1444 match Offer::try_from(encoded_offer) {
1445 Ok(_) => panic!("expected error"),
1446 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1453 use super::{Offer, ParseError};
1454 use bitcoin::bech32;
1455 use crate::ln::msgs::DecodeError;
1457 // TODO: Remove once test vectors are updated.
1460 fn encodes_offer_as_bech32_without_checksum() {
1461 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1462 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1463 let reencoded_offer = offer.to_string();
1464 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1465 assert_eq!(reencoded_offer, encoded_offer);
1468 // TODO: Remove once test vectors are updated.
1471 fn parses_bech32_encoded_offers() {
1473 // BOLT 12 test vectors
1474 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1475 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1476 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1477 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1478 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1479 // Two blinded paths
1480 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1482 for encoded_offer in &offers {
1483 if let Err(e) = encoded_offer.parse::<Offer>() {
1484 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1490 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1492 // BOLT 12 test vectors
1493 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1494 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1495 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1496 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1497 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1499 for encoded_offer in &offers {
1500 match encoded_offer.parse::<Offer>() {
1501 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1502 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1509 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1510 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1511 match encoded_offer.parse::<Offer>() {
1512 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1513 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1518 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1519 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1520 match encoded_offer.parse::<Offer>() {
1521 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1522 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1527 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1528 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1529 match encoded_offer.parse::<Offer>() {
1530 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1531 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),