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