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