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::onion_message::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::{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::chain::keysinterface::EntropySource;
79 use crate::ln::features::OfferFeatures;
80 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
81 use crate::ln::msgs::MAX_VALUE_MSAT;
82 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
83 use crate::offers::merkle::TlvStream;
84 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
85 use crate::offers::signer::{Metadata, MetadataMaterial, self};
86 use crate::onion_message::BlindedPath;
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 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 /// [module-level documentation]: self
102 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
103 offer: OfferContents,
104 metadata_strategy: core::marker::PhantomData<M>,
105 secp_ctx: Option<&'a Secp256k1<T>>,
108 /// Indicates how [`Offer::metadata`] may be set.
109 pub trait MetadataStrategy {}
111 /// [`Offer::metadata`] may be explicitly set or left empty.
112 pub struct ExplicitMetadata {}
114 /// [`Offer::metadata`] will be derived.
115 pub struct DerivedMetadata {}
117 impl MetadataStrategy for ExplicitMetadata {}
118 impl MetadataStrategy for DerivedMetadata {}
120 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
121 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
122 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
123 /// while the offer is valid.
125 /// Use a different pubkey per offer to avoid correlating offers.
126 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
128 offer: OfferContents {
129 chains: None, metadata: None, amount: None, description,
130 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
131 supported_quantity: Quantity::One, signing_pubkey,
133 metadata_strategy: core::marker::PhantomData,
138 /// Sets the [`Offer::metadata`] to the given bytes.
140 /// Successive calls to this method will override the previous setting.
141 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, SemanticError> {
142 self.offer.metadata = Some(Metadata::Bytes(metadata));
147 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
148 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
149 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
150 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
151 /// provided `node_id` is used for the signing pubkey.
153 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
154 /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
157 /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
158 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
159 pub fn deriving_signing_pubkey<ES: Deref>(
160 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
161 secp_ctx: &'a Secp256k1<T>
162 ) -> Self where ES::Target: EntropySource {
163 let nonce = Nonce::from_entropy_source(entropy_source);
164 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
165 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
167 offer: OfferContents {
168 chains: None, metadata: Some(metadata), amount: None, description,
169 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
170 supported_quantity: Quantity::One, signing_pubkey: node_id,
172 metadata_strategy: core::marker::PhantomData,
173 secp_ctx: Some(secp_ctx),
178 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
179 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
180 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
182 /// See [`Offer::chains`] on how this relates to the payment currency.
184 /// Successive calls to this method will add another chain hash.
185 pub fn chain(mut self, network: Network) -> Self {
186 let chains = self.offer.chains.get_or_insert_with(Vec::new);
187 let chain = ChainHash::using_genesis_block(network);
188 if !chains.contains(&chain) {
195 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
197 /// Successive calls to this method will override the previous setting.
198 pub fn amount_msats(self, amount_msats: u64) -> Self {
199 self.amount(Amount::Bitcoin { amount_msats })
202 /// Sets the [`Offer::amount`].
204 /// Successive calls to this method will override the previous setting.
205 pub(super) fn amount(mut self, amount: Amount) -> Self {
206 self.offer.amount = Some(amount);
210 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
211 /// already passed is valid and can be checked for using [`Offer::is_expired`].
213 /// Successive calls to this method will override the previous setting.
214 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
215 self.offer.absolute_expiry = Some(absolute_expiry);
219 /// Sets the [`Offer::issuer`].
221 /// Successive calls to this method will override the previous setting.
222 pub fn issuer(mut self, issuer: String) -> Self {
223 self.offer.issuer = Some(issuer);
227 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
228 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
230 /// Successive calls to this method will add another blinded path. Caller is responsible for not
231 /// adding duplicate paths.
232 pub fn path(mut self, path: BlindedPath) -> Self {
233 self.offer.paths.get_or_insert_with(Vec::new).push(path);
237 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
238 /// [`Quantity::One`].
240 /// Successive calls to this method will override the previous setting.
241 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
242 self.offer.supported_quantity = quantity;
246 /// Builds an [`Offer`] from the builder's settings.
247 pub fn build(mut self) -> Result<Offer, SemanticError> {
248 match self.offer.amount {
249 Some(Amount::Bitcoin { amount_msats }) => {
250 if amount_msats > MAX_VALUE_MSAT {
251 return Err(SemanticError::InvalidAmount);
254 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
258 if let Some(chains) = &self.offer.chains {
259 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
260 self.offer.chains = None;
264 Ok(self.build_without_checks())
267 fn build_without_checks(mut self) -> Offer {
268 // Create the metadata for stateless verification of an InvoiceRequest.
269 if let Some(mut metadata) = self.offer.metadata.take() {
270 if metadata.has_derivation_material() {
271 if self.offer.paths.is_none() {
272 metadata = metadata.without_keys();
275 let mut tlv_stream = self.offer.as_tlv_stream();
276 debug_assert_eq!(tlv_stream.metadata, None);
277 tlv_stream.metadata = None;
278 if metadata.derives_keys() {
279 tlv_stream.node_id = None;
282 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
283 metadata = derived_metadata;
284 if let Some(keys) = keys {
285 self.offer.signing_pubkey = keys.public_key();
289 self.offer.metadata = Some(metadata);
292 let mut bytes = Vec::new();
293 self.offer.write(&mut bytes).unwrap();
295 Offer { bytes, contents: self.offer }
300 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
301 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
302 self.offer.features = features;
306 pub(super) fn build_unchecked(self) -> Offer {
307 self.build_without_checks()
311 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
313 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
314 /// customer may request an [`Invoice`] for a specific quantity and using an amount sufficient to
315 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
317 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
320 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
322 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
323 /// [`Invoice`]: crate::offers::invoice::Invoice
324 #[derive(Clone, Debug)]
325 #[cfg_attr(test, derive(PartialEq))]
327 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
329 pub(super) bytes: Vec<u8>,
330 pub(super) contents: OfferContents,
333 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an [`Invoice`].
335 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
336 /// [`Invoice`]: crate::offers::invoice::Invoice
337 #[derive(Clone, Debug)]
338 #[cfg_attr(test, derive(PartialEq))]
339 pub(super) struct OfferContents {
340 chains: Option<Vec<ChainHash>>,
341 metadata: Option<Metadata>,
342 amount: Option<Amount>,
344 features: OfferFeatures,
345 absolute_expiry: Option<Duration>,
346 issuer: Option<String>,
347 paths: Option<Vec<BlindedPath>>,
348 supported_quantity: Quantity,
349 signing_pubkey: PublicKey,
353 // TODO: Return a slice once ChainHash has constants.
354 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
355 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
356 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
357 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
358 /// for the selected chain.
359 pub fn chains(&self) -> Vec<ChainHash> {
360 self.contents.chains()
363 pub(super) fn implied_chain(&self) -> ChainHash {
364 self.contents.implied_chain()
367 /// Returns whether the given chain is supported by the offer.
368 pub fn supports_chain(&self, chain: ChainHash) -> bool {
369 self.contents.supports_chain(chain)
372 // TODO: Link to corresponding method in `InvoiceRequest`.
373 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
374 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
375 pub fn metadata(&self) -> Option<&Vec<u8>> {
376 self.contents.metadata()
379 /// The minimum amount required for a successful payment of a single item.
380 pub fn amount(&self) -> Option<&Amount> {
381 self.contents.amount()
384 /// A complete description of the purpose of the payment. Intended to be displayed to the user
385 /// but with the caveat that it has not been verified in any way.
386 pub fn description(&self) -> PrintableString {
387 PrintableString(&self.contents.description)
390 /// Features pertaining to the offer.
391 pub fn features(&self) -> &OfferFeatures {
392 &self.contents.features
395 /// Duration since the Unix epoch when an invoice should no longer be requested.
397 /// If `None`, the offer does not expire.
398 pub fn absolute_expiry(&self) -> Option<Duration> {
399 self.contents.absolute_expiry
402 /// Whether the offer has expired.
403 #[cfg(feature = "std")]
404 pub fn is_expired(&self) -> bool {
405 self.contents.is_expired()
408 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
409 /// displayed to the user but with the caveat that it has not been verified in any way.
410 pub fn issuer(&self) -> Option<PrintableString> {
411 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
414 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
415 /// recipient privacy by obfuscating its node id.
416 pub fn paths(&self) -> &[BlindedPath] {
417 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
420 /// The quantity of items supported.
421 pub fn supported_quantity(&self) -> Quantity {
422 self.contents.supported_quantity()
425 /// Returns whether the given quantity is valid for the offer.
426 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
427 self.contents.is_valid_quantity(quantity)
430 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
432 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
433 pub fn expects_quantity(&self) -> bool {
434 self.contents.expects_quantity()
437 /// The public key used by the recipient to sign invoices.
438 pub fn signing_pubkey(&self) -> PublicKey {
439 self.contents.signing_pubkey()
442 /// Similar to [`Offer::request_invoice`] except it:
443 /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
445 /// - sets the [`InvoiceRequest::metadata`] when [`InvoiceRequestBuilder::build`] is called such
446 /// that it can be used to determine if the invoice was requested using a base [`ExpandedKey`]
447 /// from which the payer id was derived.
449 /// Useful to protect the sender's privacy.
451 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
452 /// [`InvoiceRequest::metadata`]: crate::offers::invoice_request::InvoiceRequest::metadata
453 /// [`Invoice::verify`]: crate::offers::invoice::Invoice::verify
454 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
455 pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
456 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
457 ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, SemanticError>
459 ES::Target: EntropySource,
461 if self.features().requires_unknown_bits() {
462 return Err(SemanticError::UnknownRequiredFeatures);
465 Ok(InvoiceRequestBuilder::deriving_payer_id(self, expanded_key, entropy_source, secp_ctx))
468 /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
469 /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
471 /// Useful for recurring payments using the same `payer_id` with different invoices.
473 /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
474 pub fn request_invoice_deriving_metadata<ES: Deref>(
475 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
476 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError>
478 ES::Target: EntropySource,
480 if self.features().requires_unknown_bits() {
481 return Err(SemanticError::UnknownRequiredFeatures);
484 Ok(InvoiceRequestBuilder::deriving_metadata(self, payer_id, expanded_key, entropy_source))
487 /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
488 /// which will be reflected in the `Invoice` response.
490 /// The `metadata` is useful for including information about the derivation of `payer_id` such
491 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
492 /// hashing in the signature calculation.
494 /// This should not leak any information such as by using a simple BIP-32 derivation path.
495 /// Otherwise, payments may be correlated.
497 /// Errors if the offer contains unknown required features.
499 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
500 pub fn request_invoice(
501 &self, metadata: Vec<u8>, payer_id: PublicKey
502 ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError> {
503 if self.features().requires_unknown_bits() {
504 return Err(SemanticError::UnknownRequiredFeatures);
507 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
511 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
512 self.contents.as_tlv_stream()
516 impl AsRef<[u8]> for Offer {
517 fn as_ref(&self) -> &[u8] {
523 pub fn chains(&self) -> Vec<ChainHash> {
524 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
527 pub fn implied_chain(&self) -> ChainHash {
528 ChainHash::using_genesis_block(Network::Bitcoin)
531 pub fn supports_chain(&self, chain: ChainHash) -> bool {
532 self.chains().contains(&chain)
535 pub fn metadata(&self) -> Option<&Vec<u8>> {
536 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
539 #[cfg(feature = "std")]
540 pub(super) fn is_expired(&self) -> bool {
541 match self.absolute_expiry {
542 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
543 Ok(elapsed) => elapsed > seconds_from_epoch,
550 pub fn amount(&self) -> Option<&Amount> {
554 pub(super) fn check_amount_msats_for_quantity(
555 &self, amount_msats: Option<u64>, quantity: Option<u64>
556 ) -> Result<(), SemanticError> {
557 let offer_amount_msats = match self.amount {
559 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
560 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
563 if !self.expects_quantity() || quantity.is_some() {
564 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
565 .ok_or(SemanticError::InvalidAmount)?;
566 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
568 if amount_msats < expected_amount_msats {
569 return Err(SemanticError::InsufficientAmount);
572 if amount_msats > MAX_VALUE_MSAT {
573 return Err(SemanticError::InvalidAmount);
580 pub fn supported_quantity(&self) -> Quantity {
581 self.supported_quantity
584 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
585 let expects_quantity = self.expects_quantity();
587 None if expects_quantity => Err(SemanticError::MissingQuantity),
588 Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
589 Some(quantity) if !self.is_valid_quantity(quantity) => {
590 Err(SemanticError::InvalidQuantity)
596 fn is_valid_quantity(&self, quantity: u64) -> bool {
597 match self.supported_quantity {
598 Quantity::Bounded(n) => quantity <= n.get(),
599 Quantity::Unbounded => quantity > 0,
600 Quantity::One => quantity == 1,
604 fn expects_quantity(&self) -> bool {
605 match self.supported_quantity {
606 Quantity::Bounded(_) => true,
607 Quantity::Unbounded => true,
608 Quantity::One => false,
612 pub(super) fn signing_pubkey(&self) -> PublicKey {
616 /// Verifies that the offer metadata was produced from the offer in the TLV stream.
617 pub(super) fn verify<T: secp256k1::Signing>(
618 &self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
620 match self.metadata() {
622 let tlv_stream = tlv_stream.range(OFFER_TYPES).filter(|record| {
623 match record.r#type {
624 OFFER_METADATA_TYPE => false,
625 OFFER_NODE_ID_TYPE => !self.metadata.as_ref().unwrap().derives_keys(),
629 signer::verify_metadata(
630 metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
637 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
638 let (currency, amount) = match &self.amount {
639 None => (None, None),
640 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
641 Some(Amount::Currency { iso4217_code, amount }) => (
642 Some(iso4217_code), Some(*amount)
647 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
651 chains: self.chains.as_ref(),
652 metadata: self.metadata(),
655 description: Some(&self.description),
657 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
658 paths: self.paths.as_ref(),
659 issuer: self.issuer.as_ref(),
660 quantity_max: self.supported_quantity.to_tlv_record(),
661 node_id: Some(&self.signing_pubkey),
666 impl Writeable for Offer {
667 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
668 WithoutLength(&self.bytes).write(writer)
672 impl Writeable for OfferContents {
673 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
674 self.as_tlv_stream().write(writer)
678 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
679 /// another currency.
680 #[derive(Clone, Debug, PartialEq)]
682 /// An amount of bitcoin.
684 /// The amount in millisatoshi.
687 /// An amount of currency specified using ISO 4712.
689 /// The currency that the amount is denominated in.
690 iso4217_code: CurrencyCode,
691 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
696 /// An ISO 4712 three-letter currency code (e.g., USD).
697 pub type CurrencyCode = [u8; 3];
699 /// Quantity of items supported by an [`Offer`].
700 #[derive(Clone, Copy, Debug, PartialEq)]
702 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
703 /// but is limited (e.g., because of per customer or inventory limits).
705 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
708 /// One or more items. Use when more than one item can be requested without any limit.
710 /// Only one item. Use when only a single item can be requested.
715 fn to_tlv_record(&self) -> Option<u64> {
717 Quantity::Bounded(n) => Some(n.get()),
718 Quantity::Unbounded => Some(0),
719 Quantity::One => None,
724 /// Valid type range for offer TLV records.
725 const OFFER_TYPES: core::ops::Range<u64> = 1..80;
727 /// TLV record type for [`Offer::metadata`].
728 const OFFER_METADATA_TYPE: u64 = 4;
730 /// TLV record type for [`Offer::signing_pubkey`].
731 const OFFER_NODE_ID_TYPE: u64 = 22;
733 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
734 (2, chains: (Vec<ChainHash>, WithoutLength)),
735 (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
736 (6, currency: CurrencyCode),
737 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
738 (10, description: (String, WithoutLength)),
739 (12, features: (OfferFeatures, WithoutLength)),
740 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
741 (16, paths: (Vec<BlindedPath>, WithoutLength)),
742 (18, issuer: (String, WithoutLength)),
743 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
744 (OFFER_NODE_ID_TYPE, node_id: PublicKey),
747 impl Bech32Encode for Offer {
748 const BECH32_HRP: &'static str = "lno";
751 impl FromStr for Offer {
752 type Err = ParseError;
754 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
755 Self::from_bech32_str(s)
759 impl TryFrom<Vec<u8>> for Offer {
760 type Error = ParseError;
762 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
763 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
764 let ParsedMessage { bytes, tlv_stream } = offer;
765 let contents = OfferContents::try_from(tlv_stream)?;
766 Ok(Offer { bytes, contents })
770 impl TryFrom<OfferTlvStream> for OfferContents {
771 type Error = SemanticError;
773 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
775 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
776 issuer, quantity_max, node_id,
779 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
781 let amount = match (currency, amount) {
782 (None, None) => None,
783 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
784 return Err(SemanticError::InvalidAmount);
786 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
787 (Some(_), None) => return Err(SemanticError::MissingAmount),
788 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
791 let description = match description {
792 None => return Err(SemanticError::MissingDescription),
793 Some(description) => description,
796 let features = features.unwrap_or_else(OfferFeatures::empty);
798 let absolute_expiry = absolute_expiry
799 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
801 let supported_quantity = match quantity_max {
802 None => Quantity::One,
803 Some(0) => Quantity::Unbounded,
804 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
807 let signing_pubkey = match node_id {
808 None => return Err(SemanticError::MissingSigningPubkey),
809 Some(node_id) => node_id,
813 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
814 supported_quantity, signing_pubkey,
819 impl core::fmt::Display for Offer {
820 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
821 self.fmt_bech32_str(f)
827 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
829 use bitcoin::blockdata::constants::ChainHash;
830 use bitcoin::network::constants::Network;
831 use bitcoin::secp256k1::Secp256k1;
832 use core::convert::TryFrom;
833 use core::num::NonZeroU64;
834 use core::time::Duration;
835 use crate::chain::keysinterface::KeyMaterial;
836 use crate::ln::features::OfferFeatures;
837 use crate::ln::inbound_payment::ExpandedKey;
838 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
839 use crate::offers::parse::{ParseError, SemanticError};
840 use crate::offers::test_utils::*;
841 use crate::onion_message::{BlindedHop, BlindedPath};
842 use crate::util::ser::{BigSize, Writeable};
843 use crate::util::string::PrintableString;
846 fn builds_offer_with_defaults() {
847 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
849 let mut buffer = Vec::new();
850 offer.write(&mut buffer).unwrap();
852 assert_eq!(offer.bytes, buffer.as_slice());
853 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
854 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
855 assert_eq!(offer.metadata(), None);
856 assert_eq!(offer.amount(), None);
857 assert_eq!(offer.description(), PrintableString("foo"));
858 assert_eq!(offer.features(), &OfferFeatures::empty());
859 assert_eq!(offer.absolute_expiry(), None);
860 #[cfg(feature = "std")]
861 assert!(!offer.is_expired());
862 assert_eq!(offer.paths(), &[]);
863 assert_eq!(offer.issuer(), None);
864 assert_eq!(offer.supported_quantity(), Quantity::One);
865 assert_eq!(offer.signing_pubkey(), pubkey(42));
868 offer.as_tlv_stream(),
874 description: Some(&String::from("foo")),
876 absolute_expiry: None,
880 node_id: Some(&pubkey(42)),
884 if let Err(e) = Offer::try_from(buffer) {
885 panic!("error parsing offer: {:?}", e);
890 fn builds_offer_with_chains() {
891 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
892 let testnet = ChainHash::using_genesis_block(Network::Testnet);
894 let offer = OfferBuilder::new("foo".into(), pubkey(42))
895 .chain(Network::Bitcoin)
898 assert!(offer.supports_chain(mainnet));
899 assert_eq!(offer.chains(), vec![mainnet]);
900 assert_eq!(offer.as_tlv_stream().chains, None);
902 let offer = OfferBuilder::new("foo".into(), pubkey(42))
903 .chain(Network::Testnet)
906 assert!(offer.supports_chain(testnet));
907 assert_eq!(offer.chains(), vec![testnet]);
908 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
910 let offer = OfferBuilder::new("foo".into(), pubkey(42))
911 .chain(Network::Testnet)
912 .chain(Network::Testnet)
915 assert!(offer.supports_chain(testnet));
916 assert_eq!(offer.chains(), vec![testnet]);
917 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
919 let offer = OfferBuilder::new("foo".into(), pubkey(42))
920 .chain(Network::Bitcoin)
921 .chain(Network::Testnet)
924 assert!(offer.supports_chain(mainnet));
925 assert!(offer.supports_chain(testnet));
926 assert_eq!(offer.chains(), vec![mainnet, testnet]);
927 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
931 fn builds_offer_with_metadata() {
932 let offer = OfferBuilder::new("foo".into(), pubkey(42))
933 .metadata(vec![42; 32]).unwrap()
936 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
937 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
939 let offer = OfferBuilder::new("foo".into(), pubkey(42))
940 .metadata(vec![42; 32]).unwrap()
941 .metadata(vec![43; 32]).unwrap()
944 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
945 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
949 fn builds_offer_with_metadata_derived() {
950 let desc = "foo".to_string();
951 let node_id = recipient_pubkey();
952 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
953 let entropy = FixedEntropy {};
954 let secp_ctx = Secp256k1::new();
956 let offer = OfferBuilder
957 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
960 assert_eq!(offer.signing_pubkey(), node_id);
962 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
964 .sign(payer_sign).unwrap();
965 assert!(invoice_request.verify(&expanded_key, &secp_ctx));
967 // Fails verification with altered offer field
968 let mut tlv_stream = offer.as_tlv_stream();
969 tlv_stream.amount = Some(100);
971 let mut encoded_offer = Vec::new();
972 tlv_stream.write(&mut encoded_offer).unwrap();
974 let invoice_request = Offer::try_from(encoded_offer).unwrap()
975 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
977 .sign(payer_sign).unwrap();
978 assert!(!invoice_request.verify(&expanded_key, &secp_ctx));
980 // Fails verification with altered metadata
981 let mut tlv_stream = offer.as_tlv_stream();
982 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
983 tlv_stream.metadata = Some(&metadata);
985 let mut encoded_offer = Vec::new();
986 tlv_stream.write(&mut encoded_offer).unwrap();
988 let invoice_request = Offer::try_from(encoded_offer).unwrap()
989 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
991 .sign(payer_sign).unwrap();
992 assert!(!invoice_request.verify(&expanded_key, &secp_ctx));
996 fn builds_offer_with_derived_signing_pubkey() {
997 let desc = "foo".to_string();
998 let node_id = recipient_pubkey();
999 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1000 let entropy = FixedEntropy {};
1001 let secp_ctx = Secp256k1::new();
1003 let blinded_path = BlindedPath {
1004 introduction_node_id: pubkey(40),
1005 blinding_point: pubkey(41),
1007 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1008 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1012 let offer = OfferBuilder
1013 ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1017 assert_ne!(offer.signing_pubkey(), node_id);
1019 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1021 .sign(payer_sign).unwrap();
1022 assert!(invoice_request.verify(&expanded_key, &secp_ctx));
1024 // Fails verification with altered offer field
1025 let mut tlv_stream = offer.as_tlv_stream();
1026 tlv_stream.amount = Some(100);
1028 let mut encoded_offer = Vec::new();
1029 tlv_stream.write(&mut encoded_offer).unwrap();
1031 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1032 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1034 .sign(payer_sign).unwrap();
1035 assert!(!invoice_request.verify(&expanded_key, &secp_ctx));
1037 // Fails verification with altered signing pubkey
1038 let mut tlv_stream = offer.as_tlv_stream();
1039 let signing_pubkey = pubkey(1);
1040 tlv_stream.node_id = Some(&signing_pubkey);
1042 let mut encoded_offer = Vec::new();
1043 tlv_stream.write(&mut encoded_offer).unwrap();
1045 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1046 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1048 .sign(payer_sign).unwrap();
1049 assert!(!invoice_request.verify(&expanded_key, &secp_ctx));
1053 fn builds_offer_with_amount() {
1054 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1055 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1057 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1061 let tlv_stream = offer.as_tlv_stream();
1062 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1063 assert_eq!(tlv_stream.amount, Some(1000));
1064 assert_eq!(tlv_stream.currency, None);
1066 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1067 .amount(currency_amount.clone());
1068 let tlv_stream = builder.offer.as_tlv_stream();
1069 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1070 assert_eq!(tlv_stream.amount, Some(10));
1071 assert_eq!(tlv_stream.currency, Some(b"USD"));
1072 match builder.build() {
1073 Ok(_) => panic!("expected error"),
1074 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
1077 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1078 .amount(currency_amount.clone())
1079 .amount(bitcoin_amount.clone())
1082 let tlv_stream = offer.as_tlv_stream();
1083 assert_eq!(tlv_stream.amount, Some(1000));
1084 assert_eq!(tlv_stream.currency, None);
1086 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1087 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1088 Ok(_) => panic!("expected error"),
1089 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1094 fn builds_offer_with_features() {
1095 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1096 .features_unchecked(OfferFeatures::unknown())
1099 assert_eq!(offer.features(), &OfferFeatures::unknown());
1100 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1102 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1103 .features_unchecked(OfferFeatures::unknown())
1104 .features_unchecked(OfferFeatures::empty())
1107 assert_eq!(offer.features(), &OfferFeatures::empty());
1108 assert_eq!(offer.as_tlv_stream().features, None);
1112 fn builds_offer_with_absolute_expiry() {
1113 let future_expiry = Duration::from_secs(u64::max_value());
1114 let past_expiry = Duration::from_secs(0);
1116 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1117 .absolute_expiry(future_expiry)
1120 #[cfg(feature = "std")]
1121 assert!(!offer.is_expired());
1122 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1123 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1125 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1126 .absolute_expiry(future_expiry)
1127 .absolute_expiry(past_expiry)
1130 #[cfg(feature = "std")]
1131 assert!(offer.is_expired());
1132 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1133 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1137 fn builds_offer_with_paths() {
1140 introduction_node_id: pubkey(40),
1141 blinding_point: pubkey(41),
1143 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1144 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1148 introduction_node_id: pubkey(40),
1149 blinding_point: pubkey(41),
1151 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1152 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1157 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1158 .path(paths[0].clone())
1159 .path(paths[1].clone())
1162 let tlv_stream = offer.as_tlv_stream();
1163 assert_eq!(offer.paths(), paths.as_slice());
1164 assert_eq!(offer.signing_pubkey(), pubkey(42));
1165 assert_ne!(pubkey(42), pubkey(44));
1166 assert_eq!(tlv_stream.paths, Some(&paths));
1167 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1171 fn builds_offer_with_issuer() {
1172 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1173 .issuer("bar".into())
1176 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1177 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1179 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1180 .issuer("bar".into())
1181 .issuer("baz".into())
1184 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1185 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1189 fn builds_offer_with_supported_quantity() {
1190 let one = NonZeroU64::new(1).unwrap();
1191 let ten = NonZeroU64::new(10).unwrap();
1193 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1194 .supported_quantity(Quantity::One)
1197 let tlv_stream = offer.as_tlv_stream();
1198 assert_eq!(offer.supported_quantity(), Quantity::One);
1199 assert_eq!(tlv_stream.quantity_max, None);
1201 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1202 .supported_quantity(Quantity::Unbounded)
1205 let tlv_stream = offer.as_tlv_stream();
1206 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1207 assert_eq!(tlv_stream.quantity_max, Some(0));
1209 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1210 .supported_quantity(Quantity::Bounded(ten))
1213 let tlv_stream = offer.as_tlv_stream();
1214 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1215 assert_eq!(tlv_stream.quantity_max, Some(10));
1217 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1218 .supported_quantity(Quantity::Bounded(one))
1221 let tlv_stream = offer.as_tlv_stream();
1222 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1223 assert_eq!(tlv_stream.quantity_max, Some(1));
1225 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1226 .supported_quantity(Quantity::Bounded(ten))
1227 .supported_quantity(Quantity::One)
1230 let tlv_stream = offer.as_tlv_stream();
1231 assert_eq!(offer.supported_quantity(), Quantity::One);
1232 assert_eq!(tlv_stream.quantity_max, None);
1236 fn fails_requesting_invoice_with_unknown_required_features() {
1237 match OfferBuilder::new("foo".into(), pubkey(42))
1238 .features_unchecked(OfferFeatures::unknown())
1240 .request_invoice(vec![1; 32], pubkey(43))
1242 Ok(_) => panic!("expected error"),
1243 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1248 fn parses_offer_with_chains() {
1249 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1250 .chain(Network::Bitcoin)
1251 .chain(Network::Testnet)
1254 if let Err(e) = offer.to_string().parse::<Offer>() {
1255 panic!("error parsing offer: {:?}", e);
1260 fn parses_offer_with_amount() {
1261 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1262 .amount(Amount::Bitcoin { amount_msats: 1000 })
1265 if let Err(e) = offer.to_string().parse::<Offer>() {
1266 panic!("error parsing offer: {:?}", e);
1269 let mut tlv_stream = offer.as_tlv_stream();
1270 tlv_stream.amount = Some(1000);
1271 tlv_stream.currency = Some(b"USD");
1273 let mut encoded_offer = Vec::new();
1274 tlv_stream.write(&mut encoded_offer).unwrap();
1276 if let Err(e) = Offer::try_from(encoded_offer) {
1277 panic!("error parsing offer: {:?}", e);
1280 let mut tlv_stream = offer.as_tlv_stream();
1281 tlv_stream.amount = None;
1282 tlv_stream.currency = Some(b"USD");
1284 let mut encoded_offer = Vec::new();
1285 tlv_stream.write(&mut encoded_offer).unwrap();
1287 match Offer::try_from(encoded_offer) {
1288 Ok(_) => panic!("expected error"),
1289 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1292 let mut tlv_stream = offer.as_tlv_stream();
1293 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1294 tlv_stream.currency = None;
1296 let mut encoded_offer = Vec::new();
1297 tlv_stream.write(&mut encoded_offer).unwrap();
1299 match Offer::try_from(encoded_offer) {
1300 Ok(_) => panic!("expected error"),
1301 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1306 fn parses_offer_with_description() {
1307 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1308 if let Err(e) = offer.to_string().parse::<Offer>() {
1309 panic!("error parsing offer: {:?}", e);
1312 let mut tlv_stream = offer.as_tlv_stream();
1313 tlv_stream.description = None;
1315 let mut encoded_offer = Vec::new();
1316 tlv_stream.write(&mut encoded_offer).unwrap();
1318 match Offer::try_from(encoded_offer) {
1319 Ok(_) => panic!("expected error"),
1321 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1327 fn parses_offer_with_paths() {
1328 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1330 introduction_node_id: pubkey(40),
1331 blinding_point: pubkey(41),
1333 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1334 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1338 introduction_node_id: pubkey(40),
1339 blinding_point: pubkey(41),
1341 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1342 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1347 if let Err(e) = offer.to_string().parse::<Offer>() {
1348 panic!("error parsing offer: {:?}", e);
1351 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1352 builder.offer.paths = Some(vec![]);
1354 let offer = builder.build().unwrap();
1355 if let Err(e) = offer.to_string().parse::<Offer>() {
1356 panic!("error parsing offer: {:?}", e);
1361 fn parses_offer_with_quantity() {
1362 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1363 .supported_quantity(Quantity::One)
1366 if let Err(e) = offer.to_string().parse::<Offer>() {
1367 panic!("error parsing offer: {:?}", e);
1370 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1371 .supported_quantity(Quantity::Unbounded)
1374 if let Err(e) = offer.to_string().parse::<Offer>() {
1375 panic!("error parsing offer: {:?}", e);
1378 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1379 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1382 if let Err(e) = offer.to_string().parse::<Offer>() {
1383 panic!("error parsing offer: {:?}", e);
1386 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1387 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1390 if let Err(e) = offer.to_string().parse::<Offer>() {
1391 panic!("error parsing offer: {:?}", e);
1396 fn parses_offer_with_node_id() {
1397 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1398 if let Err(e) = offer.to_string().parse::<Offer>() {
1399 panic!("error parsing offer: {:?}", e);
1402 let mut tlv_stream = offer.as_tlv_stream();
1403 tlv_stream.node_id = None;
1405 let mut encoded_offer = Vec::new();
1406 tlv_stream.write(&mut encoded_offer).unwrap();
1408 match Offer::try_from(encoded_offer) {
1409 Ok(_) => panic!("expected error"),
1411 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1417 fn fails_parsing_offer_with_extra_tlv_records() {
1418 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1420 let mut encoded_offer = Vec::new();
1421 offer.write(&mut encoded_offer).unwrap();
1422 BigSize(80).write(&mut encoded_offer).unwrap();
1423 BigSize(32).write(&mut encoded_offer).unwrap();
1424 [42u8; 32].write(&mut encoded_offer).unwrap();
1426 match Offer::try_from(encoded_offer) {
1427 Ok(_) => panic!("expected error"),
1428 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1435 use super::{Offer, ParseError};
1436 use bitcoin::bech32;
1437 use crate::ln::msgs::DecodeError;
1439 // TODO: Remove once test vectors are updated.
1442 fn encodes_offer_as_bech32_without_checksum() {
1443 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1444 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1445 let reencoded_offer = offer.to_string();
1446 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1447 assert_eq!(reencoded_offer, encoded_offer);
1450 // TODO: Remove once test vectors are updated.
1453 fn parses_bech32_encoded_offers() {
1455 // BOLT 12 test vectors
1456 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1457 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1458 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1459 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1460 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1461 // Two blinded paths
1462 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1464 for encoded_offer in &offers {
1465 if let Err(e) = encoded_offer.parse::<Offer>() {
1466 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1472 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1474 // BOLT 12 test vectors
1475 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1476 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1477 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1478 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1479 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1481 for encoded_offer in &offers {
1482 match encoded_offer.parse::<Offer>() {
1483 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1484 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1491 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1492 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1493 match encoded_offer.parse::<Offer>() {
1494 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1495 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1500 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1501 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1502 match encoded_offer.parse::<Offer>() {
1503 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1504 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1509 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1510 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1511 match encoded_offer.parse::<Offer>() {
1512 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1513 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),