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::InvoiceRequestBuilder;
83 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
84 use crate::offers::signer::{Metadata, MetadataMaterial};
85 use crate::onion_message::BlindedPath;
86 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
87 use crate::util::string::PrintableString;
89 use crate::prelude::*;
91 #[cfg(feature = "std")]
92 use std::time::SystemTime;
94 const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
96 /// Builds an [`Offer`] for the "offer to be paid" flow.
98 /// See [module-level documentation] for usage.
100 /// [module-level documentation]: self
101 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
102 offer: OfferContents,
103 metadata_strategy: core::marker::PhantomData<M>,
104 secp_ctx: Option<&'a Secp256k1<T>>,
107 /// Indicates how [`Offer::metadata`] may be set.
108 pub trait MetadataStrategy {}
110 /// [`Offer::metadata`] may be explicitly set or left empty.
111 pub struct ExplicitMetadata {}
113 /// [`Offer::metadata`] will be derived.
114 pub struct DerivedMetadata {}
116 impl MetadataStrategy for ExplicitMetadata {}
117 impl MetadataStrategy for DerivedMetadata {}
119 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
120 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
121 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
122 /// while the offer is valid.
124 /// Use a different pubkey per offer to avoid correlating offers.
125 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
127 offer: OfferContents {
128 chains: None, metadata: None, amount: None, description,
129 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
130 supported_quantity: Quantity::One, signing_pubkey,
132 metadata_strategy: core::marker::PhantomData,
137 /// Sets the [`Offer::metadata`] to the given bytes.
139 /// Successive calls to this method will override the previous setting.
140 pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, SemanticError> {
141 self.offer.metadata = Some(Metadata::Bytes(metadata));
146 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
147 /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
148 /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
149 /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
150 /// provided `node_id` is used for the signing pubkey.
152 /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used to
153 /// verify that an [`InvoiceRequest`] was produced for the offer given an [`ExpandedKey`].
155 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
156 /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
157 pub fn deriving_signing_pubkey<ES: Deref>(
158 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
159 secp_ctx: &'a Secp256k1<T>
160 ) -> Self where ES::Target: EntropySource {
161 let nonce = Nonce::from_entropy_source(entropy_source);
162 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
163 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
165 offer: OfferContents {
166 chains: None, metadata: Some(metadata), amount: None, description,
167 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
168 supported_quantity: Quantity::One, signing_pubkey: node_id,
170 metadata_strategy: core::marker::PhantomData,
171 secp_ctx: Some(secp_ctx),
176 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
177 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
178 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
180 /// See [`Offer::chains`] on how this relates to the payment currency.
182 /// Successive calls to this method will add another chain hash.
183 pub fn chain(mut self, network: Network) -> Self {
184 let chains = self.offer.chains.get_or_insert_with(Vec::new);
185 let chain = ChainHash::using_genesis_block(network);
186 if !chains.contains(&chain) {
193 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
195 /// Successive calls to this method will override the previous setting.
196 pub fn amount_msats(self, amount_msats: u64) -> Self {
197 self.amount(Amount::Bitcoin { amount_msats })
200 /// Sets the [`Offer::amount`].
202 /// Successive calls to this method will override the previous setting.
203 pub(super) fn amount(mut self, amount: Amount) -> Self {
204 self.offer.amount = Some(amount);
208 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
209 /// already passed is valid and can be checked for using [`Offer::is_expired`].
211 /// Successive calls to this method will override the previous setting.
212 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
213 self.offer.absolute_expiry = Some(absolute_expiry);
217 /// Sets the [`Offer::issuer`].
219 /// Successive calls to this method will override the previous setting.
220 pub fn issuer(mut self, issuer: String) -> Self {
221 self.offer.issuer = Some(issuer);
225 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
226 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
228 /// Successive calls to this method will add another blinded path. Caller is responsible for not
229 /// adding duplicate paths.
230 pub fn path(mut self, path: BlindedPath) -> Self {
231 self.offer.paths.get_or_insert_with(Vec::new).push(path);
235 /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
236 /// [`Quantity::One`].
238 /// Successive calls to this method will override the previous setting.
239 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
240 self.offer.supported_quantity = quantity;
244 /// Builds an [`Offer`] from the builder's settings.
245 pub fn build(mut self) -> Result<Offer, SemanticError> {
246 match self.offer.amount {
247 Some(Amount::Bitcoin { amount_msats }) => {
248 if amount_msats > MAX_VALUE_MSAT {
249 return Err(SemanticError::InvalidAmount);
252 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
256 if let Some(chains) = &self.offer.chains {
257 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
258 self.offer.chains = None;
262 Ok(self.build_without_checks())
265 fn build_without_checks(mut self) -> Offer {
266 // Create the metadata for stateless verification of an InvoiceRequest.
267 if let Some(mut metadata) = self.offer.metadata.take() {
268 if metadata.has_derivation_material() {
269 if self.offer.paths.is_none() {
270 metadata = metadata.without_keys();
273 let mut tlv_stream = self.offer.as_tlv_stream();
274 debug_assert_eq!(tlv_stream.metadata, None);
275 tlv_stream.metadata = None;
276 if metadata.derives_keys() {
277 tlv_stream.node_id = None;
280 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
281 metadata = derived_metadata;
282 if let Some(keys) = keys {
283 self.offer.signing_pubkey = keys.public_key();
287 self.offer.metadata = Some(metadata);
290 let mut bytes = Vec::new();
291 self.offer.write(&mut bytes).unwrap();
293 Offer { bytes, contents: self.offer }
298 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
299 fn features_unchecked(mut self, features: OfferFeatures) -> Self {
300 self.offer.features = features;
304 pub(super) fn build_unchecked(self) -> Offer {
305 self.build_without_checks()
309 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
311 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
312 /// customer may request an [`Invoice`] for a specific quantity and using an amount sufficient to
313 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
315 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
318 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
320 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
321 /// [`Invoice`]: crate::offers::invoice::Invoice
322 #[derive(Clone, Debug)]
323 #[cfg_attr(test, derive(PartialEq))]
325 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
327 pub(super) bytes: Vec<u8>,
328 pub(super) contents: OfferContents,
331 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an [`Invoice`].
333 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
334 /// [`Invoice`]: crate::offers::invoice::Invoice
335 #[derive(Clone, Debug)]
336 #[cfg_attr(test, derive(PartialEq))]
337 pub(super) struct OfferContents {
338 chains: Option<Vec<ChainHash>>,
339 metadata: Option<Metadata>,
340 amount: Option<Amount>,
342 features: OfferFeatures,
343 absolute_expiry: Option<Duration>,
344 issuer: Option<String>,
345 paths: Option<Vec<BlindedPath>>,
346 supported_quantity: Quantity,
347 signing_pubkey: PublicKey,
351 // TODO: Return a slice once ChainHash has constants.
352 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
353 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
354 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
355 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
356 /// for the selected chain.
357 pub fn chains(&self) -> Vec<ChainHash> {
358 self.contents.chains()
361 pub(super) fn implied_chain(&self) -> ChainHash {
362 self.contents.implied_chain()
365 /// Returns whether the given chain is supported by the offer.
366 pub fn supports_chain(&self, chain: ChainHash) -> bool {
367 self.contents.supports_chain(chain)
370 // TODO: Link to corresponding method in `InvoiceRequest`.
371 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
372 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
373 pub fn metadata(&self) -> Option<&Vec<u8>> {
374 self.contents.metadata()
377 /// The minimum amount required for a successful payment of a single item.
378 pub fn amount(&self) -> Option<&Amount> {
379 self.contents.amount()
382 /// A complete description of the purpose of the payment. Intended to be displayed to the user
383 /// but with the caveat that it has not been verified in any way.
384 pub fn description(&self) -> PrintableString {
385 PrintableString(&self.contents.description)
388 /// Features pertaining to the offer.
389 pub fn features(&self) -> &OfferFeatures {
390 &self.contents.features
393 /// Duration since the Unix epoch when an invoice should no longer be requested.
395 /// If `None`, the offer does not expire.
396 pub fn absolute_expiry(&self) -> Option<Duration> {
397 self.contents.absolute_expiry
400 /// Whether the offer has expired.
401 #[cfg(feature = "std")]
402 pub fn is_expired(&self) -> bool {
403 self.contents.is_expired()
406 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
407 /// displayed to the user but with the caveat that it has not been verified in any way.
408 pub fn issuer(&self) -> Option<PrintableString> {
409 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
412 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
413 /// recipient privacy by obfuscating its node id.
414 pub fn paths(&self) -> &[BlindedPath] {
415 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
418 /// The quantity of items supported.
419 pub fn supported_quantity(&self) -> Quantity {
420 self.contents.supported_quantity()
423 /// Returns whether the given quantity is valid for the offer.
424 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
425 self.contents.is_valid_quantity(quantity)
428 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
430 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
431 pub fn expects_quantity(&self) -> bool {
432 self.contents.expects_quantity()
435 /// The public key used by the recipient to sign invoices.
436 pub fn signing_pubkey(&self) -> PublicKey {
437 self.contents.signing_pubkey()
440 /// Creates an [`InvoiceRequest`] for the offer with the given `metadata` and `payer_id`, which
441 /// will be reflected in the `Invoice` response.
443 /// The `metadata` is useful for including information about the derivation of `payer_id` such
444 /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
445 /// hashing in the signature calculation.
447 /// This should not leak any information such as by using a simple BIP-32 derivation path.
448 /// Otherwise, payments may be correlated.
450 /// Errors if the offer contains unknown required features.
452 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
453 pub fn request_invoice(
454 &self, metadata: Vec<u8>, payer_id: PublicKey
455 ) -> Result<InvoiceRequestBuilder, SemanticError> {
456 if self.features().requires_unknown_bits() {
457 return Err(SemanticError::UnknownRequiredFeatures);
460 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
464 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
465 self.contents.as_tlv_stream()
469 impl AsRef<[u8]> for Offer {
470 fn as_ref(&self) -> &[u8] {
476 pub fn chains(&self) -> Vec<ChainHash> {
477 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
480 pub fn implied_chain(&self) -> ChainHash {
481 ChainHash::using_genesis_block(Network::Bitcoin)
484 pub fn supports_chain(&self, chain: ChainHash) -> bool {
485 self.chains().contains(&chain)
488 pub fn metadata(&self) -> Option<&Vec<u8>> {
489 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
492 #[cfg(feature = "std")]
493 pub(super) fn is_expired(&self) -> bool {
494 match self.absolute_expiry {
495 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
496 Ok(elapsed) => elapsed > seconds_from_epoch,
503 pub fn amount(&self) -> Option<&Amount> {
507 pub(super) fn check_amount_msats_for_quantity(
508 &self, amount_msats: Option<u64>, quantity: Option<u64>
509 ) -> Result<(), SemanticError> {
510 let offer_amount_msats = match self.amount {
512 Some(Amount::Bitcoin { amount_msats }) => amount_msats,
513 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
516 if !self.expects_quantity() || quantity.is_some() {
517 let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
518 .ok_or(SemanticError::InvalidAmount)?;
519 let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
521 if amount_msats < expected_amount_msats {
522 return Err(SemanticError::InsufficientAmount);
525 if amount_msats > MAX_VALUE_MSAT {
526 return Err(SemanticError::InvalidAmount);
533 pub fn supported_quantity(&self) -> Quantity {
534 self.supported_quantity
537 pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
538 let expects_quantity = self.expects_quantity();
540 None if expects_quantity => Err(SemanticError::MissingQuantity),
541 Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
542 Some(quantity) if !self.is_valid_quantity(quantity) => {
543 Err(SemanticError::InvalidQuantity)
549 fn is_valid_quantity(&self, quantity: u64) -> bool {
550 match self.supported_quantity {
551 Quantity::Bounded(n) => quantity <= n.get(),
552 Quantity::Unbounded => quantity > 0,
553 Quantity::One => quantity == 1,
557 fn expects_quantity(&self) -> bool {
558 match self.supported_quantity {
559 Quantity::Bounded(_) => true,
560 Quantity::Unbounded => true,
561 Quantity::One => false,
565 pub(super) fn signing_pubkey(&self) -> PublicKey {
569 pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
570 let (currency, amount) = match &self.amount {
571 None => (None, None),
572 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
573 Some(Amount::Currency { iso4217_code, amount }) => (
574 Some(iso4217_code), Some(*amount)
579 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
583 chains: self.chains.as_ref(),
584 metadata: self.metadata(),
587 description: Some(&self.description),
589 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
590 paths: self.paths.as_ref(),
591 issuer: self.issuer.as_ref(),
592 quantity_max: self.supported_quantity.to_tlv_record(),
593 node_id: Some(&self.signing_pubkey),
598 impl Writeable for Offer {
599 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
600 WithoutLength(&self.bytes).write(writer)
604 impl Writeable for OfferContents {
605 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
606 self.as_tlv_stream().write(writer)
610 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
611 /// another currency.
612 #[derive(Clone, Debug, PartialEq)]
614 /// An amount of bitcoin.
616 /// The amount in millisatoshi.
619 /// An amount of currency specified using ISO 4712.
621 /// The currency that the amount is denominated in.
622 iso4217_code: CurrencyCode,
623 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
628 /// An ISO 4712 three-letter currency code (e.g., USD).
629 pub type CurrencyCode = [u8; 3];
631 /// Quantity of items supported by an [`Offer`].
632 #[derive(Clone, Copy, Debug, PartialEq)]
634 /// Up to a specific number of items (inclusive). Use when more than one item can be requested
635 /// but is limited (e.g., because of per customer or inventory limits).
637 /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
640 /// One or more items. Use when more than one item can be requested without any limit.
642 /// Only one item. Use when only a single item can be requested.
647 fn to_tlv_record(&self) -> Option<u64> {
649 Quantity::Bounded(n) => Some(n.get()),
650 Quantity::Unbounded => Some(0),
651 Quantity::One => None,
656 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
657 (2, chains: (Vec<ChainHash>, WithoutLength)),
658 (4, metadata: (Vec<u8>, WithoutLength)),
659 (6, currency: CurrencyCode),
660 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
661 (10, description: (String, WithoutLength)),
662 (12, features: (OfferFeatures, WithoutLength)),
663 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
664 (16, paths: (Vec<BlindedPath>, WithoutLength)),
665 (18, issuer: (String, WithoutLength)),
666 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
667 (22, node_id: PublicKey),
670 impl Bech32Encode for Offer {
671 const BECH32_HRP: &'static str = "lno";
674 impl FromStr for Offer {
675 type Err = ParseError;
677 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
678 Self::from_bech32_str(s)
682 impl TryFrom<Vec<u8>> for Offer {
683 type Error = ParseError;
685 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
686 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
687 let ParsedMessage { bytes, tlv_stream } = offer;
688 let contents = OfferContents::try_from(tlv_stream)?;
689 Ok(Offer { bytes, contents })
693 impl TryFrom<OfferTlvStream> for OfferContents {
694 type Error = SemanticError;
696 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
698 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
699 issuer, quantity_max, node_id,
702 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
704 let amount = match (currency, amount) {
705 (None, None) => None,
706 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
707 return Err(SemanticError::InvalidAmount);
709 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
710 (Some(_), None) => return Err(SemanticError::MissingAmount),
711 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
714 let description = match description {
715 None => return Err(SemanticError::MissingDescription),
716 Some(description) => description,
719 let features = features.unwrap_or_else(OfferFeatures::empty);
721 let absolute_expiry = absolute_expiry
722 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
724 let supported_quantity = match quantity_max {
725 None => Quantity::One,
726 Some(0) => Quantity::Unbounded,
727 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
730 let signing_pubkey = match node_id {
731 None => return Err(SemanticError::MissingSigningPubkey),
732 Some(node_id) => node_id,
736 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
737 supported_quantity, signing_pubkey,
742 impl core::fmt::Display for Offer {
743 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
744 self.fmt_bech32_str(f)
750 use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
752 use bitcoin::blockdata::constants::ChainHash;
753 use bitcoin::network::constants::Network;
754 use core::convert::TryFrom;
755 use core::num::NonZeroU64;
756 use core::time::Duration;
757 use crate::ln::features::OfferFeatures;
758 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
759 use crate::offers::parse::{ParseError, SemanticError};
760 use crate::offers::test_utils::*;
761 use crate::onion_message::{BlindedHop, BlindedPath};
762 use crate::util::ser::{BigSize, Writeable};
763 use crate::util::string::PrintableString;
766 fn builds_offer_with_defaults() {
767 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
769 let mut buffer = Vec::new();
770 offer.write(&mut buffer).unwrap();
772 assert_eq!(offer.bytes, buffer.as_slice());
773 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
774 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
775 assert_eq!(offer.metadata(), None);
776 assert_eq!(offer.amount(), None);
777 assert_eq!(offer.description(), PrintableString("foo"));
778 assert_eq!(offer.features(), &OfferFeatures::empty());
779 assert_eq!(offer.absolute_expiry(), None);
780 #[cfg(feature = "std")]
781 assert!(!offer.is_expired());
782 assert_eq!(offer.paths(), &[]);
783 assert_eq!(offer.issuer(), None);
784 assert_eq!(offer.supported_quantity(), Quantity::One);
785 assert_eq!(offer.signing_pubkey(), pubkey(42));
788 offer.as_tlv_stream(),
794 description: Some(&String::from("foo")),
796 absolute_expiry: None,
800 node_id: Some(&pubkey(42)),
804 if let Err(e) = Offer::try_from(buffer) {
805 panic!("error parsing offer: {:?}", e);
810 fn builds_offer_with_chains() {
811 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
812 let testnet = ChainHash::using_genesis_block(Network::Testnet);
814 let offer = OfferBuilder::new("foo".into(), pubkey(42))
815 .chain(Network::Bitcoin)
818 assert!(offer.supports_chain(mainnet));
819 assert_eq!(offer.chains(), vec![mainnet]);
820 assert_eq!(offer.as_tlv_stream().chains, None);
822 let offer = OfferBuilder::new("foo".into(), pubkey(42))
823 .chain(Network::Testnet)
826 assert!(offer.supports_chain(testnet));
827 assert_eq!(offer.chains(), vec![testnet]);
828 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
830 let offer = OfferBuilder::new("foo".into(), pubkey(42))
831 .chain(Network::Testnet)
832 .chain(Network::Testnet)
835 assert!(offer.supports_chain(testnet));
836 assert_eq!(offer.chains(), vec![testnet]);
837 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
839 let offer = OfferBuilder::new("foo".into(), pubkey(42))
840 .chain(Network::Bitcoin)
841 .chain(Network::Testnet)
844 assert!(offer.supports_chain(mainnet));
845 assert!(offer.supports_chain(testnet));
846 assert_eq!(offer.chains(), vec![mainnet, testnet]);
847 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
851 fn builds_offer_with_metadata() {
852 let offer = OfferBuilder::new("foo".into(), pubkey(42))
853 .metadata(vec![42; 32]).unwrap()
856 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
857 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
859 let offer = OfferBuilder::new("foo".into(), pubkey(42))
860 .metadata(vec![42; 32]).unwrap()
861 .metadata(vec![43; 32]).unwrap()
864 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
865 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
869 fn builds_offer_with_amount() {
870 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
871 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
873 let offer = OfferBuilder::new("foo".into(), pubkey(42))
877 let tlv_stream = offer.as_tlv_stream();
878 assert_eq!(offer.amount(), Some(&bitcoin_amount));
879 assert_eq!(tlv_stream.amount, Some(1000));
880 assert_eq!(tlv_stream.currency, None);
882 let builder = OfferBuilder::new("foo".into(), pubkey(42))
883 .amount(currency_amount.clone());
884 let tlv_stream = builder.offer.as_tlv_stream();
885 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
886 assert_eq!(tlv_stream.amount, Some(10));
887 assert_eq!(tlv_stream.currency, Some(b"USD"));
888 match builder.build() {
889 Ok(_) => panic!("expected error"),
890 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
893 let offer = OfferBuilder::new("foo".into(), pubkey(42))
894 .amount(currency_amount.clone())
895 .amount(bitcoin_amount.clone())
898 let tlv_stream = offer.as_tlv_stream();
899 assert_eq!(tlv_stream.amount, Some(1000));
900 assert_eq!(tlv_stream.currency, None);
902 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
903 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
904 Ok(_) => panic!("expected error"),
905 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
910 fn builds_offer_with_features() {
911 let offer = OfferBuilder::new("foo".into(), pubkey(42))
912 .features_unchecked(OfferFeatures::unknown())
915 assert_eq!(offer.features(), &OfferFeatures::unknown());
916 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
918 let offer = OfferBuilder::new("foo".into(), pubkey(42))
919 .features_unchecked(OfferFeatures::unknown())
920 .features_unchecked(OfferFeatures::empty())
923 assert_eq!(offer.features(), &OfferFeatures::empty());
924 assert_eq!(offer.as_tlv_stream().features, None);
928 fn builds_offer_with_absolute_expiry() {
929 let future_expiry = Duration::from_secs(u64::max_value());
930 let past_expiry = Duration::from_secs(0);
932 let offer = OfferBuilder::new("foo".into(), pubkey(42))
933 .absolute_expiry(future_expiry)
936 #[cfg(feature = "std")]
937 assert!(!offer.is_expired());
938 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
939 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
941 let offer = OfferBuilder::new("foo".into(), pubkey(42))
942 .absolute_expiry(future_expiry)
943 .absolute_expiry(past_expiry)
946 #[cfg(feature = "std")]
947 assert!(offer.is_expired());
948 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
949 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
953 fn builds_offer_with_paths() {
956 introduction_node_id: pubkey(40),
957 blinding_point: pubkey(41),
959 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
960 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
964 introduction_node_id: pubkey(40),
965 blinding_point: pubkey(41),
967 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
968 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
973 let offer = OfferBuilder::new("foo".into(), pubkey(42))
974 .path(paths[0].clone())
975 .path(paths[1].clone())
978 let tlv_stream = offer.as_tlv_stream();
979 assert_eq!(offer.paths(), paths.as_slice());
980 assert_eq!(offer.signing_pubkey(), pubkey(42));
981 assert_ne!(pubkey(42), pubkey(44));
982 assert_eq!(tlv_stream.paths, Some(&paths));
983 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
987 fn builds_offer_with_issuer() {
988 let offer = OfferBuilder::new("foo".into(), pubkey(42))
989 .issuer("bar".into())
992 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
993 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
995 let offer = OfferBuilder::new("foo".into(), pubkey(42))
996 .issuer("bar".into())
997 .issuer("baz".into())
1000 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1001 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1005 fn builds_offer_with_supported_quantity() {
1006 let one = NonZeroU64::new(1).unwrap();
1007 let ten = NonZeroU64::new(10).unwrap();
1009 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1010 .supported_quantity(Quantity::One)
1013 let tlv_stream = offer.as_tlv_stream();
1014 assert_eq!(offer.supported_quantity(), Quantity::One);
1015 assert_eq!(tlv_stream.quantity_max, None);
1017 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1018 .supported_quantity(Quantity::Unbounded)
1021 let tlv_stream = offer.as_tlv_stream();
1022 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1023 assert_eq!(tlv_stream.quantity_max, Some(0));
1025 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1026 .supported_quantity(Quantity::Bounded(ten))
1029 let tlv_stream = offer.as_tlv_stream();
1030 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1031 assert_eq!(tlv_stream.quantity_max, Some(10));
1033 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1034 .supported_quantity(Quantity::Bounded(one))
1037 let tlv_stream = offer.as_tlv_stream();
1038 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1039 assert_eq!(tlv_stream.quantity_max, Some(1));
1041 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1042 .supported_quantity(Quantity::Bounded(ten))
1043 .supported_quantity(Quantity::One)
1046 let tlv_stream = offer.as_tlv_stream();
1047 assert_eq!(offer.supported_quantity(), Quantity::One);
1048 assert_eq!(tlv_stream.quantity_max, None);
1052 fn fails_requesting_invoice_with_unknown_required_features() {
1053 match OfferBuilder::new("foo".into(), pubkey(42))
1054 .features_unchecked(OfferFeatures::unknown())
1056 .request_invoice(vec![1; 32], pubkey(43))
1058 Ok(_) => panic!("expected error"),
1059 Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1064 fn parses_offer_with_chains() {
1065 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1066 .chain(Network::Bitcoin)
1067 .chain(Network::Testnet)
1070 if let Err(e) = offer.to_string().parse::<Offer>() {
1071 panic!("error parsing offer: {:?}", e);
1076 fn parses_offer_with_amount() {
1077 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1078 .amount(Amount::Bitcoin { amount_msats: 1000 })
1081 if let Err(e) = offer.to_string().parse::<Offer>() {
1082 panic!("error parsing offer: {:?}", e);
1085 let mut tlv_stream = offer.as_tlv_stream();
1086 tlv_stream.amount = Some(1000);
1087 tlv_stream.currency = Some(b"USD");
1089 let mut encoded_offer = Vec::new();
1090 tlv_stream.write(&mut encoded_offer).unwrap();
1092 if let Err(e) = Offer::try_from(encoded_offer) {
1093 panic!("error parsing offer: {:?}", e);
1096 let mut tlv_stream = offer.as_tlv_stream();
1097 tlv_stream.amount = None;
1098 tlv_stream.currency = Some(b"USD");
1100 let mut encoded_offer = Vec::new();
1101 tlv_stream.write(&mut encoded_offer).unwrap();
1103 match Offer::try_from(encoded_offer) {
1104 Ok(_) => panic!("expected error"),
1105 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1108 let mut tlv_stream = offer.as_tlv_stream();
1109 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1110 tlv_stream.currency = None;
1112 let mut encoded_offer = Vec::new();
1113 tlv_stream.write(&mut encoded_offer).unwrap();
1115 match Offer::try_from(encoded_offer) {
1116 Ok(_) => panic!("expected error"),
1117 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1122 fn parses_offer_with_description() {
1123 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1124 if let Err(e) = offer.to_string().parse::<Offer>() {
1125 panic!("error parsing offer: {:?}", e);
1128 let mut tlv_stream = offer.as_tlv_stream();
1129 tlv_stream.description = None;
1131 let mut encoded_offer = Vec::new();
1132 tlv_stream.write(&mut encoded_offer).unwrap();
1134 match Offer::try_from(encoded_offer) {
1135 Ok(_) => panic!("expected error"),
1137 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1143 fn parses_offer_with_paths() {
1144 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1146 introduction_node_id: pubkey(40),
1147 blinding_point: pubkey(41),
1149 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1150 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1154 introduction_node_id: pubkey(40),
1155 blinding_point: pubkey(41),
1157 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1158 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1163 if let Err(e) = offer.to_string().parse::<Offer>() {
1164 panic!("error parsing offer: {:?}", e);
1167 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1168 builder.offer.paths = Some(vec![]);
1170 let offer = builder.build().unwrap();
1171 if let Err(e) = offer.to_string().parse::<Offer>() {
1172 panic!("error parsing offer: {:?}", e);
1177 fn parses_offer_with_quantity() {
1178 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1179 .supported_quantity(Quantity::One)
1182 if let Err(e) = offer.to_string().parse::<Offer>() {
1183 panic!("error parsing offer: {:?}", e);
1186 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1187 .supported_quantity(Quantity::Unbounded)
1190 if let Err(e) = offer.to_string().parse::<Offer>() {
1191 panic!("error parsing offer: {:?}", e);
1194 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1195 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1198 if let Err(e) = offer.to_string().parse::<Offer>() {
1199 panic!("error parsing offer: {:?}", e);
1202 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1203 .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1206 if let Err(e) = offer.to_string().parse::<Offer>() {
1207 panic!("error parsing offer: {:?}", e);
1212 fn parses_offer_with_node_id() {
1213 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1214 if let Err(e) = offer.to_string().parse::<Offer>() {
1215 panic!("error parsing offer: {:?}", e);
1218 let mut tlv_stream = offer.as_tlv_stream();
1219 tlv_stream.node_id = None;
1221 let mut encoded_offer = Vec::new();
1222 tlv_stream.write(&mut encoded_offer).unwrap();
1224 match Offer::try_from(encoded_offer) {
1225 Ok(_) => panic!("expected error"),
1227 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1233 fn fails_parsing_offer_with_extra_tlv_records() {
1234 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1236 let mut encoded_offer = Vec::new();
1237 offer.write(&mut encoded_offer).unwrap();
1238 BigSize(80).write(&mut encoded_offer).unwrap();
1239 BigSize(32).write(&mut encoded_offer).unwrap();
1240 [42u8; 32].write(&mut encoded_offer).unwrap();
1242 match Offer::try_from(encoded_offer) {
1243 Ok(_) => panic!("expected error"),
1244 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1251 use super::{Offer, ParseError};
1252 use bitcoin::bech32;
1253 use crate::ln::msgs::DecodeError;
1255 // TODO: Remove once test vectors are updated.
1258 fn encodes_offer_as_bech32_without_checksum() {
1259 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1260 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1261 let reencoded_offer = offer.to_string();
1262 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1263 assert_eq!(reencoded_offer, encoded_offer);
1266 // TODO: Remove once test vectors are updated.
1269 fn parses_bech32_encoded_offers() {
1271 // BOLT 12 test vectors
1272 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1273 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1274 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1275 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1276 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1277 // Two blinded paths
1278 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1280 for encoded_offer in &offers {
1281 if let Err(e) = encoded_offer.parse::<Offer>() {
1282 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1288 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1290 // BOLT 12 test vectors
1291 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1292 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1293 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1294 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1295 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1297 for encoded_offer in &offers {
1298 match encoded_offer.parse::<Offer>() {
1299 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1300 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1307 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1308 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1309 match encoded_offer.parse::<Offer>() {
1310 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1311 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1316 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1317 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1318 match encoded_offer.parse::<Offer>() {
1319 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1320 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1325 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1326 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1327 match encoded_offer.parse::<Offer>() {
1328 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1329 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),