]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/offers/offer.rs
Add some no-exporting of more offers code
[rust-lightning] / lightning / src / offers / offer.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Data structures and encoding for `offer` messages.
11 //!
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.
15 //!
16 //! ```
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
20 //!
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
24 //!
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};
29 //!
30 //! # use lightning::blinded_path::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
33 //! #
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
36 //! #
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);
42 //!
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())
51 //!     .build()?;
52 //!
53 //! // Encode as a bech32 string for use in a QR code.
54 //! let encoded_offer = offer.to_string();
55 //!
56 //! // Parse from a bech32 string after scanning from a QR code.
57 //! let offer = encoded_offer.parse::<Offer>()?;
58 //!
59 //! // Encode offer as raw bytes.
60 //! let mut bytes = Vec::new();
61 //! offer.write(&mut bytes).unwrap();
62 //!
63 //! // Decode raw bytes into an offer.
64 //! let offer = Offer::try_from(bytes)?;
65 //! # Ok(())
66 //! # }
67 //! ```
68
69 use bitcoin::blockdata::constants::ChainHash;
70 use bitcoin::network::constants::Network;
71 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
72 use core::convert::TryFrom;
73 use core::num::NonZeroU64;
74 use core::ops::Deref;
75 use core::str::FromStr;
76 use core::time::Duration;
77 use crate::chain::keysinterface::EntropySource;
78 use crate::io;
79 use crate::blinded_path::BlindedPath;
80 use crate::ln::features::OfferFeatures;
81 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
82 use crate::ln::msgs::MAX_VALUE_MSAT;
83 use crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder};
84 use crate::offers::merkle::TlvStream;
85 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
86 use crate::offers::signer::{Metadata, MetadataMaterial, self};
87 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
88 use crate::util::string::PrintableString;
89
90 use crate::prelude::*;
91
92 #[cfg(feature = "std")]
93 use std::time::SystemTime;
94
95 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
96
97 /// Builds an [`Offer`] for the "offer to be paid" flow.
98 ///
99 /// See [module-level documentation] for usage.
100 ///
101 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
102 ///
103 /// [module-level documentation]: self
104 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
105         offer: OfferContents,
106         metadata_strategy: core::marker::PhantomData<M>,
107         secp_ctx: Option<&'a Secp256k1<T>>,
108 }
109
110 /// Indicates how [`Offer::metadata`] may be set.
111 ///
112 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
113 pub trait MetadataStrategy {}
114
115 /// [`Offer::metadata`] may be explicitly set or left empty.
116 ///
117 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
118 pub struct ExplicitMetadata {}
119
120 /// [`Offer::metadata`] will be derived.
121 ///
122 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
123 pub struct DerivedMetadata {}
124
125 impl MetadataStrategy for ExplicitMetadata {}
126 impl MetadataStrategy for DerivedMetadata {}
127
128 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
129         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
130         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
131         /// while the offer is valid.
132         ///
133         /// Use a different pubkey per offer to avoid correlating offers.
134         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
135                 OfferBuilder {
136                         offer: OfferContents {
137                                 chains: None, metadata: None, amount: None, description,
138                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
139                                 supported_quantity: Quantity::One, signing_pubkey,
140                         },
141                         metadata_strategy: core::marker::PhantomData,
142                         secp_ctx: None,
143                 }
144         }
145
146         /// Sets the [`Offer::metadata`] to the given bytes.
147         ///
148         /// Successive calls to this method will override the previous setting.
149         pub fn metadata(mut self, metadata: Vec<u8>) -> Result<Self, SemanticError> {
150                 self.offer.metadata = Some(Metadata::Bytes(metadata));
151                 Ok(self)
152         }
153 }
154
155 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
156         /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
157         /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
158         /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
159         /// provided `node_id` is used for the signing pubkey.
160         ///
161         /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
162         /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
163         /// [`ExpandedKey`].
164         ///
165         /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
166         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
167         pub fn deriving_signing_pubkey<ES: Deref>(
168                 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
169                 secp_ctx: &'a Secp256k1<T>
170         ) -> Self where ES::Target: EntropySource {
171                 let nonce = Nonce::from_entropy_source(entropy_source);
172                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES);
173                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
174                 OfferBuilder {
175                         offer: OfferContents {
176                                 chains: None, metadata: Some(metadata), amount: None, description,
177                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
178                                 supported_quantity: Quantity::One, signing_pubkey: node_id,
179                         },
180                         metadata_strategy: core::marker::PhantomData,
181                         secp_ctx: Some(secp_ctx),
182                 }
183         }
184 }
185
186 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
187         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
188         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
189         ///
190         /// See [`Offer::chains`] on how this relates to the payment currency.
191         ///
192         /// Successive calls to this method will add another chain hash.
193         pub fn chain(mut self, network: Network) -> Self {
194                 let chains = self.offer.chains.get_or_insert_with(Vec::new);
195                 let chain = ChainHash::using_genesis_block(network);
196                 if !chains.contains(&chain) {
197                         chains.push(chain);
198                 }
199
200                 self
201         }
202
203         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
204         ///
205         /// Successive calls to this method will override the previous setting.
206         pub fn amount_msats(self, amount_msats: u64) -> Self {
207                 self.amount(Amount::Bitcoin { amount_msats })
208         }
209
210         /// Sets the [`Offer::amount`].
211         ///
212         /// Successive calls to this method will override the previous setting.
213         pub(super) fn amount(mut self, amount: Amount) -> Self {
214                 self.offer.amount = Some(amount);
215                 self
216         }
217
218         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
219         /// already passed is valid and can be checked for using [`Offer::is_expired`].
220         ///
221         /// Successive calls to this method will override the previous setting.
222         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
223                 self.offer.absolute_expiry = Some(absolute_expiry);
224                 self
225         }
226
227         /// Sets the [`Offer::issuer`].
228         ///
229         /// Successive calls to this method will override the previous setting.
230         pub fn issuer(mut self, issuer: String) -> Self {
231                 self.offer.issuer = Some(issuer);
232                 self
233         }
234
235         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
236         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
237         ///
238         /// Successive calls to this method will add another blinded path. Caller is responsible for not
239         /// adding duplicate paths.
240         pub fn path(mut self, path: BlindedPath) -> Self {
241                 self.offer.paths.get_or_insert_with(Vec::new).push(path);
242                 self
243         }
244
245         /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
246         /// [`Quantity::One`].
247         ///
248         /// Successive calls to this method will override the previous setting.
249         pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
250                 self.offer.supported_quantity = quantity;
251                 self
252         }
253
254         /// Builds an [`Offer`] from the builder's settings.
255         pub fn build(mut self) -> Result<Offer, SemanticError> {
256                 match self.offer.amount {
257                         Some(Amount::Bitcoin { amount_msats }) => {
258                                 if amount_msats > MAX_VALUE_MSAT {
259                                         return Err(SemanticError::InvalidAmount);
260                                 }
261                         },
262                         Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
263                         None => {},
264                 }
265
266                 if let Some(chains) = &self.offer.chains {
267                         if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
268                                 self.offer.chains = None;
269                         }
270                 }
271
272                 Ok(self.build_without_checks())
273         }
274
275         fn build_without_checks(mut self) -> Offer {
276                 // Create the metadata for stateless verification of an InvoiceRequest.
277                 if let Some(mut metadata) = self.offer.metadata.take() {
278                         if metadata.has_derivation_material() {
279                                 if self.offer.paths.is_none() {
280                                         metadata = metadata.without_keys();
281                                 }
282
283                                 let mut tlv_stream = self.offer.as_tlv_stream();
284                                 debug_assert_eq!(tlv_stream.metadata, None);
285                                 tlv_stream.metadata = None;
286                                 if metadata.derives_keys() {
287                                         tlv_stream.node_id = None;
288                                 }
289
290                                 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, self.secp_ctx);
291                                 metadata = derived_metadata;
292                                 if let Some(keys) = keys {
293                                         self.offer.signing_pubkey = keys.public_key();
294                                 }
295                         }
296
297                         self.offer.metadata = Some(metadata);
298                 }
299
300                 let mut bytes = Vec::new();
301                 self.offer.write(&mut bytes).unwrap();
302
303                 Offer { bytes, contents: self.offer }
304         }
305 }
306
307 #[cfg(test)]
308 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
309         fn features_unchecked(mut self, features: OfferFeatures) -> Self {
310                 self.offer.features = features;
311                 self
312         }
313
314         pub(super) fn build_unchecked(self) -> Offer {
315                 self.build_without_checks()
316         }
317 }
318
319 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
320 ///
321 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
322 /// customer may request an [`Invoice`] for a specific quantity and using an amount sufficient to
323 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
324 ///
325 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
326 /// latter.
327 ///
328 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
329 ///
330 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
331 /// [`Invoice`]: crate::offers::invoice::Invoice
332 #[derive(Clone, Debug)]
333 #[cfg_attr(test, derive(PartialEq))]
334 pub struct Offer {
335         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
336         // fields.
337         pub(super) bytes: Vec<u8>,
338         pub(super) contents: OfferContents,
339 }
340
341 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an [`Invoice`].
342 ///
343 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
344 /// [`Invoice`]: crate::offers::invoice::Invoice
345 #[derive(Clone, Debug)]
346 #[cfg_attr(test, derive(PartialEq))]
347 pub(super) struct OfferContents {
348         chains: Option<Vec<ChainHash>>,
349         metadata: Option<Metadata>,
350         amount: Option<Amount>,
351         description: String,
352         features: OfferFeatures,
353         absolute_expiry: Option<Duration>,
354         issuer: Option<String>,
355         paths: Option<Vec<BlindedPath>>,
356         supported_quantity: Quantity,
357         signing_pubkey: PublicKey,
358 }
359
360 impl Offer {
361         // TODO: Return a slice once ChainHash has constants.
362         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
363         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
364         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
365         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
366         /// for the selected chain.
367         pub fn chains(&self) -> Vec<ChainHash> {
368                 self.contents.chains()
369         }
370
371         pub(super) fn implied_chain(&self) -> ChainHash {
372                 self.contents.implied_chain()
373         }
374
375         /// Returns whether the given chain is supported by the offer.
376         pub fn supports_chain(&self, chain: ChainHash) -> bool {
377                 self.contents.supports_chain(chain)
378         }
379
380         // TODO: Link to corresponding method in `InvoiceRequest`.
381         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
382         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
383         pub fn metadata(&self) -> Option<&Vec<u8>> {
384                 self.contents.metadata()
385         }
386
387         /// The minimum amount required for a successful payment of a single item.
388         pub fn amount(&self) -> Option<&Amount> {
389                 self.contents.amount()
390         }
391
392         /// A complete description of the purpose of the payment. Intended to be displayed to the user
393         /// but with the caveat that it has not been verified in any way.
394         pub fn description(&self) -> PrintableString {
395                 self.contents.description()
396         }
397
398         /// Features pertaining to the offer.
399         pub fn features(&self) -> &OfferFeatures {
400                 &self.contents.features
401         }
402
403         /// Duration since the Unix epoch when an invoice should no longer be requested.
404         ///
405         /// If `None`, the offer does not expire.
406         pub fn absolute_expiry(&self) -> Option<Duration> {
407                 self.contents.absolute_expiry
408         }
409
410         /// Whether the offer has expired.
411         #[cfg(feature = "std")]
412         pub fn is_expired(&self) -> bool {
413                 self.contents.is_expired()
414         }
415
416         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
417         /// displayed to the user but with the caveat that it has not been verified in any way.
418         pub fn issuer(&self) -> Option<PrintableString> {
419                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
420         }
421
422         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
423         /// recipient privacy by obfuscating its node id.
424         pub fn paths(&self) -> &[BlindedPath] {
425                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
426         }
427
428         /// The quantity of items supported.
429         pub fn supported_quantity(&self) -> Quantity {
430                 self.contents.supported_quantity()
431         }
432
433         /// Returns whether the given quantity is valid for the offer.
434         pub fn is_valid_quantity(&self, quantity: u64) -> bool {
435                 self.contents.is_valid_quantity(quantity)
436         }
437
438         /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
439         ///
440         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
441         pub fn expects_quantity(&self) -> bool {
442                 self.contents.expects_quantity()
443         }
444
445         /// The public key used by the recipient to sign invoices.
446         pub fn signing_pubkey(&self) -> PublicKey {
447                 self.contents.signing_pubkey()
448         }
449
450         /// Similar to [`Offer::request_invoice`] except it:
451         /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
452         ///   request, and
453         /// - sets the [`InvoiceRequest::metadata`] when [`InvoiceRequestBuilder::build`] is called such
454         ///   that it can be used by [`Invoice::verify`] to determine if the invoice was requested using
455         ///   a base [`ExpandedKey`] from which the payer id was derived.
456         ///
457         /// Useful to protect the sender's privacy.
458         ///
459         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
460         ///
461         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
462         /// [`InvoiceRequest::metadata`]: crate::offers::invoice_request::InvoiceRequest::metadata
463         /// [`Invoice::verify`]: crate::offers::invoice::Invoice::verify
464         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
465         pub fn request_invoice_deriving_payer_id<'a, 'b, ES: Deref, T: secp256k1::Signing>(
466                 &'a self, expanded_key: &ExpandedKey, entropy_source: ES, secp_ctx: &'b Secp256k1<T>
467         ) -> Result<InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>, SemanticError>
468         where
469                 ES::Target: EntropySource,
470         {
471                 if self.features().requires_unknown_bits() {
472                         return Err(SemanticError::UnknownRequiredFeatures);
473                 }
474
475                 Ok(InvoiceRequestBuilder::deriving_payer_id(self, expanded_key, entropy_source, secp_ctx))
476         }
477
478         /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
479         /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
480         ///
481         /// Useful for recurring payments using the same `payer_id` with different invoices.
482         ///
483         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
484         ///
485         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
486         pub fn request_invoice_deriving_metadata<ES: Deref>(
487                 &self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES
488         ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError>
489         where
490                 ES::Target: EntropySource,
491         {
492                 if self.features().requires_unknown_bits() {
493                         return Err(SemanticError::UnknownRequiredFeatures);
494                 }
495
496                 Ok(InvoiceRequestBuilder::deriving_metadata(self, payer_id, expanded_key, entropy_source))
497         }
498
499         /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
500         /// which will be reflected in the `Invoice` response.
501         ///
502         /// The `metadata` is useful for including information about the derivation of `payer_id` such
503         /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
504         /// hashing in the signature calculation.
505         ///
506         /// This should not leak any information such as by using a simple BIP-32 derivation path.
507         /// Otherwise, payments may be correlated.
508         ///
509         /// Errors if the offer contains unknown required features.
510         ///
511         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
512         ///
513         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
514         pub fn request_invoice(
515                 &self, metadata: Vec<u8>, payer_id: PublicKey
516         ) -> Result<InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>, SemanticError> {
517                 if self.features().requires_unknown_bits() {
518                         return Err(SemanticError::UnknownRequiredFeatures);
519                 }
520
521                 Ok(InvoiceRequestBuilder::new(self, metadata, payer_id))
522         }
523
524         #[cfg(test)]
525         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
526                 self.contents.as_tlv_stream()
527         }
528 }
529
530 impl AsRef<[u8]> for Offer {
531         fn as_ref(&self) -> &[u8] {
532                 &self.bytes
533         }
534 }
535
536 impl OfferContents {
537         pub fn chains(&self) -> Vec<ChainHash> {
538                 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
539         }
540
541         pub fn implied_chain(&self) -> ChainHash {
542                 ChainHash::using_genesis_block(Network::Bitcoin)
543         }
544
545         pub fn supports_chain(&self, chain: ChainHash) -> bool {
546                 self.chains().contains(&chain)
547         }
548
549         pub fn metadata(&self) -> Option<&Vec<u8>> {
550                 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
551         }
552
553         pub fn description(&self) -> PrintableString {
554                 PrintableString(&self.description)
555         }
556
557         #[cfg(feature = "std")]
558         pub(super) fn is_expired(&self) -> bool {
559                 match self.absolute_expiry {
560                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
561                                 Ok(elapsed) => elapsed > seconds_from_epoch,
562                                 Err(_) => false,
563                         },
564                         None => false,
565                 }
566         }
567
568         pub fn amount(&self) -> Option<&Amount> {
569                 self.amount.as_ref()
570         }
571
572         pub(super) fn check_amount_msats_for_quantity(
573                 &self, amount_msats: Option<u64>, quantity: Option<u64>
574         ) -> Result<(), SemanticError> {
575                 let offer_amount_msats = match self.amount {
576                         None => 0,
577                         Some(Amount::Bitcoin { amount_msats }) => amount_msats,
578                         Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
579                 };
580
581                 if !self.expects_quantity() || quantity.is_some() {
582                         let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
583                                 .ok_or(SemanticError::InvalidAmount)?;
584                         let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
585
586                         if amount_msats < expected_amount_msats {
587                                 return Err(SemanticError::InsufficientAmount);
588                         }
589
590                         if amount_msats > MAX_VALUE_MSAT {
591                                 return Err(SemanticError::InvalidAmount);
592                         }
593                 }
594
595                 Ok(())
596         }
597
598         pub fn supported_quantity(&self) -> Quantity {
599                 self.supported_quantity
600         }
601
602         pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), SemanticError> {
603                 let expects_quantity = self.expects_quantity();
604                 match quantity {
605                         None if expects_quantity => Err(SemanticError::MissingQuantity),
606                         Some(_) if !expects_quantity => Err(SemanticError::UnexpectedQuantity),
607                         Some(quantity) if !self.is_valid_quantity(quantity) => {
608                                 Err(SemanticError::InvalidQuantity)
609                         },
610                         _ => Ok(()),
611                 }
612         }
613
614         fn is_valid_quantity(&self, quantity: u64) -> bool {
615                 match self.supported_quantity {
616                         Quantity::Bounded(n) => quantity <= n.get(),
617                         Quantity::Unbounded => quantity > 0,
618                         Quantity::One => quantity == 1,
619                 }
620         }
621
622         fn expects_quantity(&self) -> bool {
623                 match self.supported_quantity {
624                         Quantity::Bounded(_) => true,
625                         Quantity::Unbounded => true,
626                         Quantity::One => false,
627                 }
628         }
629
630         pub(super) fn signing_pubkey(&self) -> PublicKey {
631                 self.signing_pubkey
632         }
633
634         /// Verifies that the offer metadata was produced from the offer in the TLV stream.
635         pub(super) fn verify<T: secp256k1::Signing>(
636                 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
637         ) -> Result<Option<KeyPair>, ()> {
638                 match self.metadata() {
639                         Some(metadata) => {
640                                 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
641                                         match record.r#type {
642                                                 OFFER_METADATA_TYPE => false,
643                                                 OFFER_NODE_ID_TYPE => !self.metadata.as_ref().unwrap().derives_keys(),
644                                                 _ => true,
645                                         }
646                                 });
647                                 signer::verify_metadata(
648                                         metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
649                                 )
650                         },
651                         None => Err(()),
652                 }
653         }
654
655         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
656                 let (currency, amount) = match &self.amount {
657                         None => (None, None),
658                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
659                         Some(Amount::Currency { iso4217_code, amount }) => (
660                                 Some(iso4217_code), Some(*amount)
661                         ),
662                 };
663
664                 let features = {
665                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
666                 };
667
668                 OfferTlvStreamRef {
669                         chains: self.chains.as_ref(),
670                         metadata: self.metadata(),
671                         currency,
672                         amount,
673                         description: Some(&self.description),
674                         features,
675                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
676                         paths: self.paths.as_ref(),
677                         issuer: self.issuer.as_ref(),
678                         quantity_max: self.supported_quantity.to_tlv_record(),
679                         node_id: Some(&self.signing_pubkey),
680                 }
681         }
682 }
683
684 impl Writeable for Offer {
685         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
686                 WithoutLength(&self.bytes).write(writer)
687         }
688 }
689
690 impl Writeable for OfferContents {
691         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692                 self.as_tlv_stream().write(writer)
693         }
694 }
695
696 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
697 /// another currency.
698 #[derive(Clone, Debug, PartialEq)]
699 pub enum Amount {
700         /// An amount of bitcoin.
701         Bitcoin {
702                 /// The amount in millisatoshi.
703                 amount_msats: u64,
704         },
705         /// An amount of currency specified using ISO 4712.
706         Currency {
707                 /// The currency that the amount is denominated in.
708                 ///
709                 /// This is not exported to bindings users as bindings have troubles with type aliases to
710                 /// byte arrays.
711                 iso4217_code: CurrencyCode,
712                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
713                 amount: u64,
714         },
715 }
716
717 /// An ISO 4712 three-letter currency code (e.g., USD).
718 pub(crate) type CurrencyCode = [u8; 3];
719
720 /// Quantity of items supported by an [`Offer`].
721 #[derive(Clone, Copy, Debug, PartialEq)]
722 pub enum Quantity {
723         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
724         /// but is limited (e.g., because of per customer or inventory limits).
725         ///
726         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
727         /// is supported.
728         Bounded(/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
729                 NonZeroU64),
730         /// One or more items. Use when more than one item can be requested without any limit.
731         Unbounded,
732         /// Only one item. Use when only a single item can be requested.
733         One,
734 }
735
736 impl Quantity {
737         fn to_tlv_record(&self) -> Option<u64> {
738                 match self {
739                         Quantity::Bounded(n) => Some(n.get()),
740                         Quantity::Unbounded => Some(0),
741                         Quantity::One => None,
742                 }
743         }
744 }
745
746 /// Valid type range for offer TLV records.
747 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
748
749 /// TLV record type for [`Offer::metadata`].
750 const OFFER_METADATA_TYPE: u64 = 4;
751
752 /// TLV record type for [`Offer::signing_pubkey`].
753 const OFFER_NODE_ID_TYPE: u64 = 22;
754
755 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
756         (2, chains: (Vec<ChainHash>, WithoutLength)),
757         (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
758         (6, currency: CurrencyCode),
759         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
760         (10, description: (String, WithoutLength)),
761         (12, features: (OfferFeatures, WithoutLength)),
762         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
763         (16, paths: (Vec<BlindedPath>, WithoutLength)),
764         (18, issuer: (String, WithoutLength)),
765         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
766         (OFFER_NODE_ID_TYPE, node_id: PublicKey),
767 });
768
769 impl Bech32Encode for Offer {
770         const BECH32_HRP: &'static str = "lno";
771 }
772
773 impl FromStr for Offer {
774         type Err = ParseError;
775
776         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
777                 Self::from_bech32_str(s)
778         }
779 }
780
781 impl TryFrom<Vec<u8>> for Offer {
782         type Error = ParseError;
783
784         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
785                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
786                 let ParsedMessage { bytes, tlv_stream } = offer;
787                 let contents = OfferContents::try_from(tlv_stream)?;
788                 Ok(Offer { bytes, contents })
789         }
790 }
791
792 impl TryFrom<OfferTlvStream> for OfferContents {
793         type Error = SemanticError;
794
795         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
796                 let OfferTlvStream {
797                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
798                         issuer, quantity_max, node_id,
799                 } = tlv_stream;
800
801                 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
802
803                 let amount = match (currency, amount) {
804                         (None, None) => None,
805                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
806                                 return Err(SemanticError::InvalidAmount);
807                         },
808                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
809                         (Some(_), None) => return Err(SemanticError::MissingAmount),
810                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
811                 };
812
813                 let description = match description {
814                         None => return Err(SemanticError::MissingDescription),
815                         Some(description) => description,
816                 };
817
818                 let features = features.unwrap_or_else(OfferFeatures::empty);
819
820                 let absolute_expiry = absolute_expiry
821                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
822
823                 let supported_quantity = match quantity_max {
824                         None => Quantity::One,
825                         Some(0) => Quantity::Unbounded,
826                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
827                 };
828
829                 let signing_pubkey = match node_id {
830                         None => return Err(SemanticError::MissingSigningPubkey),
831                         Some(node_id) => node_id,
832                 };
833
834                 Ok(OfferContents {
835                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
836                         supported_quantity, signing_pubkey,
837                 })
838         }
839 }
840
841 impl core::fmt::Display for Offer {
842         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
843                 self.fmt_bech32_str(f)
844         }
845 }
846
847 #[cfg(test)]
848 mod tests {
849         use super::{Amount, Offer, OfferBuilder, OfferTlvStreamRef, Quantity};
850
851         use bitcoin::blockdata::constants::ChainHash;
852         use bitcoin::network::constants::Network;
853         use bitcoin::secp256k1::Secp256k1;
854         use core::convert::TryFrom;
855         use core::num::NonZeroU64;
856         use core::time::Duration;
857         use crate::blinded_path::{BlindedHop, BlindedPath};
858         use crate::chain::keysinterface::KeyMaterial;
859         use crate::ln::features::OfferFeatures;
860         use crate::ln::inbound_payment::ExpandedKey;
861         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
862         use crate::offers::parse::{ParseError, SemanticError};
863         use crate::offers::test_utils::*;
864         use crate::util::ser::{BigSize, Writeable};
865         use crate::util::string::PrintableString;
866
867         #[test]
868         fn builds_offer_with_defaults() {
869                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
870
871                 let mut buffer = Vec::new();
872                 offer.write(&mut buffer).unwrap();
873
874                 assert_eq!(offer.bytes, buffer.as_slice());
875                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
876                 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
877                 assert_eq!(offer.metadata(), None);
878                 assert_eq!(offer.amount(), None);
879                 assert_eq!(offer.description(), PrintableString("foo"));
880                 assert_eq!(offer.features(), &OfferFeatures::empty());
881                 assert_eq!(offer.absolute_expiry(), None);
882                 #[cfg(feature = "std")]
883                 assert!(!offer.is_expired());
884                 assert_eq!(offer.paths(), &[]);
885                 assert_eq!(offer.issuer(), None);
886                 assert_eq!(offer.supported_quantity(), Quantity::One);
887                 assert_eq!(offer.signing_pubkey(), pubkey(42));
888
889                 assert_eq!(
890                         offer.as_tlv_stream(),
891                         OfferTlvStreamRef {
892                                 chains: None,
893                                 metadata: None,
894                                 currency: None,
895                                 amount: None,
896                                 description: Some(&String::from("foo")),
897                                 features: None,
898                                 absolute_expiry: None,
899                                 paths: None,
900                                 issuer: None,
901                                 quantity_max: None,
902                                 node_id: Some(&pubkey(42)),
903                         },
904                 );
905
906                 if let Err(e) = Offer::try_from(buffer) {
907                         panic!("error parsing offer: {:?}", e);
908                 }
909         }
910
911         #[test]
912         fn builds_offer_with_chains() {
913                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
914                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
915
916                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
917                         .chain(Network::Bitcoin)
918                         .build()
919                         .unwrap();
920                 assert!(offer.supports_chain(mainnet));
921                 assert_eq!(offer.chains(), vec![mainnet]);
922                 assert_eq!(offer.as_tlv_stream().chains, None);
923
924                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
925                         .chain(Network::Testnet)
926                         .build()
927                         .unwrap();
928                 assert!(offer.supports_chain(testnet));
929                 assert_eq!(offer.chains(), vec![testnet]);
930                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
931
932                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
933                         .chain(Network::Testnet)
934                         .chain(Network::Testnet)
935                         .build()
936                         .unwrap();
937                 assert!(offer.supports_chain(testnet));
938                 assert_eq!(offer.chains(), vec![testnet]);
939                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
940
941                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
942                         .chain(Network::Bitcoin)
943                         .chain(Network::Testnet)
944                         .build()
945                         .unwrap();
946                 assert!(offer.supports_chain(mainnet));
947                 assert!(offer.supports_chain(testnet));
948                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
949                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
950         }
951
952         #[test]
953         fn builds_offer_with_metadata() {
954                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
955                         .metadata(vec![42; 32]).unwrap()
956                         .build()
957                         .unwrap();
958                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
959                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
960
961                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
962                         .metadata(vec![42; 32]).unwrap()
963                         .metadata(vec![43; 32]).unwrap()
964                         .build()
965                         .unwrap();
966                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
967                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
968         }
969
970         #[test]
971         fn builds_offer_with_metadata_derived() {
972                 let desc = "foo".to_string();
973                 let node_id = recipient_pubkey();
974                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
975                 let entropy = FixedEntropy {};
976                 let secp_ctx = Secp256k1::new();
977
978                 let offer = OfferBuilder
979                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
980                         .amount_msats(1000)
981                         .build().unwrap();
982                 assert_eq!(offer.signing_pubkey(), node_id);
983
984                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
985                         .build().unwrap()
986                         .sign(payer_sign).unwrap();
987                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
988
989                 // Fails verification with altered offer field
990                 let mut tlv_stream = offer.as_tlv_stream();
991                 tlv_stream.amount = Some(100);
992
993                 let mut encoded_offer = Vec::new();
994                 tlv_stream.write(&mut encoded_offer).unwrap();
995
996                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
997                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
998                         .build().unwrap()
999                         .sign(payer_sign).unwrap();
1000                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1001
1002                 // Fails verification with altered metadata
1003                 let mut tlv_stream = offer.as_tlv_stream();
1004                 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1005                 tlv_stream.metadata = Some(&metadata);
1006
1007                 let mut encoded_offer = Vec::new();
1008                 tlv_stream.write(&mut encoded_offer).unwrap();
1009
1010                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1011                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1012                         .build().unwrap()
1013                         .sign(payer_sign).unwrap();
1014                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1015         }
1016
1017         #[test]
1018         fn builds_offer_with_derived_signing_pubkey() {
1019                 let desc = "foo".to_string();
1020                 let node_id = recipient_pubkey();
1021                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1022                 let entropy = FixedEntropy {};
1023                 let secp_ctx = Secp256k1::new();
1024
1025                 let blinded_path = BlindedPath {
1026                         introduction_node_id: pubkey(40),
1027                         blinding_point: pubkey(41),
1028                         blinded_hops: vec![
1029                                 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1030                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1031                         ],
1032                 };
1033
1034                 let offer = OfferBuilder
1035                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1036                         .amount_msats(1000)
1037                         .path(blinded_path)
1038                         .build().unwrap();
1039                 assert_ne!(offer.signing_pubkey(), node_id);
1040
1041                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1042                         .build().unwrap()
1043                         .sign(payer_sign).unwrap();
1044                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1045
1046                 // Fails verification with altered offer field
1047                 let mut tlv_stream = offer.as_tlv_stream();
1048                 tlv_stream.amount = Some(100);
1049
1050                 let mut encoded_offer = Vec::new();
1051                 tlv_stream.write(&mut encoded_offer).unwrap();
1052
1053                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1054                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1055                         .build().unwrap()
1056                         .sign(payer_sign).unwrap();
1057                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1058
1059                 // Fails verification with altered signing pubkey
1060                 let mut tlv_stream = offer.as_tlv_stream();
1061                 let signing_pubkey = pubkey(1);
1062                 tlv_stream.node_id = Some(&signing_pubkey);
1063
1064                 let mut encoded_offer = Vec::new();
1065                 tlv_stream.write(&mut encoded_offer).unwrap();
1066
1067                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1068                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1069                         .build().unwrap()
1070                         .sign(payer_sign).unwrap();
1071                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1072         }
1073
1074         #[test]
1075         fn builds_offer_with_amount() {
1076                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1077                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1078
1079                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1080                         .amount_msats(1000)
1081                         .build()
1082                         .unwrap();
1083                 let tlv_stream = offer.as_tlv_stream();
1084                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1085                 assert_eq!(tlv_stream.amount, Some(1000));
1086                 assert_eq!(tlv_stream.currency, None);
1087
1088                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1089                         .amount(currency_amount.clone());
1090                 let tlv_stream = builder.offer.as_tlv_stream();
1091                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1092                 assert_eq!(tlv_stream.amount, Some(10));
1093                 assert_eq!(tlv_stream.currency, Some(b"USD"));
1094                 match builder.build() {
1095                         Ok(_) => panic!("expected error"),
1096                         Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
1097                 }
1098
1099                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1100                         .amount(currency_amount.clone())
1101                         .amount(bitcoin_amount.clone())
1102                         .build()
1103                         .unwrap();
1104                 let tlv_stream = offer.as_tlv_stream();
1105                 assert_eq!(tlv_stream.amount, Some(1000));
1106                 assert_eq!(tlv_stream.currency, None);
1107
1108                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1109                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1110                         Ok(_) => panic!("expected error"),
1111                         Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
1112                 }
1113         }
1114
1115         #[test]
1116         fn builds_offer_with_features() {
1117                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1118                         .features_unchecked(OfferFeatures::unknown())
1119                         .build()
1120                         .unwrap();
1121                 assert_eq!(offer.features(), &OfferFeatures::unknown());
1122                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1123
1124                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1125                         .features_unchecked(OfferFeatures::unknown())
1126                         .features_unchecked(OfferFeatures::empty())
1127                         .build()
1128                         .unwrap();
1129                 assert_eq!(offer.features(), &OfferFeatures::empty());
1130                 assert_eq!(offer.as_tlv_stream().features, None);
1131         }
1132
1133         #[test]
1134         fn builds_offer_with_absolute_expiry() {
1135                 let future_expiry = Duration::from_secs(u64::max_value());
1136                 let past_expiry = Duration::from_secs(0);
1137
1138                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1139                         .absolute_expiry(future_expiry)
1140                         .build()
1141                         .unwrap();
1142                 #[cfg(feature = "std")]
1143                 assert!(!offer.is_expired());
1144                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1145                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1146
1147                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1148                         .absolute_expiry(future_expiry)
1149                         .absolute_expiry(past_expiry)
1150                         .build()
1151                         .unwrap();
1152                 #[cfg(feature = "std")]
1153                 assert!(offer.is_expired());
1154                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1155                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1156         }
1157
1158         #[test]
1159         fn builds_offer_with_paths() {
1160                 let paths = vec![
1161                         BlindedPath {
1162                                 introduction_node_id: pubkey(40),
1163                                 blinding_point: pubkey(41),
1164                                 blinded_hops: vec![
1165                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1166                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1167                                 ],
1168                         },
1169                         BlindedPath {
1170                                 introduction_node_id: pubkey(40),
1171                                 blinding_point: pubkey(41),
1172                                 blinded_hops: vec![
1173                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1174                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1175                                 ],
1176                         },
1177                 ];
1178
1179                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1180                         .path(paths[0].clone())
1181                         .path(paths[1].clone())
1182                         .build()
1183                         .unwrap();
1184                 let tlv_stream = offer.as_tlv_stream();
1185                 assert_eq!(offer.paths(), paths.as_slice());
1186                 assert_eq!(offer.signing_pubkey(), pubkey(42));
1187                 assert_ne!(pubkey(42), pubkey(44));
1188                 assert_eq!(tlv_stream.paths, Some(&paths));
1189                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1190         }
1191
1192         #[test]
1193         fn builds_offer_with_issuer() {
1194                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1195                         .issuer("bar".into())
1196                         .build()
1197                         .unwrap();
1198                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1199                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1200
1201                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1202                         .issuer("bar".into())
1203                         .issuer("baz".into())
1204                         .build()
1205                         .unwrap();
1206                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1207                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1208         }
1209
1210         #[test]
1211         fn builds_offer_with_supported_quantity() {
1212                 let one = NonZeroU64::new(1).unwrap();
1213                 let ten = NonZeroU64::new(10).unwrap();
1214
1215                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1216                         .supported_quantity(Quantity::One)
1217                         .build()
1218                         .unwrap();
1219                 let tlv_stream = offer.as_tlv_stream();
1220                 assert_eq!(offer.supported_quantity(), Quantity::One);
1221                 assert_eq!(tlv_stream.quantity_max, None);
1222
1223                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1224                         .supported_quantity(Quantity::Unbounded)
1225                         .build()
1226                         .unwrap();
1227                 let tlv_stream = offer.as_tlv_stream();
1228                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1229                 assert_eq!(tlv_stream.quantity_max, Some(0));
1230
1231                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1232                         .supported_quantity(Quantity::Bounded(ten))
1233                         .build()
1234                         .unwrap();
1235                 let tlv_stream = offer.as_tlv_stream();
1236                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1237                 assert_eq!(tlv_stream.quantity_max, Some(10));
1238
1239                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1240                         .supported_quantity(Quantity::Bounded(one))
1241                         .build()
1242                         .unwrap();
1243                 let tlv_stream = offer.as_tlv_stream();
1244                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1245                 assert_eq!(tlv_stream.quantity_max, Some(1));
1246
1247                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1248                         .supported_quantity(Quantity::Bounded(ten))
1249                         .supported_quantity(Quantity::One)
1250                         .build()
1251                         .unwrap();
1252                 let tlv_stream = offer.as_tlv_stream();
1253                 assert_eq!(offer.supported_quantity(), Quantity::One);
1254                 assert_eq!(tlv_stream.quantity_max, None);
1255         }
1256
1257         #[test]
1258         fn fails_requesting_invoice_with_unknown_required_features() {
1259                 match OfferBuilder::new("foo".into(), pubkey(42))
1260                         .features_unchecked(OfferFeatures::unknown())
1261                         .build().unwrap()
1262                         .request_invoice(vec![1; 32], pubkey(43))
1263                 {
1264                         Ok(_) => panic!("expected error"),
1265                         Err(e) => assert_eq!(e, SemanticError::UnknownRequiredFeatures),
1266                 }
1267         }
1268
1269         #[test]
1270         fn parses_offer_with_chains() {
1271                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1272                         .chain(Network::Bitcoin)
1273                         .chain(Network::Testnet)
1274                         .build()
1275                         .unwrap();
1276                 if let Err(e) = offer.to_string().parse::<Offer>() {
1277                         panic!("error parsing offer: {:?}", e);
1278                 }
1279         }
1280
1281         #[test]
1282         fn parses_offer_with_amount() {
1283                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1284                         .amount(Amount::Bitcoin { amount_msats: 1000 })
1285                         .build()
1286                         .unwrap();
1287                 if let Err(e) = offer.to_string().parse::<Offer>() {
1288                         panic!("error parsing offer: {:?}", e);
1289                 }
1290
1291                 let mut tlv_stream = offer.as_tlv_stream();
1292                 tlv_stream.amount = Some(1000);
1293                 tlv_stream.currency = Some(b"USD");
1294
1295                 let mut encoded_offer = Vec::new();
1296                 tlv_stream.write(&mut encoded_offer).unwrap();
1297
1298                 if let Err(e) = Offer::try_from(encoded_offer) {
1299                         panic!("error parsing offer: {:?}", e);
1300                 }
1301
1302                 let mut tlv_stream = offer.as_tlv_stream();
1303                 tlv_stream.amount = None;
1304                 tlv_stream.currency = Some(b"USD");
1305
1306                 let mut encoded_offer = Vec::new();
1307                 tlv_stream.write(&mut encoded_offer).unwrap();
1308
1309                 match Offer::try_from(encoded_offer) {
1310                         Ok(_) => panic!("expected error"),
1311                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1312                 }
1313
1314                 let mut tlv_stream = offer.as_tlv_stream();
1315                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1316                 tlv_stream.currency = None;
1317
1318                 let mut encoded_offer = Vec::new();
1319                 tlv_stream.write(&mut encoded_offer).unwrap();
1320
1321                 match Offer::try_from(encoded_offer) {
1322                         Ok(_) => panic!("expected error"),
1323                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
1324                 }
1325         }
1326
1327         #[test]
1328         fn parses_offer_with_description() {
1329                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1330                 if let Err(e) = offer.to_string().parse::<Offer>() {
1331                         panic!("error parsing offer: {:?}", e);
1332                 }
1333
1334                 let mut tlv_stream = offer.as_tlv_stream();
1335                 tlv_stream.description = None;
1336
1337                 let mut encoded_offer = Vec::new();
1338                 tlv_stream.write(&mut encoded_offer).unwrap();
1339
1340                 match Offer::try_from(encoded_offer) {
1341                         Ok(_) => panic!("expected error"),
1342                         Err(e) => {
1343                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
1344                         },
1345                 }
1346         }
1347
1348         #[test]
1349         fn parses_offer_with_paths() {
1350                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1351                         .path(BlindedPath {
1352                                 introduction_node_id: pubkey(40),
1353                                 blinding_point: pubkey(41),
1354                                 blinded_hops: vec![
1355                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1356                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1357                                 ],
1358                         })
1359                         .path(BlindedPath {
1360                                 introduction_node_id: pubkey(40),
1361                                 blinding_point: pubkey(41),
1362                                 blinded_hops: vec![
1363                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1364                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1365                                 ],
1366                         })
1367                         .build()
1368                         .unwrap();
1369                 if let Err(e) = offer.to_string().parse::<Offer>() {
1370                         panic!("error parsing offer: {:?}", e);
1371                 }
1372
1373                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1374                 builder.offer.paths = Some(vec![]);
1375
1376                 let offer = builder.build().unwrap();
1377                 if let Err(e) = offer.to_string().parse::<Offer>() {
1378                         panic!("error parsing offer: {:?}", e);
1379                 }
1380         }
1381
1382         #[test]
1383         fn parses_offer_with_quantity() {
1384                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1385                         .supported_quantity(Quantity::One)
1386                         .build()
1387                         .unwrap();
1388                 if let Err(e) = offer.to_string().parse::<Offer>() {
1389                         panic!("error parsing offer: {:?}", e);
1390                 }
1391
1392                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1393                         .supported_quantity(Quantity::Unbounded)
1394                         .build()
1395                         .unwrap();
1396                 if let Err(e) = offer.to_string().parse::<Offer>() {
1397                         panic!("error parsing offer: {:?}", e);
1398                 }
1399
1400                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1401                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1402                         .build()
1403                         .unwrap();
1404                 if let Err(e) = offer.to_string().parse::<Offer>() {
1405                         panic!("error parsing offer: {:?}", e);
1406                 }
1407
1408                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1409                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1410                         .build()
1411                         .unwrap();
1412                 if let Err(e) = offer.to_string().parse::<Offer>() {
1413                         panic!("error parsing offer: {:?}", e);
1414                 }
1415         }
1416
1417         #[test]
1418         fn parses_offer_with_node_id() {
1419                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1420                 if let Err(e) = offer.to_string().parse::<Offer>() {
1421                         panic!("error parsing offer: {:?}", e);
1422                 }
1423
1424                 let mut tlv_stream = offer.as_tlv_stream();
1425                 tlv_stream.node_id = None;
1426
1427                 let mut encoded_offer = Vec::new();
1428                 tlv_stream.write(&mut encoded_offer).unwrap();
1429
1430                 match Offer::try_from(encoded_offer) {
1431                         Ok(_) => panic!("expected error"),
1432                         Err(e) => {
1433                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1434                         },
1435                 }
1436         }
1437
1438         #[test]
1439         fn fails_parsing_offer_with_extra_tlv_records() {
1440                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1441
1442                 let mut encoded_offer = Vec::new();
1443                 offer.write(&mut encoded_offer).unwrap();
1444                 BigSize(80).write(&mut encoded_offer).unwrap();
1445                 BigSize(32).write(&mut encoded_offer).unwrap();
1446                 [42u8; 32].write(&mut encoded_offer).unwrap();
1447
1448                 match Offer::try_from(encoded_offer) {
1449                         Ok(_) => panic!("expected error"),
1450                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1451                 }
1452         }
1453 }
1454
1455 #[cfg(test)]
1456 mod bech32_tests {
1457         use super::{Offer, ParseError};
1458         use bitcoin::bech32;
1459         use crate::ln::msgs::DecodeError;
1460
1461         // TODO: Remove once test vectors are updated.
1462         #[ignore]
1463         #[test]
1464         fn encodes_offer_as_bech32_without_checksum() {
1465                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1466                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1467                 let reencoded_offer = offer.to_string();
1468                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1469                 assert_eq!(reencoded_offer, encoded_offer);
1470         }
1471
1472         // TODO: Remove once test vectors are updated.
1473         #[ignore]
1474         #[test]
1475         fn parses_bech32_encoded_offers() {
1476                 let offers = [
1477                         // BOLT 12 test vectors
1478                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1479                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1480                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1481                         "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1482                         "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+  0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r  y",
1483                         // Two blinded paths
1484                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1485                 ];
1486                 for encoded_offer in &offers {
1487                         if let Err(e) = encoded_offer.parse::<Offer>() {
1488                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1489                         }
1490                 }
1491         }
1492
1493         #[test]
1494         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1495                 let offers = [
1496                         // BOLT 12 test vectors
1497                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1498                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1499                         "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1500                         "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1501                         "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1502                 ];
1503                 for encoded_offer in &offers {
1504                         match encoded_offer.parse::<Offer>() {
1505                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1506                                 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1507                         }
1508                 }
1509
1510         }
1511
1512         #[test]
1513         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1514                 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1515                 match encoded_offer.parse::<Offer>() {
1516                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1517                         Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1518                 }
1519         }
1520
1521         #[test]
1522         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1523                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1524                 match encoded_offer.parse::<Offer>() {
1525                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1526                         Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1527                 }
1528         }
1529
1530         #[test]
1531         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1532                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1533                 match encoded_offer.parse::<Offer>() {
1534                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
1535                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1536                 }
1537         }
1538 }