1 // This file is Copyright its original authors, visible in version control
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
10 //! Data structures and encoding for `offer` messages.
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.
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
21 //! use core::convert::TryFrom;
22 //! use core::num::NonZeroU64;
23 //! use core::time::Duration;
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};
30 //! # use lightning::onion_message::BlindedPath;
31 //! # #[cfg(feature = "std")]
32 //! # use std::time::SystemTime;
34 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
35 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
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);
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())
53 //! // Encode as a bech32 string for use in a QR code.
54 //! let encoded_offer = offer.to_string();
56 //! // Parse from a bech32 string after scanning from a QR code.
57 //! let offer = encoded_offer.parse::<Offer>()?;
59 //! // Encode offer as raw bytes.
60 //! let mut bytes = Vec::new();
61 //! offer.write(&mut bytes).unwrap();
63 //! // Decode raw bytes into an offer.
64 //! let offer = Offer::try_from(bytes)?;
69 use bitcoin::blockdata::constants::ChainHash;
70 use bitcoin::network::constants::Network;
71 use bitcoin::secp256k1::PublicKey;
72 use core::convert::TryFrom;
73 use core::num::NonZeroU64;
74 use core::str::FromStr;
75 use core::time::Duration;
77 use crate::ln::features::OfferFeatures;
78 use crate::ln::msgs::MAX_VALUE_MSAT;
79 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
80 use crate::onion_message::BlindedPath;
81 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
82 use crate::util::string::PrintableString;
84 use crate::prelude::*;
86 #[cfg(feature = "std")]
87 use std::time::SystemTime;
89 /// Builds an [`Offer`] for the "offer to be paid" flow.
91 /// See [module-level documentation] for usage.
93 /// [module-level documentation]: self
94 pub struct OfferBuilder {
99 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
100 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
101 /// while the offer is valid.
103 /// Use a different pubkey per offer to avoid correlating offers.
104 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
105 let offer = OfferContents {
106 chains: None, metadata: None, amount: None, description,
107 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
108 supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
110 OfferBuilder { offer }
113 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
114 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
116 /// See [`Offer::chains`] on how this relates to the payment currency.
118 /// Successive calls to this method will add another chain hash.
119 pub fn chain(mut self, network: Network) -> Self {
120 let chains = self.offer.chains.get_or_insert_with(Vec::new);
121 let chain = ChainHash::using_genesis_block(network);
122 if !chains.contains(&chain) {
129 /// Sets the [`Offer::metadata`].
131 /// Successive calls to this method will override the previous setting.
132 pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
133 self.offer.metadata = Some(metadata);
137 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
139 /// Successive calls to this method will override the previous setting.
140 pub fn amount_msats(mut self, amount_msats: u64) -> Self {
141 self.amount(Amount::Bitcoin { amount_msats })
144 /// Sets the [`Offer::amount`].
146 /// Successive calls to this method will override the previous setting.
147 fn amount(mut self, amount: Amount) -> Self {
148 self.offer.amount = Some(amount);
152 /// Sets the [`Offer::features`].
154 /// Successive calls to this method will override the previous setting.
156 pub fn features(mut self, features: OfferFeatures) -> Self {
157 self.offer.features = features;
161 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
162 /// already passed is valid and can be checked for using [`Offer::is_expired`].
164 /// Successive calls to this method will override the previous setting.
165 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
166 self.offer.absolute_expiry = Some(absolute_expiry);
170 /// Sets the [`Offer::issuer`].
172 /// Successive calls to this method will override the previous setting.
173 pub fn issuer(mut self, issuer: String) -> Self {
174 self.offer.issuer = Some(issuer);
178 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
179 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
181 /// Successive calls to this method will add another blinded path. Caller is responsible for not
182 /// adding duplicate paths.
183 pub fn path(mut self, path: BlindedPath) -> Self {
184 self.offer.paths.get_or_insert_with(Vec::new).push(path);
188 /// Sets the quantity of items for [`Offer::supported_quantity`].
190 /// Successive calls to this method will override the previous setting.
191 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
192 self.offer.supported_quantity = quantity;
196 /// Builds an [`Offer`] from the builder's settings.
197 pub fn build(mut self) -> Result<Offer, SemanticError> {
198 match self.offer.amount {
199 Some(Amount::Bitcoin { amount_msats }) => {
200 if amount_msats > MAX_VALUE_MSAT {
201 return Err(SemanticError::InvalidAmount);
204 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
208 if let Some(chains) = &self.offer.chains {
209 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
210 self.offer.chains = None;
214 let mut bytes = Vec::new();
215 self.offer.write(&mut bytes).unwrap();
219 contents: self.offer,
224 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
226 /// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
227 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
228 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
230 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
233 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
234 #[derive(Clone, Debug)]
236 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
239 contents: OfferContents,
242 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
243 #[derive(Clone, Debug)]
244 pub(crate) struct OfferContents {
245 chains: Option<Vec<ChainHash>>,
246 metadata: Option<Vec<u8>>,
247 amount: Option<Amount>,
249 features: OfferFeatures,
250 absolute_expiry: Option<Duration>,
251 issuer: Option<String>,
252 paths: Option<Vec<BlindedPath>>,
253 supported_quantity: Quantity,
254 signing_pubkey: Option<PublicKey>,
258 // TODO: Return a slice once ChainHash has constants.
259 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
260 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
261 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
262 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
263 /// for the selected chain.
264 pub fn chains(&self) -> Vec<ChainHash> {
268 .unwrap_or_else(|| vec![self.contents.implied_chain()])
271 // TODO: Link to corresponding method in `InvoiceRequest`.
272 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
273 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
274 pub fn metadata(&self) -> Option<&Vec<u8>> {
275 self.contents.metadata.as_ref()
278 /// The minimum amount required for a successful payment of a single item.
279 pub fn amount(&self) -> Option<&Amount> {
280 self.contents.amount.as_ref()
283 /// A complete description of the purpose of the payment. Intended to be displayed to the user
284 /// but with the caveat that it has not been verified in any way.
285 pub fn description(&self) -> PrintableString {
286 PrintableString(&self.contents.description)
289 /// Features pertaining to the offer.
290 pub fn features(&self) -> &OfferFeatures {
291 &self.contents.features
294 /// Duration since the Unix epoch when an invoice should no longer be requested.
296 /// If `None`, the offer does not expire.
297 pub fn absolute_expiry(&self) -> Option<Duration> {
298 self.contents.absolute_expiry
301 /// Whether the offer has expired.
302 #[cfg(feature = "std")]
303 pub fn is_expired(&self) -> bool {
304 match self.absolute_expiry() {
305 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
306 Ok(elapsed) => elapsed > seconds_from_epoch,
313 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
314 /// displayed to the user but with the caveat that it has not been verified in any way.
315 pub fn issuer(&self) -> Option<PrintableString> {
316 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
319 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
320 /// recipient privacy by obfuscating its node id.
321 pub fn paths(&self) -> &[BlindedPath] {
322 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
325 /// The quantity of items supported.
326 pub fn supported_quantity(&self) -> Quantity {
327 self.contents.supported_quantity()
330 /// The public key used by the recipient to sign invoices.
331 pub fn signing_pubkey(&self) -> PublicKey {
332 self.contents.signing_pubkey.unwrap()
336 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
337 self.contents.as_tlv_stream()
341 impl AsRef<[u8]> for Offer {
342 fn as_ref(&self) -> &[u8] {
348 pub fn implied_chain(&self) -> ChainHash {
349 ChainHash::using_genesis_block(Network::Bitcoin)
352 pub fn supported_quantity(&self) -> Quantity {
353 self.supported_quantity
356 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
357 let (currency, amount) = match &self.amount {
358 None => (None, None),
359 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
360 Some(Amount::Currency { iso4217_code, amount }) => (
361 Some(iso4217_code), Some(*amount)
366 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
370 chains: self.chains.as_ref(),
371 metadata: self.metadata.as_ref(),
374 description: Some(&self.description),
376 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
377 paths: self.paths.as_ref(),
378 issuer: self.issuer.as_ref(),
379 quantity_max: self.supported_quantity.to_tlv_record(),
380 node_id: self.signing_pubkey.as_ref(),
385 impl Writeable for Offer {
386 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
387 WithoutLength(&self.bytes).write(writer)
391 impl Writeable for OfferContents {
392 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
393 self.as_tlv_stream().write(writer)
397 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
398 /// another currency.
399 #[derive(Clone, Debug, PartialEq)]
401 /// An amount of bitcoin.
403 /// The amount in millisatoshi.
406 /// An amount of currency specified using ISO 4712.
408 /// The currency that the amount is denominated in.
409 iso4217_code: CurrencyCode,
410 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
415 /// An ISO 4712 three-letter currency code (e.g., USD).
416 pub type CurrencyCode = [u8; 3];
418 /// Quantity of items supported by an [`Offer`].
419 #[derive(Clone, Copy, Debug, PartialEq)]
421 /// Up to a specific number of items (inclusive).
423 /// One or more items.
429 Quantity::Bounded(NonZeroU64::new(1).unwrap())
432 fn to_tlv_record(&self) -> Option<u64> {
434 Quantity::Bounded(n) => {
436 if n == 1 { None } else { Some(n) }
438 Quantity::Unbounded => Some(0),
443 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
444 (2, chains: (Vec<ChainHash>, WithoutLength)),
445 (4, metadata: (Vec<u8>, WithoutLength)),
446 (6, currency: CurrencyCode),
447 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
448 (10, description: (String, WithoutLength)),
449 (12, features: OfferFeatures),
450 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
451 (16, paths: (Vec<BlindedPath>, WithoutLength)),
452 (18, issuer: (String, WithoutLength)),
453 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
454 (22, node_id: PublicKey),
457 impl Bech32Encode for Offer {
458 const BECH32_HRP: &'static str = "lno";
461 impl FromStr for Offer {
462 type Err = ParseError;
464 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
465 Self::from_bech32_str(s)
469 impl TryFrom<Vec<u8>> for Offer {
470 type Error = ParseError;
472 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
473 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
474 let ParsedMessage { bytes, tlv_stream } = offer;
475 let contents = OfferContents::try_from(tlv_stream)?;
476 Ok(Offer { bytes, contents })
480 impl TryFrom<OfferTlvStream> for OfferContents {
481 type Error = SemanticError;
483 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
485 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
486 issuer, quantity_max, node_id,
489 let amount = match (currency, amount) {
490 (None, None) => None,
491 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
492 return Err(SemanticError::InvalidAmount);
494 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
495 (Some(_), None) => return Err(SemanticError::MissingAmount),
496 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
499 let description = match description {
500 None => return Err(SemanticError::MissingDescription),
501 Some(description) => description,
504 let features = features.unwrap_or_else(OfferFeatures::empty);
506 let absolute_expiry = absolute_expiry
507 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
509 let supported_quantity = match quantity_max {
510 None => Quantity::one(),
511 Some(0) => Quantity::Unbounded,
512 Some(1) => return Err(SemanticError::InvalidQuantity),
513 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
516 if node_id.is_none() {
517 return Err(SemanticError::MissingSigningPubkey);
521 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
522 supported_quantity, signing_pubkey: node_id,
527 impl core::fmt::Display for Offer {
528 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
529 self.fmt_bech32_str(f)
535 use super::{Amount, Offer, OfferBuilder, Quantity};
537 use bitcoin::blockdata::constants::ChainHash;
538 use bitcoin::network::constants::Network;
539 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
540 use core::convert::TryFrom;
541 use core::num::NonZeroU64;
542 use core::time::Duration;
543 use crate::ln::features::OfferFeatures;
544 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
545 use crate::offers::parse::{ParseError, SemanticError};
546 use crate::onion_message::{BlindedHop, BlindedPath};
547 use crate::util::ser::{BigSize, Writeable};
548 use crate::util::string::PrintableString;
550 fn pubkey(byte: u8) -> PublicKey {
551 let secp_ctx = Secp256k1::new();
552 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
555 fn privkey(byte: u8) -> SecretKey {
556 SecretKey::from_slice(&[byte; 32]).unwrap()
560 fn builds_offer_with_defaults() {
561 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
562 let tlv_stream = offer.as_tlv_stream();
563 let mut buffer = Vec::new();
564 offer.write(&mut buffer).unwrap();
566 assert_eq!(offer.bytes, buffer.as_slice());
567 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
568 assert_eq!(offer.metadata(), None);
569 assert_eq!(offer.amount(), None);
570 assert_eq!(offer.description(), PrintableString("foo"));
571 assert_eq!(offer.features(), &OfferFeatures::empty());
572 assert_eq!(offer.absolute_expiry(), None);
573 #[cfg(feature = "std")]
574 assert!(!offer.is_expired());
575 assert_eq!(offer.paths(), &[]);
576 assert_eq!(offer.issuer(), None);
577 assert_eq!(offer.supported_quantity(), Quantity::one());
578 assert_eq!(offer.signing_pubkey(), pubkey(42));
580 assert_eq!(tlv_stream.chains, None);
581 assert_eq!(tlv_stream.metadata, None);
582 assert_eq!(tlv_stream.currency, None);
583 assert_eq!(tlv_stream.amount, None);
584 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
585 assert_eq!(tlv_stream.features, None);
586 assert_eq!(tlv_stream.absolute_expiry, None);
587 assert_eq!(tlv_stream.paths, None);
588 assert_eq!(tlv_stream.issuer, None);
589 assert_eq!(tlv_stream.quantity_max, None);
590 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
592 if let Err(e) = Offer::try_from(buffer) {
593 panic!("error parsing offer: {:?}", e);
598 fn builds_offer_with_chains() {
599 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
600 let testnet = ChainHash::using_genesis_block(Network::Testnet);
602 let offer = OfferBuilder::new("foo".into(), pubkey(42))
603 .chain(Network::Bitcoin)
606 assert_eq!(offer.chains(), vec![mainnet]);
607 assert_eq!(offer.as_tlv_stream().chains, None);
609 let offer = OfferBuilder::new("foo".into(), pubkey(42))
610 .chain(Network::Testnet)
613 assert_eq!(offer.chains(), vec![testnet]);
614 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
616 let offer = OfferBuilder::new("foo".into(), pubkey(42))
617 .chain(Network::Testnet)
618 .chain(Network::Testnet)
621 assert_eq!(offer.chains(), vec![testnet]);
622 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
624 let offer = OfferBuilder::new("foo".into(), pubkey(42))
625 .chain(Network::Bitcoin)
626 .chain(Network::Testnet)
629 assert_eq!(offer.chains(), vec![mainnet, testnet]);
630 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
634 fn builds_offer_with_metadata() {
635 let offer = OfferBuilder::new("foo".into(), pubkey(42))
636 .metadata(vec![42; 32])
639 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
640 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
642 let offer = OfferBuilder::new("foo".into(), pubkey(42))
643 .metadata(vec![42; 32])
644 .metadata(vec![43; 32])
647 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
648 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
652 fn builds_offer_with_amount() {
653 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
654 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
656 let offer = OfferBuilder::new("foo".into(), pubkey(42))
660 let tlv_stream = offer.as_tlv_stream();
661 assert_eq!(offer.amount(), Some(&bitcoin_amount));
662 assert_eq!(tlv_stream.amount, Some(1000));
663 assert_eq!(tlv_stream.currency, None);
665 let builder = OfferBuilder::new("foo".into(), pubkey(42))
666 .amount(currency_amount.clone());
667 let tlv_stream = builder.offer.as_tlv_stream();
668 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
669 assert_eq!(tlv_stream.amount, Some(10));
670 assert_eq!(tlv_stream.currency, Some(b"USD"));
671 match builder.build() {
672 Ok(_) => panic!("expected error"),
673 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
676 let offer = OfferBuilder::new("foo".into(), pubkey(42))
677 .amount(currency_amount.clone())
678 .amount(bitcoin_amount.clone())
681 let tlv_stream = offer.as_tlv_stream();
682 assert_eq!(tlv_stream.amount, Some(1000));
683 assert_eq!(tlv_stream.currency, None);
685 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
686 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
687 Ok(_) => panic!("expected error"),
688 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
693 fn builds_offer_with_features() {
694 let offer = OfferBuilder::new("foo".into(), pubkey(42))
695 .features(OfferFeatures::unknown())
698 assert_eq!(offer.features(), &OfferFeatures::unknown());
699 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
701 let offer = OfferBuilder::new("foo".into(), pubkey(42))
702 .features(OfferFeatures::unknown())
703 .features(OfferFeatures::empty())
706 assert_eq!(offer.features(), &OfferFeatures::empty());
707 assert_eq!(offer.as_tlv_stream().features, None);
711 fn builds_offer_with_absolute_expiry() {
712 let future_expiry = Duration::from_secs(u64::max_value());
713 let past_expiry = Duration::from_secs(0);
715 let offer = OfferBuilder::new("foo".into(), pubkey(42))
716 .absolute_expiry(future_expiry)
719 #[cfg(feature = "std")]
720 assert!(!offer.is_expired());
721 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
722 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
724 let offer = OfferBuilder::new("foo".into(), pubkey(42))
725 .absolute_expiry(future_expiry)
726 .absolute_expiry(past_expiry)
729 #[cfg(feature = "std")]
730 assert!(offer.is_expired());
731 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
732 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
736 fn builds_offer_with_paths() {
739 introduction_node_id: pubkey(40),
740 blinding_point: pubkey(41),
742 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
743 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
747 introduction_node_id: pubkey(40),
748 blinding_point: pubkey(41),
750 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
751 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
756 let offer = OfferBuilder::new("foo".into(), pubkey(42))
757 .path(paths[0].clone())
758 .path(paths[1].clone())
761 let tlv_stream = offer.as_tlv_stream();
762 assert_eq!(offer.paths(), paths.as_slice());
763 assert_eq!(offer.signing_pubkey(), pubkey(42));
764 assert_ne!(pubkey(42), pubkey(44));
765 assert_eq!(tlv_stream.paths, Some(&paths));
766 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
770 fn builds_offer_with_issuer() {
771 let offer = OfferBuilder::new("foo".into(), pubkey(42))
772 .issuer("bar".into())
775 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
776 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
778 let offer = OfferBuilder::new("foo".into(), pubkey(42))
779 .issuer("bar".into())
780 .issuer("baz".into())
783 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
784 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
788 fn builds_offer_with_supported_quantity() {
789 let ten = NonZeroU64::new(10).unwrap();
791 let offer = OfferBuilder::new("foo".into(), pubkey(42))
792 .supported_quantity(Quantity::one())
795 let tlv_stream = offer.as_tlv_stream();
796 assert_eq!(offer.supported_quantity(), Quantity::one());
797 assert_eq!(tlv_stream.quantity_max, None);
799 let offer = OfferBuilder::new("foo".into(), pubkey(42))
800 .supported_quantity(Quantity::Unbounded)
803 let tlv_stream = offer.as_tlv_stream();
804 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
805 assert_eq!(tlv_stream.quantity_max, Some(0));
807 let offer = OfferBuilder::new("foo".into(), pubkey(42))
808 .supported_quantity(Quantity::Bounded(ten))
811 let tlv_stream = offer.as_tlv_stream();
812 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
813 assert_eq!(tlv_stream.quantity_max, Some(10));
815 let offer = OfferBuilder::new("foo".into(), pubkey(42))
816 .supported_quantity(Quantity::Bounded(ten))
817 .supported_quantity(Quantity::one())
820 let tlv_stream = offer.as_tlv_stream();
821 assert_eq!(offer.supported_quantity(), Quantity::one());
822 assert_eq!(tlv_stream.quantity_max, None);
826 fn parses_offer_with_chains() {
827 let offer = OfferBuilder::new("foo".into(), pubkey(42))
828 .chain(Network::Bitcoin)
829 .chain(Network::Testnet)
832 if let Err(e) = offer.to_string().parse::<Offer>() {
833 panic!("error parsing offer: {:?}", e);
838 fn parses_offer_with_amount() {
839 let offer = OfferBuilder::new("foo".into(), pubkey(42))
840 .amount(Amount::Bitcoin { amount_msats: 1000 })
843 if let Err(e) = offer.to_string().parse::<Offer>() {
844 panic!("error parsing offer: {:?}", e);
847 let mut tlv_stream = offer.as_tlv_stream();
848 tlv_stream.amount = Some(1000);
849 tlv_stream.currency = Some(b"USD");
851 let mut encoded_offer = Vec::new();
852 tlv_stream.write(&mut encoded_offer).unwrap();
854 if let Err(e) = Offer::try_from(encoded_offer) {
855 panic!("error parsing offer: {:?}", e);
858 let mut tlv_stream = offer.as_tlv_stream();
859 tlv_stream.amount = None;
860 tlv_stream.currency = Some(b"USD");
862 let mut encoded_offer = Vec::new();
863 tlv_stream.write(&mut encoded_offer).unwrap();
865 match Offer::try_from(encoded_offer) {
866 Ok(_) => panic!("expected error"),
867 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
870 let mut tlv_stream = offer.as_tlv_stream();
871 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
872 tlv_stream.currency = None;
874 let mut encoded_offer = Vec::new();
875 tlv_stream.write(&mut encoded_offer).unwrap();
877 match Offer::try_from(encoded_offer) {
878 Ok(_) => panic!("expected error"),
879 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
884 fn parses_offer_with_description() {
885 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
886 if let Err(e) = offer.to_string().parse::<Offer>() {
887 panic!("error parsing offer: {:?}", e);
890 let mut tlv_stream = offer.as_tlv_stream();
891 tlv_stream.description = None;
893 let mut encoded_offer = Vec::new();
894 tlv_stream.write(&mut encoded_offer).unwrap();
896 match Offer::try_from(encoded_offer) {
897 Ok(_) => panic!("expected error"),
899 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
905 fn parses_offer_with_paths() {
906 let offer = OfferBuilder::new("foo".into(), pubkey(42))
908 introduction_node_id: pubkey(40),
909 blinding_point: pubkey(41),
911 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
912 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
916 introduction_node_id: pubkey(40),
917 blinding_point: pubkey(41),
919 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
920 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
925 if let Err(e) = offer.to_string().parse::<Offer>() {
926 panic!("error parsing offer: {:?}", e);
929 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
930 builder.offer.paths = Some(vec![]);
932 let offer = builder.build().unwrap();
933 if let Err(e) = offer.to_string().parse::<Offer>() {
934 panic!("error parsing offer: {:?}", e);
939 fn parses_offer_with_quantity() {
940 let offer = OfferBuilder::new("foo".into(), pubkey(42))
941 .supported_quantity(Quantity::one())
944 if let Err(e) = offer.to_string().parse::<Offer>() {
945 panic!("error parsing offer: {:?}", e);
948 let offer = OfferBuilder::new("foo".into(), pubkey(42))
949 .supported_quantity(Quantity::Unbounded)
952 if let Err(e) = offer.to_string().parse::<Offer>() {
953 panic!("error parsing offer: {:?}", e);
956 let offer = OfferBuilder::new("foo".into(), pubkey(42))
957 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
960 if let Err(e) = offer.to_string().parse::<Offer>() {
961 panic!("error parsing offer: {:?}", e);
964 let mut tlv_stream = offer.as_tlv_stream();
965 tlv_stream.quantity_max = Some(1);
967 let mut encoded_offer = Vec::new();
968 tlv_stream.write(&mut encoded_offer).unwrap();
970 match Offer::try_from(encoded_offer) {
971 Ok(_) => panic!("expected error"),
973 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
979 fn parses_offer_with_node_id() {
980 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
981 if let Err(e) = offer.to_string().parse::<Offer>() {
982 panic!("error parsing offer: {:?}", e);
985 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
986 builder.offer.signing_pubkey = None;
988 let offer = builder.build().unwrap();
989 match offer.to_string().parse::<Offer>() {
990 Ok(_) => panic!("expected error"),
992 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
998 fn fails_parsing_offer_with_extra_tlv_records() {
999 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1001 let mut encoded_offer = Vec::new();
1002 offer.write(&mut encoded_offer).unwrap();
1003 BigSize(80).write(&mut encoded_offer).unwrap();
1004 BigSize(32).write(&mut encoded_offer).unwrap();
1005 [42u8; 32].write(&mut encoded_offer).unwrap();
1007 match Offer::try_from(encoded_offer) {
1008 Ok(_) => panic!("expected error"),
1009 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1016 use super::{Offer, ParseError};
1017 use bitcoin::bech32;
1018 use crate::ln::msgs::DecodeError;
1020 // TODO: Remove once test vectors are updated.
1023 fn encodes_offer_as_bech32_without_checksum() {
1024 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1025 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1026 let reencoded_offer = offer.to_string();
1027 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1028 assert_eq!(reencoded_offer, encoded_offer);
1031 // TODO: Remove once test vectors are updated.
1034 fn parses_bech32_encoded_offers() {
1036 // BOLT 12 test vectors
1037 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1038 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1039 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1040 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1041 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1042 // Two blinded paths
1043 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1045 for encoded_offer in &offers {
1046 if let Err(e) = encoded_offer.parse::<Offer>() {
1047 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1053 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1055 // BOLT 12 test vectors
1056 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1057 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1058 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1059 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1060 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1062 for encoded_offer in &offers {
1063 match encoded_offer.parse::<Offer>() {
1064 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1065 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1072 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1073 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1074 match encoded_offer.parse::<Offer>() {
1075 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1076 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1081 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1082 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1083 match encoded_offer.parse::<Offer>() {
1084 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1085 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1090 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1091 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1092 match encoded_offer.parse::<Offer>() {
1093 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1094 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),