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