Add BOLT 12 Offers section to ChannelManager docs
[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 //! # Example
17 //!
18 //! ```
19 //! extern crate bitcoin;
20 //! extern crate core;
21 //! extern crate lightning;
22 //!
23 //! use core::convert::TryFrom;
24 //! use core::num::NonZeroU64;
25 //! use core::time::Duration;
26 //!
27 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
28 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
29 //! use lightning::offers::parse::Bolt12ParseError;
30 //! use lightning::util::ser::{Readable, Writeable};
31 //!
32 //! # use lightning::blinded_path::BlindedPath;
33 //! # #[cfg(feature = "std")]
34 //! # use std::time::SystemTime;
35 //! #
36 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
37 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
38 //! #
39 //! # #[cfg(feature = "std")]
40 //! # fn build() -> Result<(), Bolt12ParseError> {
41 //! let secp_ctx = Secp256k1::new();
42 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
43 //! let pubkey = PublicKey::from(keys);
44 //!
45 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
46 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
47 //!     .amount_msats(20_000)
48 //!     .supported_quantity(Quantity::Unbounded)
49 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
50 //!     .issuer("Foo Bar".to_string())
51 //!     .path(create_blinded_path())
52 //!     .path(create_another_blinded_path())
53 //!     .build()?;
54 //!
55 //! // Encode as a bech32 string for use in a QR code.
56 //! let encoded_offer = offer.to_string();
57 //!
58 //! // Parse from a bech32 string after scanning from a QR code.
59 //! let offer = encoded_offer.parse::<Offer>()?;
60 //!
61 //! // Encode offer as raw bytes.
62 //! let mut bytes = Vec::new();
63 //! offer.write(&mut bytes).unwrap();
64 //!
65 //! // Decode raw bytes into an offer.
66 //! let offer = Offer::try_from(bytes)?;
67 //! # Ok(())
68 //! # }
69 //! ```
70 //!
71 //! # Note
72 //!
73 //! If constructing an [`Offer`] for use with a [`ChannelManager`], use
74 //! [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
75 //!
76 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
77 //! [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
78
79 use bitcoin::blockdata::constants::ChainHash;
80 use bitcoin::network::constants::Network;
81 use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, self};
82 use core::convert::TryFrom;
83 use core::hash::{Hash, Hasher};
84 use core::num::NonZeroU64;
85 use core::ops::Deref;
86 use core::str::FromStr;
87 use core::time::Duration;
88 use crate::sign::EntropySource;
89 use crate::io;
90 use crate::blinded_path::BlindedPath;
91 use crate::ln::channelmanager::PaymentId;
92 use crate::ln::features::OfferFeatures;
93 use crate::ln::inbound_payment::{ExpandedKey, IV_LEN, Nonce};
94 use crate::ln::msgs::MAX_VALUE_MSAT;
95 use crate::offers::merkle::TlvStream;
96 use crate::offers::parse::{Bech32Encode, Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
97 use crate::offers::signer::{Metadata, MetadataMaterial, self};
98 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
99 use crate::util::string::PrintableString;
100
101 #[cfg(not(c_bindings))]
102 use {
103         crate::offers::invoice_request::{DerivedPayerId, ExplicitPayerId, InvoiceRequestBuilder},
104 };
105 #[cfg(c_bindings)]
106 use {
107         crate::offers::invoice_request::{InvoiceRequestWithDerivedPayerIdBuilder, InvoiceRequestWithExplicitPayerIdBuilder},
108 };
109
110 use crate::prelude::*;
111
112 #[cfg(feature = "std")]
113 use std::time::SystemTime;
114
115 pub(super) const IV_BYTES: &[u8; IV_LEN] = b"LDK Offer ~~~~~~";
116
117 /// Builds an [`Offer`] for the "offer to be paid" flow.
118 ///
119 /// See [module-level documentation] for usage.
120 ///
121 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
122 ///
123 /// [module-level documentation]: self
124 pub struct OfferBuilder<'a, M: MetadataStrategy, T: secp256k1::Signing> {
125         offer: OfferContents,
126         metadata_strategy: core::marker::PhantomData<M>,
127         secp_ctx: Option<&'a Secp256k1<T>>,
128 }
129
130 /// Builds an [`Offer`] for the "offer to be paid" flow.
131 ///
132 /// See [module-level documentation] for usage.
133 ///
134 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
135 ///
136 /// [module-level documentation]: self
137 #[cfg(c_bindings)]
138 pub struct OfferWithExplicitMetadataBuilder<'a> {
139         offer: OfferContents,
140         metadata_strategy: core::marker::PhantomData<ExplicitMetadata>,
141         secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
142 }
143
144 /// Builds an [`Offer`] for the "offer to be paid" flow.
145 ///
146 /// See [module-level documentation] for usage.
147 ///
148 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
149 ///
150 /// [module-level documentation]: self
151 #[cfg(c_bindings)]
152 pub struct OfferWithDerivedMetadataBuilder<'a> {
153         offer: OfferContents,
154         metadata_strategy: core::marker::PhantomData<DerivedMetadata>,
155         secp_ctx: Option<&'a Secp256k1<secp256k1::All>>,
156 }
157
158 /// Indicates how [`Offer::metadata`] may be set.
159 ///
160 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
161 pub trait MetadataStrategy {}
162
163 /// [`Offer::metadata`] may be explicitly set or left empty.
164 ///
165 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
166 pub struct ExplicitMetadata {}
167
168 /// [`Offer::metadata`] will be derived.
169 ///
170 /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
171 pub struct DerivedMetadata {}
172
173 impl MetadataStrategy for ExplicitMetadata {}
174
175 impl MetadataStrategy for DerivedMetadata {}
176
177 macro_rules! offer_explicit_metadata_builder_methods { (
178         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr
179 ) => {
180         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
181         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
182         /// while the offer is valid.
183         ///
184         /// Use a different pubkey per offer to avoid correlating offers.
185         ///
186         /// # Note
187         ///
188         /// If constructing an [`Offer`] for use with a [`ChannelManager`], use
189         /// [`ChannelManager::create_offer_builder`] instead of [`OfferBuilder::new`].
190         ///
191         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
192         /// [`ChannelManager::create_offer_builder`]: crate::ln::channelmanager::ChannelManager::create_offer_builder
193         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
194                 Self {
195                         offer: OfferContents {
196                                 chains: None, metadata: None, amount: None, description,
197                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
198                                 supported_quantity: Quantity::One, signing_pubkey,
199                         },
200                         metadata_strategy: core::marker::PhantomData,
201                         secp_ctx: None,
202                 }
203         }
204
205         /// Sets the [`Offer::metadata`] to the given bytes.
206         ///
207         /// Successive calls to this method will override the previous setting.
208         pub fn metadata(mut $self: $self_type, metadata: Vec<u8>) -> Result<$return_type, Bolt12SemanticError> {
209                 $self.offer.metadata = Some(Metadata::Bytes(metadata));
210                 Ok($return_value)
211         }
212 } }
213
214 macro_rules! offer_derived_metadata_builder_methods { ($secp_context: ty) => {
215         /// Similar to [`OfferBuilder::new`] except, if [`OfferBuilder::path`] is called, the signing
216         /// pubkey is derived from the given [`ExpandedKey`] and [`EntropySource`]. This provides
217         /// recipient privacy by using a different signing pubkey for each offer. Otherwise, the
218         /// provided `node_id` is used for the signing pubkey.
219         ///
220         /// Also, sets the metadata when [`OfferBuilder::build`] is called such that it can be used by
221         /// [`InvoiceRequest::verify`] to determine if the request was produced for the offer given an
222         /// [`ExpandedKey`].
223         ///
224         /// [`InvoiceRequest::verify`]: crate::offers::invoice_request::InvoiceRequest::verify
225         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
226         pub fn deriving_signing_pubkey<ES: Deref>(
227                 description: String, node_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
228                 secp_ctx: &'a Secp256k1<$secp_context>
229         ) -> Self where ES::Target: EntropySource {
230                 let nonce = Nonce::from_entropy_source(entropy_source);
231                 let derivation_material = MetadataMaterial::new(nonce, expanded_key, IV_BYTES, None);
232                 let metadata = Metadata::DerivedSigningPubkey(derivation_material);
233                 Self {
234                         offer: OfferContents {
235                                 chains: None, metadata: Some(metadata), amount: None, description,
236                                 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
237                                 supported_quantity: Quantity::One, signing_pubkey: node_id,
238                         },
239                         metadata_strategy: core::marker::PhantomData,
240                         secp_ctx: Some(secp_ctx),
241                 }
242         }
243 } }
244
245 macro_rules! offer_builder_methods { (
246         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
247 ) => {
248         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
249         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
250         ///
251         /// See [`Offer::chains`] on how this relates to the payment currency.
252         ///
253         /// Successive calls to this method will add another chain hash.
254         pub fn chain($self: $self_type, network: Network) -> $return_type {
255                 $self.chain_hash(ChainHash::using_genesis_block(network))
256         }
257
258         /// Adds the [`ChainHash`] to [`Offer::chains`]. If not called, the chain hash of
259         /// [`Network::Bitcoin`] is assumed to be the only one supported.
260         ///
261         /// See [`Offer::chains`] on how this relates to the payment currency.
262         ///
263         /// Successive calls to this method will add another chain hash.
264         pub(crate) fn chain_hash($($self_mut)* $self: $self_type, chain: ChainHash) -> $return_type {
265                 let chains = $self.offer.chains.get_or_insert_with(Vec::new);
266                 if !chains.contains(&chain) {
267                         chains.push(chain);
268                 }
269
270                 $return_value
271         }
272
273         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
274         ///
275         /// Successive calls to this method will override the previous setting.
276         pub fn amount_msats($self: $self_type, amount_msats: u64) -> $return_type {
277                 $self.amount(Amount::Bitcoin { amount_msats })
278         }
279
280         /// Sets the [`Offer::amount`].
281         ///
282         /// Successive calls to this method will override the previous setting.
283         pub(super) fn amount($($self_mut)* $self: $self_type, amount: Amount) -> $return_type {
284                 $self.offer.amount = Some(amount);
285                 $return_value
286         }
287
288         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
289         /// already passed is valid and can be checked for using [`Offer::is_expired`].
290         ///
291         /// Successive calls to this method will override the previous setting.
292         pub fn absolute_expiry($($self_mut)* $self: $self_type, absolute_expiry: Duration) -> $return_type {
293                 $self.offer.absolute_expiry = Some(absolute_expiry);
294                 $return_value
295         }
296
297         /// Sets the [`Offer::issuer`].
298         ///
299         /// Successive calls to this method will override the previous setting.
300         pub fn issuer($($self_mut)* $self: $self_type, issuer: String) -> $return_type {
301                 $self.offer.issuer = Some(issuer);
302                 $return_value
303         }
304
305         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
306         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
307         ///
308         /// Successive calls to this method will add another blinded path. Caller is responsible for not
309         /// adding duplicate paths.
310         pub fn path($($self_mut)* $self: $self_type, path: BlindedPath) -> $return_type {
311                 $self.offer.paths.get_or_insert_with(Vec::new).push(path);
312                 $return_value
313         }
314
315         /// Sets the quantity of items for [`Offer::supported_quantity`]. If not called, defaults to
316         /// [`Quantity::One`].
317         ///
318         /// Successive calls to this method will override the previous setting.
319         pub fn supported_quantity($($self_mut)* $self: $self_type, quantity: Quantity) -> $return_type {
320                 $self.offer.supported_quantity = quantity;
321                 $return_value
322         }
323
324         /// Builds an [`Offer`] from the builder's settings.
325         pub fn build($($self_mut)* $self: $self_type) -> Result<Offer, Bolt12SemanticError> {
326                 match $self.offer.amount {
327                         Some(Amount::Bitcoin { amount_msats }) => {
328                                 if amount_msats > MAX_VALUE_MSAT {
329                                         return Err(Bolt12SemanticError::InvalidAmount);
330                                 }
331                         },
332                         Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
333                         None => {},
334                 }
335
336                 if let Some(chains) = &$self.offer.chains {
337                         if chains.len() == 1 && chains[0] == $self.offer.implied_chain() {
338                                 $self.offer.chains = None;
339                         }
340                 }
341
342                 Ok($self.build_without_checks())
343         }
344
345         fn build_without_checks($($self_mut)* $self: $self_type) -> Offer {
346                 // Create the metadata for stateless verification of an InvoiceRequest.
347                 if let Some(mut metadata) = $self.offer.metadata.take() {
348                         if metadata.has_derivation_material() {
349                                 if $self.offer.paths.is_none() {
350                                         metadata = metadata.without_keys();
351                                 }
352
353                                 let mut tlv_stream = $self.offer.as_tlv_stream();
354                                 debug_assert_eq!(tlv_stream.metadata, None);
355                                 tlv_stream.metadata = None;
356                                 if metadata.derives_recipient_keys() {
357                                         tlv_stream.node_id = None;
358                                 }
359
360                                 let (derived_metadata, keys) = metadata.derive_from(tlv_stream, $self.secp_ctx);
361                                 metadata = derived_metadata;
362                                 if let Some(keys) = keys {
363                                         $self.offer.signing_pubkey = keys.public_key();
364                                 }
365                         }
366
367                         $self.offer.metadata = Some(metadata);
368                 }
369
370                 let mut bytes = Vec::new();
371                 $self.offer.write(&mut bytes).unwrap();
372
373                 Offer {
374                         bytes,
375                         #[cfg(not(c_bindings))]
376                         contents: $self.offer,
377                         #[cfg(c_bindings)]
378                         contents: $self.offer.clone()
379                 }
380         }
381 } }
382
383 #[cfg(test)]
384 macro_rules! offer_builder_test_methods { (
385         $self: ident, $self_type: ty, $return_type: ty, $return_value: expr $(, $self_mut: tt)?
386 ) => {
387         #[cfg_attr(c_bindings, allow(dead_code))]
388         fn features_unchecked($($self_mut)* $self: $self_type, features: OfferFeatures) -> $return_type {
389                 $self.offer.features = features;
390                 $return_value
391         }
392
393         #[cfg_attr(c_bindings, allow(dead_code))]
394         pub(crate) fn clear_chains($($self_mut)* $self: $self_type) -> $return_type {
395                 $self.offer.chains = None;
396                 $return_value
397         }
398
399         #[cfg_attr(c_bindings, allow(dead_code))]
400         pub(crate) fn clear_paths($($self_mut)* $self: $self_type) -> $return_type {
401                 $self.offer.paths = None;
402                 $return_value
403         }
404
405         #[cfg_attr(c_bindings, allow(dead_code))]
406         pub(super) fn build_unchecked($self: $self_type) -> Offer {
407                 $self.build_without_checks()
408         }
409 } }
410
411 impl<'a, M: MetadataStrategy, T: secp256k1::Signing> OfferBuilder<'a, M, T> {
412         offer_builder_methods!(self, Self, Self, self, mut);
413
414         #[cfg(test)]
415         offer_builder_test_methods!(self, Self, Self, self, mut);
416 }
417
418 impl<'a> OfferBuilder<'a, ExplicitMetadata, secp256k1::SignOnly> {
419         offer_explicit_metadata_builder_methods!(self, Self, Self, self);
420 }
421
422 impl<'a, T: secp256k1::Signing> OfferBuilder<'a, DerivedMetadata, T> {
423         offer_derived_metadata_builder_methods!(T);
424 }
425
426 #[cfg(all(c_bindings, not(test)))]
427 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
428         offer_explicit_metadata_builder_methods!(self, &mut Self, (), ());
429         offer_builder_methods!(self, &mut Self, (), ());
430 }
431
432 #[cfg(all(c_bindings, test))]
433 impl<'a> OfferWithExplicitMetadataBuilder<'a> {
434         offer_explicit_metadata_builder_methods!(self, &mut Self, &mut Self, self);
435         offer_builder_methods!(self, &mut Self, &mut Self, self);
436         offer_builder_test_methods!(self, &mut Self, &mut Self, self);
437 }
438
439 #[cfg(all(c_bindings, not(test)))]
440 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
441         offer_derived_metadata_builder_methods!(secp256k1::All);
442         offer_builder_methods!(self, &mut Self, (), ());
443 }
444
445 #[cfg(all(c_bindings, test))]
446 impl<'a> OfferWithDerivedMetadataBuilder<'a> {
447         offer_derived_metadata_builder_methods!(secp256k1::All);
448         offer_builder_methods!(self, &mut Self, &mut Self, self);
449         offer_builder_test_methods!(self, &mut Self, &mut Self, self);
450 }
451
452 #[cfg(c_bindings)]
453 impl<'a> From<OfferBuilder<'a, DerivedMetadata, secp256k1::All>>
454 for OfferWithDerivedMetadataBuilder<'a> {
455         fn from(builder: OfferBuilder<'a, DerivedMetadata, secp256k1::All>) -> Self {
456                 let OfferBuilder { offer, metadata_strategy, secp_ctx } = builder;
457
458                 Self { offer, metadata_strategy, secp_ctx }
459         }
460 }
461
462 #[cfg(c_bindings)]
463 impl<'a> From<OfferWithDerivedMetadataBuilder<'a>>
464 for OfferBuilder<'a, DerivedMetadata, secp256k1::All> {
465         fn from(builder: OfferWithDerivedMetadataBuilder<'a>) -> Self {
466                 let OfferWithDerivedMetadataBuilder { offer, metadata_strategy, secp_ctx } = builder;
467
468                 Self { offer, metadata_strategy, secp_ctx }
469         }
470 }
471
472 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
473 ///
474 /// An offer is a precursor to an [`InvoiceRequest`]. A merchant publishes an offer from which a
475 /// customer may request an [`Bolt12Invoice`] for a specific quantity and using an amount sufficient
476 /// to cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
477 ///
478 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
479 /// latter.
480 ///
481 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
482 ///
483 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
484 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
485 #[derive(Clone, Debug)]
486 pub struct Offer {
487         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
488         // fields.
489         pub(super) bytes: Vec<u8>,
490         pub(super) contents: OfferContents,
491 }
492
493 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or a
494 /// [`Bolt12Invoice`].
495 ///
496 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
497 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
498 #[derive(Clone, Debug)]
499 #[cfg_attr(test, derive(PartialEq))]
500 pub(super) struct OfferContents {
501         chains: Option<Vec<ChainHash>>,
502         metadata: Option<Metadata>,
503         amount: Option<Amount>,
504         description: String,
505         features: OfferFeatures,
506         absolute_expiry: Option<Duration>,
507         issuer: Option<String>,
508         paths: Option<Vec<BlindedPath>>,
509         supported_quantity: Quantity,
510         signing_pubkey: PublicKey,
511 }
512
513 macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
514         // TODO: Return a slice once ChainHash has constants.
515         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
516         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
517         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
518         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
519         /// for the selected chain.
520         pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
521                 $contents.chains()
522         }
523
524         // TODO: Link to corresponding method in `InvoiceRequest`.
525         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
526         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
527         pub fn metadata(&$self) -> Option<&Vec<u8>> {
528                 $contents.metadata()
529         }
530
531         /// The minimum amount required for a successful payment of a single item.
532         pub fn amount(&$self) -> Option<&$crate::offers::offer::Amount> {
533                 $contents.amount()
534         }
535
536         /// A complete description of the purpose of the payment. Intended to be displayed to the user
537         /// but with the caveat that it has not been verified in any way.
538         pub fn description(&$self) -> $crate::util::string::PrintableString {
539                 $contents.description()
540         }
541
542         /// Features pertaining to the offer.
543         pub fn offer_features(&$self) -> &$crate::ln::features::OfferFeatures {
544                 &$contents.features()
545         }
546
547         /// Duration since the Unix epoch when an invoice should no longer be requested.
548         ///
549         /// If `None`, the offer does not expire.
550         pub fn absolute_expiry(&$self) -> Option<core::time::Duration> {
551                 $contents.absolute_expiry()
552         }
553
554         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
555         /// displayed to the user but with the caveat that it has not been verified in any way.
556         pub fn issuer(&$self) -> Option<$crate::util::string::PrintableString> {
557                 $contents.issuer()
558         }
559
560         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
561         /// recipient privacy by obfuscating its node id.
562         pub fn paths(&$self) -> &[$crate::blinded_path::BlindedPath] {
563                 $contents.paths()
564         }
565
566         /// The quantity of items supported.
567         pub fn supported_quantity(&$self) -> $crate::offers::offer::Quantity {
568                 $contents.supported_quantity()
569         }
570
571         /// The public key used by the recipient to sign invoices.
572         pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
573                 $contents.signing_pubkey()
574         }
575 } }
576
577 impl Offer {
578         offer_accessors!(self, self.contents);
579
580         pub(super) fn implied_chain(&self) -> ChainHash {
581                 self.contents.implied_chain()
582         }
583
584         /// Returns whether the given chain is supported by the offer.
585         pub fn supports_chain(&self, chain: ChainHash) -> bool {
586                 self.contents.supports_chain(chain)
587         }
588
589         /// Whether the offer has expired.
590         #[cfg(feature = "std")]
591         pub fn is_expired(&self) -> bool {
592                 self.contents.is_expired()
593         }
594
595         /// Whether the offer has expired given the duration since the Unix epoch.
596         pub fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
597                 self.contents.is_expired_no_std(duration_since_epoch)
598         }
599
600         /// Returns whether the given quantity is valid for the offer.
601         pub fn is_valid_quantity(&self, quantity: u64) -> bool {
602                 self.contents.is_valid_quantity(quantity)
603         }
604
605         /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
606         ///
607         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
608         pub fn expects_quantity(&self) -> bool {
609                 self.contents.expects_quantity()
610         }
611 }
612
613 macro_rules! request_invoice_derived_payer_id { ($self: ident, $builder: ty) => {
614         /// Similar to [`Offer::request_invoice`] except it:
615         /// - derives the [`InvoiceRequest::payer_id`] such that a different key can be used for each
616         ///   request,
617         /// - sets [`InvoiceRequest::payer_metadata`] when [`InvoiceRequestBuilder::build`] is called
618         ///   such that it can be used by [`Bolt12Invoice::verify`] to determine if the invoice was
619         ///   requested using a base [`ExpandedKey`] from which the payer id was derived, and
620         /// - includes the [`PaymentId`] encrypted in [`InvoiceRequest::payer_metadata`] so that it can
621         ///   be used when sending the payment for the requested invoice.
622         ///
623         /// Useful to protect the sender's privacy.
624         ///
625         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
626         /// [`InvoiceRequest::payer_metadata`]: crate::offers::invoice_request::InvoiceRequest::payer_metadata
627         /// [`Bolt12Invoice::verify`]: crate::offers::invoice::Bolt12Invoice::verify
628         /// [`ExpandedKey`]: crate::ln::inbound_payment::ExpandedKey
629         pub fn request_invoice_deriving_payer_id<
630                 'a, 'b, ES: Deref,
631                 #[cfg(not(c_bindings))]
632                 T: secp256k1::Signing
633         >(
634                 &'a $self, expanded_key: &ExpandedKey, entropy_source: ES,
635                 #[cfg(not(c_bindings))]
636                 secp_ctx: &'b Secp256k1<T>,
637                 #[cfg(c_bindings)]
638                 secp_ctx: &'b Secp256k1<secp256k1::All>,
639                 payment_id: PaymentId
640         ) -> Result<$builder, Bolt12SemanticError>
641         where
642                 ES::Target: EntropySource,
643         {
644                 if $self.offer_features().requires_unknown_bits() {
645                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
646                 }
647
648                 Ok(<$builder>::deriving_payer_id($self, expanded_key, entropy_source, secp_ctx, payment_id))
649         }
650 } }
651
652 macro_rules! request_invoice_explicit_payer_id { ($self: ident, $builder: ty) => {
653         /// Similar to [`Offer::request_invoice_deriving_payer_id`] except uses `payer_id` for the
654         /// [`InvoiceRequest::payer_id`] instead of deriving a different key for each request.
655         ///
656         /// Useful for recurring payments using the same `payer_id` with different invoices.
657         ///
658         /// [`InvoiceRequest::payer_id`]: crate::offers::invoice_request::InvoiceRequest::payer_id
659         pub fn request_invoice_deriving_metadata<ES: Deref>(
660                 &$self, payer_id: PublicKey, expanded_key: &ExpandedKey, entropy_source: ES,
661                 payment_id: PaymentId
662         ) -> Result<$builder, Bolt12SemanticError>
663         where
664                 ES::Target: EntropySource,
665         {
666                 if $self.offer_features().requires_unknown_bits() {
667                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
668                 }
669
670                 Ok(<$builder>::deriving_metadata($self, payer_id, expanded_key, entropy_source, payment_id))
671         }
672
673         /// Creates an [`InvoiceRequestBuilder`] for the offer with the given `metadata` and `payer_id`,
674         /// which will be reflected in the `Bolt12Invoice` response.
675         ///
676         /// The `metadata` is useful for including information about the derivation of `payer_id` such
677         /// that invoice response handling can be stateless. Also serves as payer-provided entropy while
678         /// hashing in the signature calculation.
679         ///
680         /// This should not leak any information such as by using a simple BIP-32 derivation path.
681         /// Otherwise, payments may be correlated.
682         ///
683         /// Errors if the offer contains unknown required features.
684         ///
685         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
686         pub fn request_invoice(
687                 &$self, metadata: Vec<u8>, payer_id: PublicKey
688         ) -> Result<$builder, Bolt12SemanticError> {
689                 if $self.offer_features().requires_unknown_bits() {
690                         return Err(Bolt12SemanticError::UnknownRequiredFeatures);
691                 }
692
693                 Ok(<$builder>::new($self, metadata, payer_id))
694         }
695 } }
696
697 #[cfg(not(c_bindings))]
698 impl Offer {
699         request_invoice_derived_payer_id!(self, InvoiceRequestBuilder<'a, 'b, DerivedPayerId, T>);
700         request_invoice_explicit_payer_id!(self, InvoiceRequestBuilder<ExplicitPayerId, secp256k1::SignOnly>);
701 }
702
703 #[cfg(c_bindings)]
704 impl Offer {
705         request_invoice_derived_payer_id!(self, InvoiceRequestWithDerivedPayerIdBuilder<'a, 'b>);
706         request_invoice_explicit_payer_id!(self, InvoiceRequestWithExplicitPayerIdBuilder);
707 }
708
709 #[cfg(test)]
710 impl Offer {
711         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
712                 self.contents.as_tlv_stream()
713         }
714 }
715
716 impl AsRef<[u8]> for Offer {
717         fn as_ref(&self) -> &[u8] {
718                 &self.bytes
719         }
720 }
721
722 impl PartialEq for Offer {
723         fn eq(&self, other: &Self) -> bool {
724                 self.bytes.eq(&other.bytes)
725         }
726 }
727
728 impl Eq for Offer {}
729
730 impl Hash for Offer {
731         fn hash<H: Hasher>(&self, state: &mut H) {
732                 self.bytes.hash(state);
733         }
734 }
735
736 impl OfferContents {
737         pub fn chains(&self) -> Vec<ChainHash> {
738                 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
739         }
740
741         pub fn implied_chain(&self) -> ChainHash {
742                 ChainHash::using_genesis_block(Network::Bitcoin)
743         }
744
745         pub fn supports_chain(&self, chain: ChainHash) -> bool {
746                 self.chains().contains(&chain)
747         }
748
749         pub fn metadata(&self) -> Option<&Vec<u8>> {
750                 self.metadata.as_ref().and_then(|metadata| metadata.as_bytes())
751         }
752
753         pub fn amount(&self) -> Option<&Amount> {
754                 self.amount.as_ref()
755         }
756
757         pub fn description(&self) -> PrintableString {
758                 PrintableString(&self.description)
759         }
760
761         pub fn features(&self) -> &OfferFeatures {
762                 &self.features
763         }
764
765         pub fn absolute_expiry(&self) -> Option<Duration> {
766                 self.absolute_expiry
767         }
768
769         #[cfg(feature = "std")]
770         pub(super) fn is_expired(&self) -> bool {
771                 SystemTime::UNIX_EPOCH
772                         .elapsed()
773                         .map(|duration_since_epoch| self.is_expired_no_std(duration_since_epoch))
774                         .unwrap_or(false)
775         }
776
777         pub(super) fn is_expired_no_std(&self, duration_since_epoch: Duration) -> bool {
778                 self.absolute_expiry
779                         .map(|absolute_expiry| duration_since_epoch > absolute_expiry)
780                         .unwrap_or(false)
781         }
782
783         pub fn issuer(&self) -> Option<PrintableString> {
784                 self.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
785         }
786
787         pub fn paths(&self) -> &[BlindedPath] {
788                 self.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
789         }
790
791         pub(super) fn check_amount_msats_for_quantity(
792                 &self, amount_msats: Option<u64>, quantity: Option<u64>
793         ) -> Result<(), Bolt12SemanticError> {
794                 let offer_amount_msats = match self.amount {
795                         None => 0,
796                         Some(Amount::Bitcoin { amount_msats }) => amount_msats,
797                         Some(Amount::Currency { .. }) => return Err(Bolt12SemanticError::UnsupportedCurrency),
798                 };
799
800                 if !self.expects_quantity() || quantity.is_some() {
801                         let expected_amount_msats = offer_amount_msats.checked_mul(quantity.unwrap_or(1))
802                                 .ok_or(Bolt12SemanticError::InvalidAmount)?;
803                         let amount_msats = amount_msats.unwrap_or(expected_amount_msats);
804
805                         if amount_msats < expected_amount_msats {
806                                 return Err(Bolt12SemanticError::InsufficientAmount);
807                         }
808
809                         if amount_msats > MAX_VALUE_MSAT {
810                                 return Err(Bolt12SemanticError::InvalidAmount);
811                         }
812                 }
813
814                 Ok(())
815         }
816
817         pub fn supported_quantity(&self) -> Quantity {
818                 self.supported_quantity
819         }
820
821         pub(super) fn check_quantity(&self, quantity: Option<u64>) -> Result<(), Bolt12SemanticError> {
822                 let expects_quantity = self.expects_quantity();
823                 match quantity {
824                         None if expects_quantity => Err(Bolt12SemanticError::MissingQuantity),
825                         Some(_) if !expects_quantity => Err(Bolt12SemanticError::UnexpectedQuantity),
826                         Some(quantity) if !self.is_valid_quantity(quantity) => {
827                                 Err(Bolt12SemanticError::InvalidQuantity)
828                         },
829                         _ => Ok(()),
830                 }
831         }
832
833         fn is_valid_quantity(&self, quantity: u64) -> bool {
834                 match self.supported_quantity {
835                         Quantity::Bounded(n) => quantity <= n.get(),
836                         Quantity::Unbounded => quantity > 0,
837                         Quantity::One => quantity == 1,
838                 }
839         }
840
841         fn expects_quantity(&self) -> bool {
842                 match self.supported_quantity {
843                         Quantity::Bounded(_) => true,
844                         Quantity::Unbounded => true,
845                         Quantity::One => false,
846                 }
847         }
848
849         pub(super) fn signing_pubkey(&self) -> PublicKey {
850                 self.signing_pubkey
851         }
852
853         /// Verifies that the offer metadata was produced from the offer in the TLV stream.
854         pub(super) fn verify<T: secp256k1::Signing>(
855                 &self, bytes: &[u8], key: &ExpandedKey, secp_ctx: &Secp256k1<T>
856         ) -> Result<Option<KeyPair>, ()> {
857                 match self.metadata() {
858                         Some(metadata) => {
859                                 let tlv_stream = TlvStream::new(bytes).range(OFFER_TYPES).filter(|record| {
860                                         match record.r#type {
861                                                 OFFER_METADATA_TYPE => false,
862                                                 OFFER_NODE_ID_TYPE => {
863                                                         !self.metadata.as_ref().unwrap().derives_recipient_keys()
864                                                 },
865                                                 _ => true,
866                                         }
867                                 });
868                                 signer::verify_recipient_metadata(
869                                         metadata, key, IV_BYTES, self.signing_pubkey(), tlv_stream, secp_ctx
870                                 )
871                         },
872                         None => Err(()),
873                 }
874         }
875
876         pub(super) fn as_tlv_stream(&self) -> OfferTlvStreamRef {
877                 let (currency, amount) = match &self.amount {
878                         None => (None, None),
879                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
880                         Some(Amount::Currency { iso4217_code, amount }) => (
881                                 Some(iso4217_code), Some(*amount)
882                         ),
883                 };
884
885                 let features = {
886                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
887                 };
888
889                 OfferTlvStreamRef {
890                         chains: self.chains.as_ref(),
891                         metadata: self.metadata(),
892                         currency,
893                         amount,
894                         description: Some(&self.description),
895                         features,
896                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
897                         paths: self.paths.as_ref(),
898                         issuer: self.issuer.as_ref(),
899                         quantity_max: self.supported_quantity.to_tlv_record(),
900                         node_id: Some(&self.signing_pubkey),
901                 }
902         }
903 }
904
905 impl Writeable for Offer {
906         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
907                 WithoutLength(&self.bytes).write(writer)
908         }
909 }
910
911 impl Writeable for OfferContents {
912         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
913                 self.as_tlv_stream().write(writer)
914         }
915 }
916
917 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
918 /// another currency.
919 #[derive(Clone, Debug, PartialEq)]
920 pub enum Amount {
921         /// An amount of bitcoin.
922         Bitcoin {
923                 /// The amount in millisatoshi.
924                 amount_msats: u64,
925         },
926         /// An amount of currency specified using ISO 4712.
927         Currency {
928                 /// The currency that the amount is denominated in.
929                 iso4217_code: CurrencyCode,
930                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
931                 amount: u64,
932         },
933 }
934
935 /// An ISO 4712 three-letter currency code (e.g., USD).
936 pub type CurrencyCode = [u8; 3];
937
938 /// Quantity of items supported by an [`Offer`].
939 #[derive(Clone, Copy, Debug, PartialEq)]
940 pub enum Quantity {
941         /// Up to a specific number of items (inclusive). Use when more than one item can be requested
942         /// but is limited (e.g., because of per customer or inventory limits).
943         ///
944         /// May be used with `NonZeroU64::new(1)` but prefer to use [`Quantity::One`] if only one item
945         /// is supported.
946         Bounded(NonZeroU64),
947         /// One or more items. Use when more than one item can be requested without any limit.
948         Unbounded,
949         /// Only one item. Use when only a single item can be requested.
950         One,
951 }
952
953 impl Quantity {
954         fn to_tlv_record(&self) -> Option<u64> {
955                 match self {
956                         Quantity::Bounded(n) => Some(n.get()),
957                         Quantity::Unbounded => Some(0),
958                         Quantity::One => None,
959                 }
960         }
961 }
962
963 /// Valid type range for offer TLV records.
964 pub(super) const OFFER_TYPES: core::ops::Range<u64> = 1..80;
965
966 /// TLV record type for [`Offer::metadata`].
967 const OFFER_METADATA_TYPE: u64 = 4;
968
969 /// TLV record type for [`Offer::signing_pubkey`].
970 const OFFER_NODE_ID_TYPE: u64 = 22;
971
972 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, OFFER_TYPES, {
973         (2, chains: (Vec<ChainHash>, WithoutLength)),
974         (OFFER_METADATA_TYPE, metadata: (Vec<u8>, WithoutLength)),
975         (6, currency: CurrencyCode),
976         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
977         (10, description: (String, WithoutLength)),
978         (12, features: (OfferFeatures, WithoutLength)),
979         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
980         (16, paths: (Vec<BlindedPath>, WithoutLength)),
981         (18, issuer: (String, WithoutLength)),
982         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
983         (OFFER_NODE_ID_TYPE, node_id: PublicKey),
984 });
985
986 impl Bech32Encode for Offer {
987         const BECH32_HRP: &'static str = "lno";
988 }
989
990 impl FromStr for Offer {
991         type Err = Bolt12ParseError;
992
993         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
994                 Self::from_bech32_str(s)
995         }
996 }
997
998 impl TryFrom<Vec<u8>> for Offer {
999         type Error = Bolt12ParseError;
1000
1001         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1002                 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
1003                 let ParsedMessage { bytes, tlv_stream } = offer;
1004                 let contents = OfferContents::try_from(tlv_stream)?;
1005                 Ok(Offer { bytes, contents })
1006         }
1007 }
1008
1009 impl TryFrom<OfferTlvStream> for OfferContents {
1010         type Error = Bolt12SemanticError;
1011
1012         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
1013                 let OfferTlvStream {
1014                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
1015                         issuer, quantity_max, node_id,
1016                 } = tlv_stream;
1017
1018                 let metadata = metadata.map(|metadata| Metadata::Bytes(metadata));
1019
1020                 let amount = match (currency, amount) {
1021                         (None, None) => None,
1022                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
1023                                 return Err(Bolt12SemanticError::InvalidAmount);
1024                         },
1025                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
1026                         (Some(_), None) => return Err(Bolt12SemanticError::MissingAmount),
1027                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
1028                 };
1029
1030                 let description = match description {
1031                         None => return Err(Bolt12SemanticError::MissingDescription),
1032                         Some(description) => description,
1033                 };
1034
1035                 let features = features.unwrap_or_else(OfferFeatures::empty);
1036
1037                 let absolute_expiry = absolute_expiry
1038                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
1039
1040                 let supported_quantity = match quantity_max {
1041                         None => Quantity::One,
1042                         Some(0) => Quantity::Unbounded,
1043                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
1044                 };
1045
1046                 let signing_pubkey = match node_id {
1047                         None => return Err(Bolt12SemanticError::MissingSigningPubkey),
1048                         Some(node_id) => node_id,
1049                 };
1050
1051                 Ok(OfferContents {
1052                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
1053                         supported_quantity, signing_pubkey,
1054                 })
1055         }
1056 }
1057
1058 impl core::fmt::Display for Offer {
1059         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1060                 self.fmt_bech32_str(f)
1061         }
1062 }
1063
1064 #[cfg(test)]
1065 mod tests {
1066         use super::{Amount, Offer, OfferTlvStreamRef, Quantity};
1067         #[cfg(not(c_bindings))]
1068         use {
1069                 super::OfferBuilder,
1070         };
1071         #[cfg(c_bindings)]
1072         use {
1073                 super::OfferWithExplicitMetadataBuilder as OfferBuilder,
1074         };
1075
1076         use bitcoin::blockdata::constants::ChainHash;
1077         use bitcoin::network::constants::Network;
1078         use bitcoin::secp256k1::Secp256k1;
1079         use core::convert::TryFrom;
1080         use core::num::NonZeroU64;
1081         use core::time::Duration;
1082         use crate::blinded_path::{BlindedHop, BlindedPath};
1083         use crate::sign::KeyMaterial;
1084         use crate::ln::features::OfferFeatures;
1085         use crate::ln::inbound_payment::ExpandedKey;
1086         use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
1087         use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError};
1088         use crate::offers::test_utils::*;
1089         use crate::util::ser::{BigSize, Writeable};
1090         use crate::util::string::PrintableString;
1091
1092         #[test]
1093         fn builds_offer_with_defaults() {
1094                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1095
1096                 let mut buffer = Vec::new();
1097                 offer.write(&mut buffer).unwrap();
1098
1099                 assert_eq!(offer.bytes, buffer.as_slice());
1100                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
1101                 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
1102                 assert_eq!(offer.metadata(), None);
1103                 assert_eq!(offer.amount(), None);
1104                 assert_eq!(offer.description(), PrintableString("foo"));
1105                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1106                 assert_eq!(offer.absolute_expiry(), None);
1107                 #[cfg(feature = "std")]
1108                 assert!(!offer.is_expired());
1109                 assert_eq!(offer.paths(), &[]);
1110                 assert_eq!(offer.issuer(), None);
1111                 assert_eq!(offer.supported_quantity(), Quantity::One);
1112                 assert_eq!(offer.signing_pubkey(), pubkey(42));
1113
1114                 assert_eq!(
1115                         offer.as_tlv_stream(),
1116                         OfferTlvStreamRef {
1117                                 chains: None,
1118                                 metadata: None,
1119                                 currency: None,
1120                                 amount: None,
1121                                 description: Some(&String::from("foo")),
1122                                 features: None,
1123                                 absolute_expiry: None,
1124                                 paths: None,
1125                                 issuer: None,
1126                                 quantity_max: None,
1127                                 node_id: Some(&pubkey(42)),
1128                         },
1129                 );
1130
1131                 if let Err(e) = Offer::try_from(buffer) {
1132                         panic!("error parsing offer: {:?}", e);
1133                 }
1134         }
1135
1136         #[test]
1137         fn builds_offer_with_chains() {
1138                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
1139                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
1140
1141                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1142                         .chain(Network::Bitcoin)
1143                         .build()
1144                         .unwrap();
1145                 assert!(offer.supports_chain(mainnet));
1146                 assert_eq!(offer.chains(), vec![mainnet]);
1147                 assert_eq!(offer.as_tlv_stream().chains, None);
1148
1149                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1150                         .chain(Network::Testnet)
1151                         .build()
1152                         .unwrap();
1153                 assert!(offer.supports_chain(testnet));
1154                 assert_eq!(offer.chains(), vec![testnet]);
1155                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1156
1157                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1158                         .chain(Network::Testnet)
1159                         .chain(Network::Testnet)
1160                         .build()
1161                         .unwrap();
1162                 assert!(offer.supports_chain(testnet));
1163                 assert_eq!(offer.chains(), vec![testnet]);
1164                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
1165
1166                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1167                         .chain(Network::Bitcoin)
1168                         .chain(Network::Testnet)
1169                         .build()
1170                         .unwrap();
1171                 assert!(offer.supports_chain(mainnet));
1172                 assert!(offer.supports_chain(testnet));
1173                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
1174                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
1175         }
1176
1177         #[test]
1178         fn builds_offer_with_metadata() {
1179                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1180                         .metadata(vec![42; 32]).unwrap()
1181                         .build()
1182                         .unwrap();
1183                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
1184                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
1185
1186                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1187                         .metadata(vec![42; 32]).unwrap()
1188                         .metadata(vec![43; 32]).unwrap()
1189                         .build()
1190                         .unwrap();
1191                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
1192                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
1193         }
1194
1195         #[test]
1196         fn builds_offer_with_metadata_derived() {
1197                 let desc = "foo".to_string();
1198                 let node_id = recipient_pubkey();
1199                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1200                 let entropy = FixedEntropy {};
1201                 let secp_ctx = Secp256k1::new();
1202
1203                 #[cfg(c_bindings)]
1204                 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1205                 let offer = OfferBuilder
1206                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1207                         .amount_msats(1000)
1208                         .build().unwrap();
1209                 assert_eq!(offer.signing_pubkey(), node_id);
1210
1211                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1212                         .build().unwrap()
1213                         .sign(payer_sign).unwrap();
1214                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1215
1216                 // Fails verification with altered offer field
1217                 let mut tlv_stream = offer.as_tlv_stream();
1218                 tlv_stream.amount = Some(100);
1219
1220                 let mut encoded_offer = Vec::new();
1221                 tlv_stream.write(&mut encoded_offer).unwrap();
1222
1223                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1224                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1225                         .build().unwrap()
1226                         .sign(payer_sign).unwrap();
1227                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1228
1229                 // Fails verification with altered metadata
1230                 let mut tlv_stream = offer.as_tlv_stream();
1231                 let metadata = tlv_stream.metadata.unwrap().iter().copied().rev().collect();
1232                 tlv_stream.metadata = Some(&metadata);
1233
1234                 let mut encoded_offer = Vec::new();
1235                 tlv_stream.write(&mut encoded_offer).unwrap();
1236
1237                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1238                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1239                         .build().unwrap()
1240                         .sign(payer_sign).unwrap();
1241                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1242         }
1243
1244         #[test]
1245         fn builds_offer_with_derived_signing_pubkey() {
1246                 let desc = "foo".to_string();
1247                 let node_id = recipient_pubkey();
1248                 let expanded_key = ExpandedKey::new(&KeyMaterial([42; 32]));
1249                 let entropy = FixedEntropy {};
1250                 let secp_ctx = Secp256k1::new();
1251
1252                 let blinded_path = BlindedPath {
1253                         introduction_node_id: pubkey(40),
1254                         blinding_point: pubkey(41),
1255                         blinded_hops: vec![
1256                                 BlindedHop { blinded_node_id: pubkey(42), encrypted_payload: vec![0; 43] },
1257                                 BlindedHop { blinded_node_id: node_id, encrypted_payload: vec![0; 44] },
1258                         ],
1259                 };
1260
1261                 #[cfg(c_bindings)]
1262                 use super::OfferWithDerivedMetadataBuilder as OfferBuilder;
1263                 let offer = OfferBuilder
1264                         ::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
1265                         .amount_msats(1000)
1266                         .path(blinded_path)
1267                         .build().unwrap();
1268                 assert_ne!(offer.signing_pubkey(), node_id);
1269
1270                 let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1271                         .build().unwrap()
1272                         .sign(payer_sign).unwrap();
1273                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_ok());
1274
1275                 // Fails verification with altered offer field
1276                 let mut tlv_stream = offer.as_tlv_stream();
1277                 tlv_stream.amount = Some(100);
1278
1279                 let mut encoded_offer = Vec::new();
1280                 tlv_stream.write(&mut encoded_offer).unwrap();
1281
1282                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1283                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1284                         .build().unwrap()
1285                         .sign(payer_sign).unwrap();
1286                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1287
1288                 // Fails verification with altered signing pubkey
1289                 let mut tlv_stream = offer.as_tlv_stream();
1290                 let signing_pubkey = pubkey(1);
1291                 tlv_stream.node_id = Some(&signing_pubkey);
1292
1293                 let mut encoded_offer = Vec::new();
1294                 tlv_stream.write(&mut encoded_offer).unwrap();
1295
1296                 let invoice_request = Offer::try_from(encoded_offer).unwrap()
1297                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1298                         .build().unwrap()
1299                         .sign(payer_sign).unwrap();
1300                 assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());
1301         }
1302
1303         #[test]
1304         fn builds_offer_with_amount() {
1305                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
1306                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
1307
1308                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1309                         .amount_msats(1000)
1310                         .build()
1311                         .unwrap();
1312                 let tlv_stream = offer.as_tlv_stream();
1313                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
1314                 assert_eq!(tlv_stream.amount, Some(1000));
1315                 assert_eq!(tlv_stream.currency, None);
1316
1317                 #[cfg(not(c_bindings))]
1318                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
1319                         .amount(currency_amount.clone());
1320                 #[cfg(c_bindings)]
1321                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1322                 #[cfg(c_bindings)]
1323                 builder.amount(currency_amount.clone());
1324                 let tlv_stream = builder.offer.as_tlv_stream();
1325                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
1326                 assert_eq!(tlv_stream.amount, Some(10));
1327                 assert_eq!(tlv_stream.currency, Some(b"USD"));
1328                 match builder.build() {
1329                         Ok(_) => panic!("expected error"),
1330                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedCurrency),
1331                 }
1332
1333                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1334                         .amount(currency_amount.clone())
1335                         .amount(bitcoin_amount.clone())
1336                         .build()
1337                         .unwrap();
1338                 let tlv_stream = offer.as_tlv_stream();
1339                 assert_eq!(tlv_stream.amount, Some(1000));
1340                 assert_eq!(tlv_stream.currency, None);
1341
1342                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
1343                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
1344                         Ok(_) => panic!("expected error"),
1345                         Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidAmount),
1346                 }
1347         }
1348
1349         #[test]
1350         fn builds_offer_with_features() {
1351                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1352                         .features_unchecked(OfferFeatures::unknown())
1353                         .build()
1354                         .unwrap();
1355                 assert_eq!(offer.offer_features(), &OfferFeatures::unknown());
1356                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
1357
1358                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1359                         .features_unchecked(OfferFeatures::unknown())
1360                         .features_unchecked(OfferFeatures::empty())
1361                         .build()
1362                         .unwrap();
1363                 assert_eq!(offer.offer_features(), &OfferFeatures::empty());
1364                 assert_eq!(offer.as_tlv_stream().features, None);
1365         }
1366
1367         #[test]
1368         fn builds_offer_with_absolute_expiry() {
1369                 let future_expiry = Duration::from_secs(u64::max_value());
1370                 let past_expiry = Duration::from_secs(0);
1371                 let now = future_expiry - Duration::from_secs(1_000);
1372
1373                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1374                         .absolute_expiry(future_expiry)
1375                         .build()
1376                         .unwrap();
1377                 #[cfg(feature = "std")]
1378                 assert!(!offer.is_expired());
1379                 assert!(!offer.is_expired_no_std(now));
1380                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
1381                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
1382
1383                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1384                         .absolute_expiry(future_expiry)
1385                         .absolute_expiry(past_expiry)
1386                         .build()
1387                         .unwrap();
1388                 #[cfg(feature = "std")]
1389                 assert!(offer.is_expired());
1390                 assert!(offer.is_expired_no_std(now));
1391                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
1392                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
1393         }
1394
1395         #[test]
1396         fn builds_offer_with_paths() {
1397                 let paths = vec![
1398                         BlindedPath {
1399                                 introduction_node_id: pubkey(40),
1400                                 blinding_point: pubkey(41),
1401                                 blinded_hops: vec![
1402                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1403                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1404                                 ],
1405                         },
1406                         BlindedPath {
1407                                 introduction_node_id: pubkey(40),
1408                                 blinding_point: pubkey(41),
1409                                 blinded_hops: vec![
1410                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1411                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1412                                 ],
1413                         },
1414                 ];
1415
1416                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1417                         .path(paths[0].clone())
1418                         .path(paths[1].clone())
1419                         .build()
1420                         .unwrap();
1421                 let tlv_stream = offer.as_tlv_stream();
1422                 assert_eq!(offer.paths(), paths.as_slice());
1423                 assert_eq!(offer.signing_pubkey(), pubkey(42));
1424                 assert_ne!(pubkey(42), pubkey(44));
1425                 assert_eq!(tlv_stream.paths, Some(&paths));
1426                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
1427         }
1428
1429         #[test]
1430         fn builds_offer_with_issuer() {
1431                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1432                         .issuer("bar".into())
1433                         .build()
1434                         .unwrap();
1435                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
1436                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
1437
1438                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1439                         .issuer("bar".into())
1440                         .issuer("baz".into())
1441                         .build()
1442                         .unwrap();
1443                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
1444                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
1445         }
1446
1447         #[test]
1448         fn builds_offer_with_supported_quantity() {
1449                 let one = NonZeroU64::new(1).unwrap();
1450                 let ten = NonZeroU64::new(10).unwrap();
1451
1452                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1453                         .supported_quantity(Quantity::One)
1454                         .build()
1455                         .unwrap();
1456                 let tlv_stream = offer.as_tlv_stream();
1457                 assert_eq!(offer.supported_quantity(), Quantity::One);
1458                 assert_eq!(tlv_stream.quantity_max, None);
1459
1460                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1461                         .supported_quantity(Quantity::Unbounded)
1462                         .build()
1463                         .unwrap();
1464                 let tlv_stream = offer.as_tlv_stream();
1465                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
1466                 assert_eq!(tlv_stream.quantity_max, Some(0));
1467
1468                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1469                         .supported_quantity(Quantity::Bounded(ten))
1470                         .build()
1471                         .unwrap();
1472                 let tlv_stream = offer.as_tlv_stream();
1473                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
1474                 assert_eq!(tlv_stream.quantity_max, Some(10));
1475
1476                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1477                         .supported_quantity(Quantity::Bounded(one))
1478                         .build()
1479                         .unwrap();
1480                 let tlv_stream = offer.as_tlv_stream();
1481                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(one));
1482                 assert_eq!(tlv_stream.quantity_max, Some(1));
1483
1484                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1485                         .supported_quantity(Quantity::Bounded(ten))
1486                         .supported_quantity(Quantity::One)
1487                         .build()
1488                         .unwrap();
1489                 let tlv_stream = offer.as_tlv_stream();
1490                 assert_eq!(offer.supported_quantity(), Quantity::One);
1491                 assert_eq!(tlv_stream.quantity_max, None);
1492         }
1493
1494         #[test]
1495         fn fails_requesting_invoice_with_unknown_required_features() {
1496                 match OfferBuilder::new("foo".into(), pubkey(42))
1497                         .features_unchecked(OfferFeatures::unknown())
1498                         .build().unwrap()
1499                         .request_invoice(vec![1; 32], pubkey(43))
1500                 {
1501                         Ok(_) => panic!("expected error"),
1502                         Err(e) => assert_eq!(e, Bolt12SemanticError::UnknownRequiredFeatures),
1503                 }
1504         }
1505
1506         #[test]
1507         fn parses_offer_with_chains() {
1508                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1509                         .chain(Network::Bitcoin)
1510                         .chain(Network::Testnet)
1511                         .build()
1512                         .unwrap();
1513                 if let Err(e) = offer.to_string().parse::<Offer>() {
1514                         panic!("error parsing offer: {:?}", e);
1515                 }
1516         }
1517
1518         #[test]
1519         fn parses_offer_with_amount() {
1520                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1521                         .amount(Amount::Bitcoin { amount_msats: 1000 })
1522                         .build()
1523                         .unwrap();
1524                 if let Err(e) = offer.to_string().parse::<Offer>() {
1525                         panic!("error parsing offer: {:?}", e);
1526                 }
1527
1528                 let mut tlv_stream = offer.as_tlv_stream();
1529                 tlv_stream.amount = Some(1000);
1530                 tlv_stream.currency = Some(b"USD");
1531
1532                 let mut encoded_offer = Vec::new();
1533                 tlv_stream.write(&mut encoded_offer).unwrap();
1534
1535                 if let Err(e) = Offer::try_from(encoded_offer) {
1536                         panic!("error parsing offer: {:?}", e);
1537                 }
1538
1539                 let mut tlv_stream = offer.as_tlv_stream();
1540                 tlv_stream.amount = None;
1541                 tlv_stream.currency = Some(b"USD");
1542
1543                 let mut encoded_offer = Vec::new();
1544                 tlv_stream.write(&mut encoded_offer).unwrap();
1545
1546                 match Offer::try_from(encoded_offer) {
1547                         Ok(_) => panic!("expected error"),
1548                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingAmount)),
1549                 }
1550
1551                 let mut tlv_stream = offer.as_tlv_stream();
1552                 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
1553                 tlv_stream.currency = None;
1554
1555                 let mut encoded_offer = Vec::new();
1556                 tlv_stream.write(&mut encoded_offer).unwrap();
1557
1558                 match Offer::try_from(encoded_offer) {
1559                         Ok(_) => panic!("expected error"),
1560                         Err(e) => assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::InvalidAmount)),
1561                 }
1562         }
1563
1564         #[test]
1565         fn parses_offer_with_description() {
1566                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1567                 if let Err(e) = offer.to_string().parse::<Offer>() {
1568                         panic!("error parsing offer: {:?}", e);
1569                 }
1570
1571                 let mut tlv_stream = offer.as_tlv_stream();
1572                 tlv_stream.description = None;
1573
1574                 let mut encoded_offer = Vec::new();
1575                 tlv_stream.write(&mut encoded_offer).unwrap();
1576
1577                 match Offer::try_from(encoded_offer) {
1578                         Ok(_) => panic!("expected error"),
1579                         Err(e) => {
1580                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription));
1581                         },
1582                 }
1583         }
1584
1585         #[test]
1586         fn parses_offer_with_paths() {
1587                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1588                         .path(BlindedPath {
1589                                 introduction_node_id: pubkey(40),
1590                                 blinding_point: pubkey(41),
1591                                 blinded_hops: vec![
1592                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
1593                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
1594                                 ],
1595                         })
1596                         .path(BlindedPath {
1597                                 introduction_node_id: pubkey(40),
1598                                 blinding_point: pubkey(41),
1599                                 blinded_hops: vec![
1600                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
1601                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
1602                                 ],
1603                         })
1604                         .build()
1605                         .unwrap();
1606                 if let Err(e) = offer.to_string().parse::<Offer>() {
1607                         panic!("error parsing offer: {:?}", e);
1608                 }
1609
1610                 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1611                 builder.offer.paths = Some(vec![]);
1612
1613                 let offer = builder.build().unwrap();
1614                 if let Err(e) = offer.to_string().parse::<Offer>() {
1615                         panic!("error parsing offer: {:?}", e);
1616                 }
1617         }
1618
1619         #[test]
1620         fn parses_offer_with_quantity() {
1621                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1622                         .supported_quantity(Quantity::One)
1623                         .build()
1624                         .unwrap();
1625                 if let Err(e) = offer.to_string().parse::<Offer>() {
1626                         panic!("error parsing offer: {:?}", e);
1627                 }
1628
1629                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1630                         .supported_quantity(Quantity::Unbounded)
1631                         .build()
1632                         .unwrap();
1633                 if let Err(e) = offer.to_string().parse::<Offer>() {
1634                         panic!("error parsing offer: {:?}", e);
1635                 }
1636
1637                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1638                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1639                         .build()
1640                         .unwrap();
1641                 if let Err(e) = offer.to_string().parse::<Offer>() {
1642                         panic!("error parsing offer: {:?}", e);
1643                 }
1644
1645                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1646                         .supported_quantity(Quantity::Bounded(NonZeroU64::new(1).unwrap()))
1647                         .build()
1648                         .unwrap();
1649                 if let Err(e) = offer.to_string().parse::<Offer>() {
1650                         panic!("error parsing offer: {:?}", e);
1651                 }
1652         }
1653
1654         #[test]
1655         fn parses_offer_with_node_id() {
1656                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1657                 if let Err(e) = offer.to_string().parse::<Offer>() {
1658                         panic!("error parsing offer: {:?}", e);
1659                 }
1660
1661                 let mut tlv_stream = offer.as_tlv_stream();
1662                 tlv_stream.node_id = None;
1663
1664                 let mut encoded_offer = Vec::new();
1665                 tlv_stream.write(&mut encoded_offer).unwrap();
1666
1667                 match Offer::try_from(encoded_offer) {
1668                         Ok(_) => panic!("expected error"),
1669                         Err(e) => {
1670                                 assert_eq!(e, Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey));
1671                         },
1672                 }
1673         }
1674
1675         #[test]
1676         fn fails_parsing_offer_with_extra_tlv_records() {
1677                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1678
1679                 let mut encoded_offer = Vec::new();
1680                 offer.write(&mut encoded_offer).unwrap();
1681                 BigSize(80).write(&mut encoded_offer).unwrap();
1682                 BigSize(32).write(&mut encoded_offer).unwrap();
1683                 [42u8; 32].write(&mut encoded_offer).unwrap();
1684
1685                 match Offer::try_from(encoded_offer) {
1686                         Ok(_) => panic!("expected error"),
1687                         Err(e) => assert_eq!(e, Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1688                 }
1689         }
1690 }
1691
1692 #[cfg(test)]
1693 mod bolt12_tests {
1694         use super::{Bolt12ParseError, Bolt12SemanticError, Offer};
1695         use crate::ln::msgs::DecodeError;
1696
1697         #[test]
1698         fn parses_bech32_encoded_offers() {
1699                 let offers = [
1700                         // Minimal bolt12 offer
1701                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1702
1703                         // for testnet
1704                         "lno1qgsyxjtl6luzd9t3pr62xr7eemp6awnejusgf6gw45q75vcfqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1705
1706                         // for bitcoin (redundant)
1707                         "lno1qgsxlc5vp2m0rvmjcxn2y34wv0m5lyc7sdj7zksgn35dvxgqqqqqqqq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1708
1709                         // for bitcoin or liquidv1
1710                         "lno1qfqpge38tqmzyrdjj3x2qkdr5y80dlfw56ztq6yd9sme995g3gsxqqm0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq9qc4r9wd6zqan9vd6x7unnzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1711
1712                         // with metadata
1713                         "lno1qsgqqqqqqqqqqqqqqqqqqqqqqqqqqzsv23jhxapqwejkxar0wfe3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1714
1715                         // with amount
1716                         "lno1pqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1717
1718                         // with currency
1719                         "lno1qcp4256ypqpzwyq2p32x2um5ypmx2cm5dae8x93pqthvwfzadd7jejes8q9lhc4rvjxd022zv5l44g6qah82ru5rdpnpj",
1720
1721                         // with expiry
1722                         "lno1pgx9getnwss8vetrw3hhyucwq3ay997czcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1723
1724                         // with issuer
1725                         "lno1pgx9getnwss8vetrw3hhyucjy358garswvaz7tmzdak8gvfj9ehhyeeqgf85c4p3xgsxjmnyw4ehgunfv4e3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1726
1727                         // with quantity
1728                         "lno1pgx9getnwss8vetrw3hhyuc5qyz3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1729
1730                         // with unlimited (or unknown) quantity
1731                         "lno1pgx9getnwss8vetrw3hhyuc5qqtzzqhwcuj966ma9n9nqwqtl032xeyv6755yeflt235pmww58egx6rxry",
1732
1733                         // with single quantity (weird but valid)
1734                         "lno1pgx9getnwss8vetrw3hhyuc5qyq3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1735
1736                         // with feature
1737                         "lno1pgx9getnwss8vetrw3hhyucvp5yqqqqqqqqqqqqqqqqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg",
1738
1739                         // with blinded path via Bob (0x424242...), blinding 020202...
1740                         "lno1pgx9getnwss8vetrw3hhyucs5ypjgef743p5fzqq9nqxh0ah7y87rzv3ud0eleps9kl2d5348hq2k8qzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgqpqqqqqqqqqqqqqqqqqqqqqqqqqqqzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqqzq3zyg3zyg3zyg3vggzamrjghtt05kvkvpcp0a79gmy3nt6jsn98ad2xs8de6sl9qmgvcvs",
1741
1742                         // ... and with second blinded path via Carol (0x434343...), blinding 020202...
1743                         "lno1pgx9getnwss8vetrw3hhyucsl5q5yqeyv5l2cs6y3qqzesrth7mlzrlp3xg7xhulusczm04x6g6nms9trspqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqqsqqqqqqqqqqqqqqqqqqqqqqqqqqpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqpqg3zyg3zyg3zygz0uc7h32x9s0aecdhxlk075kn046aafpuuyw8f5j652t3vha2yqrsyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzqqqqqqqqqqqqqqqqqqqqqqqqqqqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqqyzyg3zyg3zyg3zzcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese",
1744
1745                         // unknown odd field
1746                         "lno1pgx9getnwss8vetrw3hhyuckyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxfppf5x2mrvdamk7unvvs",
1747                 ];
1748                 for encoded_offer in &offers {
1749                         if let Err(e) = encoded_offer.parse::<Offer>() {
1750                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1751                         }
1752                 }
1753         }
1754
1755         #[test]
1756         fn fails_parsing_bech32_encoded_offers() {
1757                 // Malformed: fields out of order
1758                 assert_eq!(
1759                         "lno1zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszpgz5znzfgdzs".parse::<Offer>(),
1760                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1761                 );
1762
1763                 // Malformed: unknown even TLV type 78
1764                 assert_eq!(
1765                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpysgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1766                         Err(Bolt12ParseError::Decode(DecodeError::UnknownRequiredFeature)),
1767                 );
1768
1769                 // Malformed: empty
1770                 assert_eq!(
1771                         "lno1".parse::<Offer>(),
1772                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1773                 );
1774
1775                 // Malformed: truncated at type
1776                 assert_eq!(
1777                         "lno1pg".parse::<Offer>(),
1778                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1779                 );
1780
1781                 // Malformed: truncated in length
1782                 assert_eq!(
1783                         "lno1pt7s".parse::<Offer>(),
1784                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1785                 );
1786
1787                 // Malformed: truncated after length
1788                 assert_eq!(
1789                         "lno1pgpq".parse::<Offer>(),
1790                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1791                 );
1792
1793                 // Malformed: truncated in description
1794                 assert_eq!(
1795                         "lno1pgpyz".parse::<Offer>(),
1796                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1797                 );
1798
1799                 // Malformed: invalid offer_chains length
1800                 assert_eq!(
1801                         "lno1qgqszzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1802                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1803                 );
1804
1805                 // Malformed: truncated currency UTF-8
1806                 assert_eq!(
1807                         "lno1qcqcqzs9g9xyjs69zcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1808                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1809                 );
1810
1811                 // Malformed: invalid currency UTF-8
1812                 assert_eq!(
1813                         "lno1qcpgqsg2q4q5cj2rg5tzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1814                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1815                 );
1816
1817                 // Malformed: truncated description UTF-8
1818                 assert_eq!(
1819                         "lno1pgqcq93pqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqy".parse::<Offer>(),
1820                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1821                 );
1822
1823                 // Malformed: invalid description UTF-8
1824                 assert_eq!(
1825                         "lno1pgpgqsgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1826                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1827                 );
1828
1829                 // Malformed: truncated offer_paths
1830                 assert_eq!(
1831                         "lno1pgz5znzfgdz3qqgpzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1832                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1833                 );
1834
1835                 // Malformed: zero num_hops in blinded_path
1836                 assert_eq!(
1837                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1838                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1839                 );
1840
1841                 // Malformed: truncated onionmsg_hop in blinded_path
1842                 assert_eq!(
1843                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgkyypqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs".parse::<Offer>(),
1844                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1845                 );
1846
1847                 // Malformed: bad first_node_id in blinded_path
1848                 assert_eq!(
1849                         "lno1pgz5znzfgdz3qqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1850                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1851                 );
1852
1853                 // Malformed: bad blinding in blinded_path
1854                 assert_eq!(
1855                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcpqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1856                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1857                 );
1858
1859                 // Malformed: bad blinded_node_id in onionmsg_hop
1860                 assert_eq!(
1861                         "lno1pgz5znzfgdz3qqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqspqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqgqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1862                         Err(Bolt12ParseError::Decode(DecodeError::ShortRead)),
1863                 );
1864
1865                 // Malformed: truncated issuer UTF-8
1866                 assert_eq!(
1867                         "lno1pgz5znzfgdz3yqvqzcssyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqsz".parse::<Offer>(),
1868                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1869                 );
1870
1871                 // Malformed: invalid issuer UTF-8
1872                 assert_eq!(
1873                         "lno1pgz5znzfgdz3yq5qgytzzqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqg".parse::<Offer>(),
1874                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1875                 );
1876
1877                 // Malformed: invalid offer_node_id
1878                 assert_eq!(
1879                         "lno1pgz5znzfgdz3vggzqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvpsxqcrqvps".parse::<Offer>(),
1880                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1881                 );
1882
1883                 // Contains type >= 80
1884                 assert_eq!(
1885                         "lno1pgz5znzfgdz3vggzqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgp9qgr0u2xq4dh3kdevrf4zg6hx8a60jv0gxe0ptgyfc6xkryqqqqqqqq".parse::<Offer>(),
1886                         Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
1887                 );
1888
1889                 // TODO: Resolved in spec https://github.com/lightning/bolts/pull/798/files#r1334851959
1890                 // Contains unknown feature 22
1891                 assert!(
1892                         "lno1pgx9getnwss8vetrw3hhyucvqdqqqqqkyypwa3eyt44h6txtxquqh7lz5djge4afgfjn7k4rgrkuag0jsd5xvxg".parse::<Offer>().is_ok()
1893                 );
1894
1895                 // Missing offer_description
1896                 assert_eq!(
1897                         "lno1zcss9mk8y3wkklfvevcrszlmu23kfrxh49px20665dqwmn4p72pksese".parse::<Offer>(),
1898                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingDescription)),
1899                 );
1900
1901                 // Missing offer_node_id"
1902                 assert_eq!(
1903                         "lno1pgx9getnwss8vetrw3hhyuc".parse::<Offer>(),
1904                         Err(Bolt12ParseError::InvalidSemantics(Bolt12SemanticError::MissingSigningPubkey)),
1905                 );
1906         }
1907 }