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