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