]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/offers/offer.rs
Offer parsing from bech32 strings
[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 //! ```ignore
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
20 //!
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
24 //!
25 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
26 //! use lightning::offers::offer::{Offer, OfferBuilder, Quantity};
27 //! use lightning::offers::parse::ParseError;
28 //! use lightning::util::ser::{Readable, Writeable};
29 //!
30 //! # use lightning::onion_message::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
33 //! #
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
36 //! #
37 //! # #[cfg(feature = "std")]
38 //! # fn build() -> Result<(), ParseError> {
39 //! let secp_ctx = Secp256k1::new();
40 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
41 //! let pubkey = PublicKey::from(keys);
42 //!
43 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
44 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
45 //!     .amount_msats(20_000)
46 //!     .supported_quantity(Quantity::Unbounded)
47 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
48 //!     .issuer("Foo Bar".to_string())
49 //!     .path(create_blinded_path())
50 //!     .path(create_another_blinded_path())
51 //!     .build()
52 //!     .unwrap();
53 //!
54 //! // Encode as a bech32 string for use in a QR code.
55 //! let encoded_offer = offer.to_string();
56 //!
57 //! // Parse from a bech32 string after scanning from a QR code.
58 //! let offer = encoded_offer.parse::<Offer>()?;
59 //!
60 //! // Encode offer as raw bytes.
61 //! let mut bytes = Vec::new();
62 //! offer.write(&mut bytes).unwrap();
63 //!
64 //! // Decode raw bytes into an offer.
65 //! let offer = Offer::try_from(bytes)?;
66 //! # Ok(())
67 //! # }
68 //! ```
69
70 use bitcoin::blockdata::constants::ChainHash;
71 use bitcoin::network::constants::Network;
72 use bitcoin::secp256k1::PublicKey;
73 use core::convert::TryFrom;
74 use core::num::NonZeroU64;
75 use core::str::FromStr;
76 use core::time::Duration;
77 use crate::io;
78 use crate::ln::features::OfferFeatures;
79 use crate::ln::msgs::MAX_VALUE_MSAT;
80 use crate::offers::parse::{Bech32Encode, ParseError, SemanticError};
81 use crate::onion_message::BlindedPath;
82 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
83 use crate::util::string::PrintableString;
84
85 use crate::prelude::*;
86
87 #[cfg(feature = "std")]
88 use std::time::SystemTime;
89
90 /// Builds an [`Offer`] for the "offer to be paid" flow.
91 ///
92 /// See [module-level documentation] for usage.
93 ///
94 /// [module-level documentation]: self
95 pub struct OfferBuilder {
96         offer: OfferContents,
97 }
98
99 impl OfferBuilder {
100         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
101         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
102         /// while the offer is valid.
103         ///
104         /// Use a different pubkey per offer to avoid correlating offers.
105         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
106                 let offer = OfferContents {
107                         chains: None, metadata: None, amount: None, description,
108                         features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
109                         supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
110                 };
111                 OfferBuilder { offer }
112         }
113
114         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
115         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
116         ///
117         /// See [`Offer::chains`] on how this relates to the payment currency.
118         ///
119         /// Successive calls to this method will add another chain hash.
120         pub fn chain(mut self, network: Network) -> Self {
121                 let chains = self.offer.chains.get_or_insert_with(Vec::new);
122                 let chain = ChainHash::using_genesis_block(network);
123                 if !chains.contains(&chain) {
124                         chains.push(chain);
125                 }
126
127                 self
128         }
129
130         /// Sets the [`Offer::metadata`].
131         ///
132         /// Successive calls to this method will override the previous setting.
133         pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
134                 self.offer.metadata = Some(metadata);
135                 self
136         }
137
138         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
139         ///
140         /// Successive calls to this method will override the previous setting.
141         pub fn amount_msats(mut self, amount_msats: u64) -> Self {
142                 self.amount(Amount::Bitcoin { amount_msats })
143         }
144
145         /// Sets the [`Offer::amount`].
146         ///
147         /// Successive calls to this method will override the previous setting.
148         fn amount(mut self, amount: Amount) -> Self {
149                 self.offer.amount = Some(amount);
150                 self
151         }
152
153         /// Sets the [`Offer::features`].
154         ///
155         /// Successive calls to this method will override the previous setting.
156         #[cfg(test)]
157         pub fn features(mut self, features: OfferFeatures) -> Self {
158                 self.offer.features = features;
159                 self
160         }
161
162         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
163         /// already passed is valid and can be checked for using [`Offer::is_expired`].
164         ///
165         /// Successive calls to this method will override the previous setting.
166         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
167                 self.offer.absolute_expiry = Some(absolute_expiry);
168                 self
169         }
170
171         /// Sets the [`Offer::issuer`].
172         ///
173         /// Successive calls to this method will override the previous setting.
174         pub fn issuer(mut self, issuer: String) -> Self {
175                 self.offer.issuer = Some(issuer);
176                 self
177         }
178
179         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
180         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
181         ///
182         /// Successive calls to this method will add another blinded path. Caller is responsible for not
183         /// adding duplicate paths.
184         pub fn path(mut self, path: BlindedPath) -> Self {
185                 self.offer.paths.get_or_insert_with(Vec::new).push(path);
186                 self
187         }
188
189         /// Sets the quantity of items for [`Offer::supported_quantity`].
190         ///
191         /// Successive calls to this method will override the previous setting.
192         pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
193                 self.offer.supported_quantity = quantity;
194                 self
195         }
196
197         /// Builds an [`Offer`] from the builder's settings.
198         pub fn build(mut self) -> Result<Offer, ()> {
199                 match self.offer.amount {
200                         Some(Amount::Bitcoin { amount_msats }) => {
201                                 if amount_msats > MAX_VALUE_MSAT {
202                                         return Err(());
203                                 }
204                         },
205                         Some(Amount::Currency { .. }) => unreachable!(),
206                         None => {},
207                 }
208
209                 if let Some(chains) = &self.offer.chains {
210                         if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
211                                 self.offer.chains = None;
212                         }
213                 }
214
215                 let mut bytes = Vec::new();
216                 self.offer.write(&mut bytes).unwrap();
217
218                 Ok(Offer {
219                         bytes,
220                         contents: self.offer,
221                 })
222         }
223 }
224
225 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
226 ///
227 /// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
228 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
229 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
230 ///
231 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
232 /// latter.
233 ///
234 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
235 #[derive(Clone, Debug)]
236 pub struct Offer {
237         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
238         // fields.
239         bytes: Vec<u8>,
240         contents: OfferContents,
241 }
242
243 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
244 #[derive(Clone, Debug)]
245 pub(crate) struct OfferContents {
246         chains: Option<Vec<ChainHash>>,
247         metadata: Option<Vec<u8>>,
248         amount: Option<Amount>,
249         description: String,
250         features: OfferFeatures,
251         absolute_expiry: Option<Duration>,
252         issuer: Option<String>,
253         paths: Option<Vec<BlindedPath>>,
254         supported_quantity: Quantity,
255         signing_pubkey: Option<PublicKey>,
256 }
257
258 impl Offer {
259         // TODO: Return a slice once ChainHash has constants.
260         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
261         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
262         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
263         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
264         /// for the selected chain.
265         pub fn chains(&self) -> Vec<ChainHash> {
266                 self.contents.chains
267                         .as_ref()
268                         .cloned()
269                         .unwrap_or_else(|| vec![self.contents.implied_chain()])
270         }
271
272         // TODO: Link to corresponding method in `InvoiceRequest`.
273         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
274         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
275         pub fn metadata(&self) -> Option<&Vec<u8>> {
276                 self.contents.metadata.as_ref()
277         }
278
279         /// The minimum amount required for a successful payment of a single item.
280         pub fn amount(&self) -> Option<&Amount> {
281                 self.contents.amount.as_ref()
282         }
283
284         /// A complete description of the purpose of the payment. Intended to be displayed to the user
285         /// but with the caveat that it has not been verified in any way.
286         pub fn description(&self) -> PrintableString {
287                 PrintableString(&self.contents.description)
288         }
289
290         /// Features pertaining to the offer.
291         pub fn features(&self) -> &OfferFeatures {
292                 &self.contents.features
293         }
294
295         /// Duration since the Unix epoch when an invoice should no longer be requested.
296         ///
297         /// If `None`, the offer does not expire.
298         pub fn absolute_expiry(&self) -> Option<Duration> {
299                 self.contents.absolute_expiry
300         }
301
302         /// Whether the offer has expired.
303         #[cfg(feature = "std")]
304         pub fn is_expired(&self) -> bool {
305                 match self.absolute_expiry() {
306                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
307                                 Ok(elapsed) => elapsed > seconds_from_epoch,
308                                 Err(_) => false,
309                         },
310                         None => false,
311                 }
312         }
313
314         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
315         /// displayed to the user but with the caveat that it has not been verified in any way.
316         pub fn issuer(&self) -> Option<PrintableString> {
317                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
318         }
319
320         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
321         /// recipient privacy by obfuscating its node id.
322         pub fn paths(&self) -> &[BlindedPath] {
323                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
324         }
325
326         /// The quantity of items supported.
327         pub fn supported_quantity(&self) -> Quantity {
328                 self.contents.supported_quantity()
329         }
330
331         /// The public key used by the recipient to sign invoices.
332         pub fn signing_pubkey(&self) -> PublicKey {
333                 self.contents.signing_pubkey.unwrap()
334         }
335
336         #[cfg(test)]
337         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
338                 self.contents.as_tlv_stream()
339         }
340 }
341
342 impl AsRef<[u8]> for Offer {
343         fn as_ref(&self) -> &[u8] {
344                 &self.bytes
345         }
346 }
347
348 impl OfferContents {
349         pub fn implied_chain(&self) -> ChainHash {
350                 ChainHash::using_genesis_block(Network::Bitcoin)
351         }
352
353         pub fn supported_quantity(&self) -> Quantity {
354                 self.supported_quantity
355         }
356
357         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
358                 let (currency, amount) = match &self.amount {
359                         None => (None, None),
360                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
361                         Some(Amount::Currency { iso4217_code, amount }) => (
362                                 Some(iso4217_code), Some(*amount)
363                         ),
364                 };
365
366                 let features = {
367                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
368                 };
369
370                 OfferTlvStreamRef {
371                         chains: self.chains.as_ref(),
372                         metadata: self.metadata.as_ref(),
373                         currency,
374                         amount,
375                         description: Some(&self.description),
376                         features,
377                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
378                         paths: self.paths.as_ref(),
379                         issuer: self.issuer.as_ref(),
380                         quantity_max: self.supported_quantity.to_tlv_record(),
381                         node_id: self.signing_pubkey.as_ref(),
382                 }
383         }
384 }
385
386 impl Writeable for Offer {
387         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
388                 WithoutLength(&self.bytes).write(writer)
389         }
390 }
391
392 impl Writeable for OfferContents {
393         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
394                 self.as_tlv_stream().write(writer)
395         }
396 }
397
398 impl TryFrom<Vec<u8>> for Offer {
399         type Error = ParseError;
400
401         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
402                 let tlv_stream: OfferTlvStream = Readable::read(&mut &bytes[..])?;
403                 Offer::try_from((bytes, tlv_stream))
404         }
405 }
406
407 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
408 /// another currency.
409 #[derive(Clone, Debug, PartialEq)]
410 pub enum Amount {
411         /// An amount of bitcoin.
412         Bitcoin {
413                 /// The amount in millisatoshi.
414                 amount_msats: u64,
415         },
416         /// An amount of currency specified using ISO 4712.
417         Currency {
418                 /// The currency that the amount is denominated in.
419                 iso4217_code: CurrencyCode,
420                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
421                 amount: u64,
422         },
423 }
424
425 /// An ISO 4712 three-letter currency code (e.g., USD).
426 pub type CurrencyCode = [u8; 3];
427
428 /// Quantity of items supported by an [`Offer`].
429 #[derive(Clone, Copy, Debug, PartialEq)]
430 pub enum Quantity {
431         /// Up to a specific number of items (inclusive).
432         Bounded(NonZeroU64),
433         /// One or more items.
434         Unbounded,
435 }
436
437 impl Quantity {
438         fn one() -> Self {
439                 Quantity::Bounded(NonZeroU64::new(1).unwrap())
440         }
441
442         fn to_tlv_record(&self) -> Option<u64> {
443                 match self {
444                         Quantity::Bounded(n) => {
445                                 let n = n.get();
446                                 if n == 1 { None } else { Some(n) }
447                         },
448                         Quantity::Unbounded => Some(0),
449                 }
450         }
451 }
452
453 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
454         (2, chains: (Vec<ChainHash>, WithoutLength)),
455         (4, metadata: (Vec<u8>, WithoutLength)),
456         (6, currency: CurrencyCode),
457         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
458         (10, description: (String, WithoutLength)),
459         (12, features: OfferFeatures),
460         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
461         (16, paths: (Vec<BlindedPath>, WithoutLength)),
462         (18, issuer: (String, WithoutLength)),
463         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
464         (22, node_id: PublicKey),
465 });
466
467 impl Bech32Encode for Offer {
468         const BECH32_HRP: &'static str = "lno";
469 }
470
471 type ParsedOffer = (Vec<u8>, OfferTlvStream);
472
473 impl FromStr for Offer {
474         type Err = ParseError;
475
476         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
477                 Self::from_bech32_str(s)
478         }
479 }
480
481 impl TryFrom<ParsedOffer> for Offer {
482         type Error = ParseError;
483
484         fn try_from(offer: ParsedOffer) -> Result<Self, Self::Error> {
485                 let (bytes, tlv_stream) = offer;
486                 let contents = OfferContents::try_from(tlv_stream)?;
487                 Ok(Offer { bytes, contents })
488         }
489 }
490
491 impl TryFrom<OfferTlvStream> for OfferContents {
492         type Error = SemanticError;
493
494         fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
495                 let OfferTlvStream {
496                         chains, metadata, currency, amount, description, features, absolute_expiry, paths,
497                         issuer, quantity_max, node_id,
498                 } = tlv_stream;
499
500                 let amount = match (currency, amount) {
501                         (None, None) => None,
502                         (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
503                                 return Err(SemanticError::InvalidAmount);
504                         },
505                         (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
506                         (Some(_), None) => return Err(SemanticError::MissingAmount),
507                         (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
508                 };
509
510                 let description = match description {
511                         None => return Err(SemanticError::MissingDescription),
512                         Some(description) => description,
513                 };
514
515                 let features = features.unwrap_or_else(OfferFeatures::empty);
516
517                 let absolute_expiry = absolute_expiry
518                         .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
519
520                 let supported_quantity = match quantity_max {
521                         None => Quantity::one(),
522                         Some(0) => Quantity::Unbounded,
523                         Some(1) => return Err(SemanticError::InvalidQuantity),
524                         Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
525                 };
526
527                 if node_id.is_none() {
528                         return Err(SemanticError::MissingSigningPubkey);
529                 }
530
531                 Ok(OfferContents {
532                         chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
533                         supported_quantity, signing_pubkey: node_id,
534                 })
535         }
536 }
537
538 impl core::fmt::Display for Offer {
539         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
540                 self.fmt_bech32_str(f)
541         }
542 }
543
544 #[cfg(test)]
545 mod tests {
546         use super::{Amount, Offer, OfferBuilder, Quantity};
547
548         use bitcoin::blockdata::constants::ChainHash;
549         use bitcoin::network::constants::Network;
550         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
551         use core::convert::TryFrom;
552         use core::num::NonZeroU64;
553         use core::time::Duration;
554         use crate::ln::features::OfferFeatures;
555         use crate::ln::msgs::MAX_VALUE_MSAT;
556         use crate::onion_message::{BlindedHop, BlindedPath};
557         use crate::util::ser::Writeable;
558         use crate::util::string::PrintableString;
559
560         fn pubkey(byte: u8) -> PublicKey {
561                 let secp_ctx = Secp256k1::new();
562                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
563         }
564
565         fn privkey(byte: u8) -> SecretKey {
566                 SecretKey::from_slice(&[byte; 32]).unwrap()
567         }
568
569         #[test]
570         fn builds_offer_with_defaults() {
571                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
572                 let tlv_stream = offer.as_tlv_stream();
573                 let mut buffer = Vec::new();
574                 offer.write(&mut buffer).unwrap();
575
576                 assert_eq!(offer.bytes, buffer.as_slice());
577                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
578                 assert_eq!(offer.metadata(), None);
579                 assert_eq!(offer.amount(), None);
580                 assert_eq!(offer.description(), PrintableString("foo"));
581                 assert_eq!(offer.features(), &OfferFeatures::empty());
582                 assert_eq!(offer.absolute_expiry(), None);
583                 #[cfg(feature = "std")]
584                 assert!(!offer.is_expired());
585                 assert_eq!(offer.paths(), &[]);
586                 assert_eq!(offer.issuer(), None);
587                 assert_eq!(offer.supported_quantity(), Quantity::one());
588                 assert_eq!(offer.signing_pubkey(), pubkey(42));
589
590                 assert_eq!(tlv_stream.chains, None);
591                 assert_eq!(tlv_stream.metadata, None);
592                 assert_eq!(tlv_stream.currency, None);
593                 assert_eq!(tlv_stream.amount, None);
594                 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
595                 assert_eq!(tlv_stream.features, None);
596                 assert_eq!(tlv_stream.absolute_expiry, None);
597                 assert_eq!(tlv_stream.paths, None);
598                 assert_eq!(tlv_stream.issuer, None);
599                 assert_eq!(tlv_stream.quantity_max, None);
600                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
601
602                 if let Err(e) = Offer::try_from(buffer) {
603                         panic!("error parsing offer: {:?}", e);
604                 }
605         }
606
607         #[test]
608         fn builds_offer_with_chains() {
609                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
610                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
611
612                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
613                         .chain(Network::Bitcoin)
614                         .build()
615                         .unwrap();
616                 assert_eq!(offer.chains(), vec![mainnet]);
617                 assert_eq!(offer.as_tlv_stream().chains, None);
618
619                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
620                         .chain(Network::Testnet)
621                         .build()
622                         .unwrap();
623                 assert_eq!(offer.chains(), vec![testnet]);
624                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
625
626                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
627                         .chain(Network::Testnet)
628                         .chain(Network::Testnet)
629                         .build()
630                         .unwrap();
631                 assert_eq!(offer.chains(), vec![testnet]);
632                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
633
634                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
635                         .chain(Network::Bitcoin)
636                         .chain(Network::Testnet)
637                         .build()
638                         .unwrap();
639                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
640                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
641         }
642
643         #[test]
644         fn builds_offer_with_metadata() {
645                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
646                         .metadata(vec![42; 32])
647                         .build()
648                         .unwrap();
649                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
650                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
651
652                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
653                         .metadata(vec![42; 32])
654                         .metadata(vec![43; 32])
655                         .build()
656                         .unwrap();
657                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
658                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
659         }
660
661         #[test]
662         fn builds_offer_with_amount() {
663                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
664                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
665
666                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
667                         .amount_msats(1000)
668                         .build()
669                         .unwrap();
670                 let tlv_stream = offer.as_tlv_stream();
671                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
672                 assert_eq!(tlv_stream.amount, Some(1000));
673                 assert_eq!(tlv_stream.currency, None);
674
675                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
676                         .amount(currency_amount.clone());
677                 let tlv_stream = builder.offer.as_tlv_stream();
678                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
679                 assert_eq!(tlv_stream.amount, Some(10));
680                 assert_eq!(tlv_stream.currency, Some(b"USD"));
681
682                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
683                         .amount(currency_amount.clone())
684                         .amount(bitcoin_amount.clone())
685                         .build()
686                         .unwrap();
687                 let tlv_stream = offer.as_tlv_stream();
688                 assert_eq!(tlv_stream.amount, Some(1000));
689                 assert_eq!(tlv_stream.currency, None);
690
691                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
692                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
693                         Ok(_) => panic!("expected error"),
694                         Err(e) => assert_eq!(e, ()),
695                 }
696         }
697
698         #[test]
699         fn builds_offer_with_features() {
700                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
701                         .features(OfferFeatures::unknown())
702                         .build()
703                         .unwrap();
704                 assert_eq!(offer.features(), &OfferFeatures::unknown());
705                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
706
707                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
708                         .features(OfferFeatures::unknown())
709                         .features(OfferFeatures::empty())
710                         .build()
711                         .unwrap();
712                 assert_eq!(offer.features(), &OfferFeatures::empty());
713                 assert_eq!(offer.as_tlv_stream().features, None);
714         }
715
716         #[test]
717         fn builds_offer_with_absolute_expiry() {
718                 let future_expiry = Duration::from_secs(u64::max_value());
719                 let past_expiry = Duration::from_secs(0);
720
721                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
722                         .absolute_expiry(future_expiry)
723                         .build()
724                         .unwrap();
725                 #[cfg(feature = "std")]
726                 assert!(!offer.is_expired());
727                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
728                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
729
730                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
731                         .absolute_expiry(future_expiry)
732                         .absolute_expiry(past_expiry)
733                         .build()
734                         .unwrap();
735                 #[cfg(feature = "std")]
736                 assert!(offer.is_expired());
737                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
738                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
739         }
740
741         #[test]
742         fn builds_offer_with_paths() {
743                 let paths = vec![
744                         BlindedPath {
745                                 introduction_node_id: pubkey(40),
746                                 blinding_point: pubkey(41),
747                                 blinded_hops: vec![
748                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
749                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
750                                 ],
751                         },
752                         BlindedPath {
753                                 introduction_node_id: pubkey(40),
754                                 blinding_point: pubkey(41),
755                                 blinded_hops: vec![
756                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
757                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
758                                 ],
759                         },
760                 ];
761
762                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
763                         .path(paths[0].clone())
764                         .path(paths[1].clone())
765                         .build()
766                         .unwrap();
767                 let tlv_stream = offer.as_tlv_stream();
768                 assert_eq!(offer.paths(), paths.as_slice());
769                 assert_eq!(offer.signing_pubkey(), pubkey(42));
770                 assert_ne!(pubkey(42), pubkey(44));
771                 assert_eq!(tlv_stream.paths, Some(&paths));
772                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
773         }
774
775         #[test]
776         fn builds_offer_with_issuer() {
777                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
778                         .issuer("bar".into())
779                         .build()
780                         .unwrap();
781                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
782                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
783
784                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
785                         .issuer("bar".into())
786                         .issuer("baz".into())
787                         .build()
788                         .unwrap();
789                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
790                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
791         }
792
793         #[test]
794         fn builds_offer_with_supported_quantity() {
795                 let ten = NonZeroU64::new(10).unwrap();
796
797                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
798                         .supported_quantity(Quantity::one())
799                         .build()
800                         .unwrap();
801                 let tlv_stream = offer.as_tlv_stream();
802                 assert_eq!(offer.supported_quantity(), Quantity::one());
803                 assert_eq!(tlv_stream.quantity_max, None);
804
805                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
806                         .supported_quantity(Quantity::Unbounded)
807                         .build()
808                         .unwrap();
809                 let tlv_stream = offer.as_tlv_stream();
810                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
811                 assert_eq!(tlv_stream.quantity_max, Some(0));
812
813                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
814                         .supported_quantity(Quantity::Bounded(ten))
815                         .build()
816                         .unwrap();
817                 let tlv_stream = offer.as_tlv_stream();
818                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
819                 assert_eq!(tlv_stream.quantity_max, Some(10));
820
821                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
822                         .supported_quantity(Quantity::Bounded(ten))
823                         .supported_quantity(Quantity::one())
824                         .build()
825                         .unwrap();
826                 let tlv_stream = offer.as_tlv_stream();
827                 assert_eq!(offer.supported_quantity(), Quantity::one());
828                 assert_eq!(tlv_stream.quantity_max, None);
829         }
830 }
831
832 #[cfg(test)]
833 mod bech32_tests {
834         use super::{Offer, ParseError};
835         use bitcoin::bech32;
836         use crate::ln::msgs::DecodeError;
837
838         // TODO: Remove once test vectors are updated.
839         #[ignore]
840         #[test]
841         fn encodes_offer_as_bech32_without_checksum() {
842                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
843                 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
844                 let reencoded_offer = offer.to_string();
845                 dbg!(reencoded_offer.parse::<Offer>().unwrap());
846                 assert_eq!(reencoded_offer, encoded_offer);
847         }
848
849         // TODO: Remove once test vectors are updated.
850         #[ignore]
851         #[test]
852         fn parses_bech32_encoded_offers() {
853                 let offers = [
854                         // BOLT 12 test vectors
855                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
856                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
857                         "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
858                         "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
859                         "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+  0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r  y",
860                         // Two blinded paths
861                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
862                 ];
863                 for encoded_offer in &offers {
864                         if let Err(e) = encoded_offer.parse::<Offer>() {
865                                 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
866                         }
867                 }
868         }
869
870         #[test]
871         fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
872                 let offers = [
873                         // BOLT 12 test vectors
874                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
875                         "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
876                         "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
877                         "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
878                         "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
879                 ];
880                 for encoded_offer in &offers {
881                         match encoded_offer.parse::<Offer>() {
882                                 Ok(_) => panic!("Valid offer: {}", encoded_offer),
883                                 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
884                         }
885                 }
886
887         }
888
889         #[test]
890         fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
891                 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
892                 match encoded_offer.parse::<Offer>() {
893                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
894                         Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
895                 }
896         }
897
898         #[test]
899         fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
900                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
901                 match encoded_offer.parse::<Offer>() {
902                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
903                         Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
904                 }
905         }
906
907         #[test]
908         fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
909                 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
910                 match encoded_offer.parse::<Offer>() {
911                         Ok(_) => panic!("Valid offer: {}", encoded_offer),
912                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
913                 }
914         }
915 }