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(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`]. If not called, defaults to
189 /// [`Quantity::one`].
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;
197 /// Builds an [`Offer`] from the builder's settings.
198 pub fn build(mut self) -> Result<Offer, SemanticError> {
199 match self.offer.amount {
200 Some(Amount::Bitcoin { amount_msats }) => {
201 if amount_msats > MAX_VALUE_MSAT {
202 return Err(SemanticError::InvalidAmount);
205 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
209 if let Some(chains) = &self.offer.chains {
210 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
211 self.offer.chains = None;
215 let mut bytes = Vec::new();
216 self.offer.write(&mut bytes).unwrap();
220 contents: self.offer,
225 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
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`].
231 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
234 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
236 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
237 #[derive(Clone, Debug)]
239 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
242 contents: OfferContents,
245 /// The contents of an [`Offer`], which may be shared with an [`InvoiceRequest`] or an `Invoice`.
247 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
248 #[derive(Clone, Debug)]
249 pub(super) struct OfferContents {
250 chains: Option<Vec<ChainHash>>,
251 metadata: Option<Vec<u8>>,
252 amount: Option<Amount>,
254 features: OfferFeatures,
255 absolute_expiry: Option<Duration>,
256 issuer: Option<String>,
257 paths: Option<Vec<BlindedPath>>,
258 supported_quantity: Quantity,
259 signing_pubkey: Option<PublicKey>,
263 // TODO: Return a slice once ChainHash has constants.
264 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
265 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
266 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
267 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
268 /// for the selected chain.
269 pub fn chains(&self) -> Vec<ChainHash> {
270 self.contents.chains()
273 // TODO: Link to corresponding method in `InvoiceRequest`.
274 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
275 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
276 pub fn metadata(&self) -> Option<&Vec<u8>> {
277 self.contents.metadata.as_ref()
280 /// The minimum amount required for a successful payment of a single item.
281 pub fn amount(&self) -> Option<&Amount> {
282 self.contents.amount.as_ref()
285 /// A complete description of the purpose of the payment. Intended to be displayed to the user
286 /// but with the caveat that it has not been verified in any way.
287 pub fn description(&self) -> PrintableString {
288 PrintableString(&self.contents.description)
291 /// Features pertaining to the offer.
292 pub fn features(&self) -> &OfferFeatures {
293 &self.contents.features
296 /// Duration since the Unix epoch when an invoice should no longer be requested.
298 /// If `None`, the offer does not expire.
299 pub fn absolute_expiry(&self) -> Option<Duration> {
300 self.contents.absolute_expiry
303 /// Whether the offer has expired.
304 #[cfg(feature = "std")]
305 pub fn is_expired(&self) -> bool {
306 match self.absolute_expiry() {
307 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
308 Ok(elapsed) => elapsed > seconds_from_epoch,
315 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
316 /// displayed to the user but with the caveat that it has not been verified in any way.
317 pub fn issuer(&self) -> Option<PrintableString> {
318 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
321 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
322 /// recipient privacy by obfuscating its node id.
323 pub fn paths(&self) -> &[BlindedPath] {
324 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
327 /// The quantity of items supported.
328 pub fn supported_quantity(&self) -> Quantity {
329 self.contents.supported_quantity()
332 /// The public key used by the recipient to sign invoices.
333 pub fn signing_pubkey(&self) -> PublicKey {
334 self.contents.signing_pubkey.unwrap()
338 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
339 self.contents.as_tlv_stream()
343 impl AsRef<[u8]> for Offer {
344 fn as_ref(&self) -> &[u8] {
350 pub fn chains(&self) -> Vec<ChainHash> {
351 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
354 pub fn implied_chain(&self) -> ChainHash {
355 ChainHash::using_genesis_block(Network::Bitcoin)
358 pub fn supported_quantity(&self) -> Quantity {
359 self.supported_quantity
362 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
363 let (currency, amount) = match &self.amount {
364 None => (None, None),
365 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
366 Some(Amount::Currency { iso4217_code, amount }) => (
367 Some(iso4217_code), Some(*amount)
372 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
376 chains: self.chains.as_ref(),
377 metadata: self.metadata.as_ref(),
380 description: Some(&self.description),
382 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
383 paths: self.paths.as_ref(),
384 issuer: self.issuer.as_ref(),
385 quantity_max: self.supported_quantity.to_tlv_record(),
386 node_id: self.signing_pubkey.as_ref(),
391 impl Writeable for Offer {
392 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
393 WithoutLength(&self.bytes).write(writer)
397 impl Writeable for OfferContents {
398 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
399 self.as_tlv_stream().write(writer)
403 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
404 /// another currency.
405 #[derive(Clone, Debug, PartialEq)]
407 /// An amount of bitcoin.
409 /// The amount in millisatoshi.
412 /// An amount of currency specified using ISO 4712.
414 /// The currency that the amount is denominated in.
415 iso4217_code: CurrencyCode,
416 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
421 /// An ISO 4712 three-letter currency code (e.g., USD).
422 pub type CurrencyCode = [u8; 3];
424 /// Quantity of items supported by an [`Offer`].
425 #[derive(Clone, Copy, Debug, PartialEq)]
427 /// Up to a specific number of items (inclusive).
429 /// One or more items.
434 /// The default quantity of one.
435 pub fn one() -> Self {
436 Quantity::Bounded(NonZeroU64::new(1).unwrap())
439 fn to_tlv_record(&self) -> Option<u64> {
441 Quantity::Bounded(n) => {
443 if n == 1 { None } else { Some(n) }
445 Quantity::Unbounded => Some(0),
450 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
451 (2, chains: (Vec<ChainHash>, WithoutLength)),
452 (4, metadata: (Vec<u8>, WithoutLength)),
453 (6, currency: CurrencyCode),
454 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
455 (10, description: (String, WithoutLength)),
456 (12, features: OfferFeatures),
457 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
458 (16, paths: (Vec<BlindedPath>, WithoutLength)),
459 (18, issuer: (String, WithoutLength)),
460 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
461 (22, node_id: PublicKey),
464 impl Bech32Encode for Offer {
465 const BECH32_HRP: &'static str = "lno";
468 impl FromStr for Offer {
469 type Err = ParseError;
471 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
472 Self::from_bech32_str(s)
476 impl TryFrom<Vec<u8>> for Offer {
477 type Error = ParseError;
479 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
480 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
481 let ParsedMessage { bytes, tlv_stream } = offer;
482 let contents = OfferContents::try_from(tlv_stream)?;
483 Ok(Offer { bytes, contents })
487 impl TryFrom<OfferTlvStream> for OfferContents {
488 type Error = SemanticError;
490 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
492 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
493 issuer, quantity_max, node_id,
496 let amount = match (currency, amount) {
497 (None, None) => None,
498 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
499 return Err(SemanticError::InvalidAmount);
501 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
502 (Some(_), None) => return Err(SemanticError::MissingAmount),
503 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
506 let description = match description {
507 None => return Err(SemanticError::MissingDescription),
508 Some(description) => description,
511 let features = features.unwrap_or_else(OfferFeatures::empty);
513 let absolute_expiry = absolute_expiry
514 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
516 let supported_quantity = match quantity_max {
517 None => Quantity::one(),
518 Some(0) => Quantity::Unbounded,
519 Some(1) => return Err(SemanticError::InvalidQuantity),
520 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
523 if node_id.is_none() {
524 return Err(SemanticError::MissingSigningPubkey);
528 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
529 supported_quantity, signing_pubkey: node_id,
534 impl core::fmt::Display for Offer {
535 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
536 self.fmt_bech32_str(f)
542 use super::{Amount, Offer, OfferBuilder, Quantity};
544 use bitcoin::blockdata::constants::ChainHash;
545 use bitcoin::network::constants::Network;
546 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
547 use core::convert::TryFrom;
548 use core::num::NonZeroU64;
549 use core::time::Duration;
550 use crate::ln::features::OfferFeatures;
551 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
552 use crate::offers::parse::{ParseError, SemanticError};
553 use crate::onion_message::{BlindedHop, BlindedPath};
554 use crate::util::ser::{BigSize, Writeable};
555 use crate::util::string::PrintableString;
557 fn pubkey(byte: u8) -> PublicKey {
558 let secp_ctx = Secp256k1::new();
559 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
562 fn privkey(byte: u8) -> SecretKey {
563 SecretKey::from_slice(&[byte; 32]).unwrap()
567 fn builds_offer_with_defaults() {
568 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
569 let tlv_stream = offer.as_tlv_stream();
570 let mut buffer = Vec::new();
571 offer.write(&mut buffer).unwrap();
573 assert_eq!(offer.bytes, buffer.as_slice());
574 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
575 assert_eq!(offer.metadata(), None);
576 assert_eq!(offer.amount(), None);
577 assert_eq!(offer.description(), PrintableString("foo"));
578 assert_eq!(offer.features(), &OfferFeatures::empty());
579 assert_eq!(offer.absolute_expiry(), None);
580 #[cfg(feature = "std")]
581 assert!(!offer.is_expired());
582 assert_eq!(offer.paths(), &[]);
583 assert_eq!(offer.issuer(), None);
584 assert_eq!(offer.supported_quantity(), Quantity::one());
585 assert_eq!(offer.signing_pubkey(), pubkey(42));
587 assert_eq!(tlv_stream.chains, None);
588 assert_eq!(tlv_stream.metadata, None);
589 assert_eq!(tlv_stream.currency, None);
590 assert_eq!(tlv_stream.amount, None);
591 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
592 assert_eq!(tlv_stream.features, None);
593 assert_eq!(tlv_stream.absolute_expiry, None);
594 assert_eq!(tlv_stream.paths, None);
595 assert_eq!(tlv_stream.issuer, None);
596 assert_eq!(tlv_stream.quantity_max, None);
597 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
599 if let Err(e) = Offer::try_from(buffer) {
600 panic!("error parsing offer: {:?}", e);
605 fn builds_offer_with_chains() {
606 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
607 let testnet = ChainHash::using_genesis_block(Network::Testnet);
609 let offer = OfferBuilder::new("foo".into(), pubkey(42))
610 .chain(Network::Bitcoin)
613 assert_eq!(offer.chains(), vec![mainnet]);
614 assert_eq!(offer.as_tlv_stream().chains, None);
616 let offer = OfferBuilder::new("foo".into(), pubkey(42))
617 .chain(Network::Testnet)
620 assert_eq!(offer.chains(), vec![testnet]);
621 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
623 let offer = OfferBuilder::new("foo".into(), pubkey(42))
624 .chain(Network::Testnet)
625 .chain(Network::Testnet)
628 assert_eq!(offer.chains(), vec![testnet]);
629 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
631 let offer = OfferBuilder::new("foo".into(), pubkey(42))
632 .chain(Network::Bitcoin)
633 .chain(Network::Testnet)
636 assert_eq!(offer.chains(), vec![mainnet, testnet]);
637 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
641 fn builds_offer_with_metadata() {
642 let offer = OfferBuilder::new("foo".into(), pubkey(42))
643 .metadata(vec![42; 32])
646 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
647 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
649 let offer = OfferBuilder::new("foo".into(), pubkey(42))
650 .metadata(vec![42; 32])
651 .metadata(vec![43; 32])
654 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
655 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
659 fn builds_offer_with_amount() {
660 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
661 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
663 let offer = OfferBuilder::new("foo".into(), pubkey(42))
667 let tlv_stream = offer.as_tlv_stream();
668 assert_eq!(offer.amount(), Some(&bitcoin_amount));
669 assert_eq!(tlv_stream.amount, Some(1000));
670 assert_eq!(tlv_stream.currency, None);
672 let builder = OfferBuilder::new("foo".into(), pubkey(42))
673 .amount(currency_amount.clone());
674 let tlv_stream = builder.offer.as_tlv_stream();
675 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
676 assert_eq!(tlv_stream.amount, Some(10));
677 assert_eq!(tlv_stream.currency, Some(b"USD"));
678 match builder.build() {
679 Ok(_) => panic!("expected error"),
680 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
683 let offer = OfferBuilder::new("foo".into(), pubkey(42))
684 .amount(currency_amount.clone())
685 .amount(bitcoin_amount.clone())
688 let tlv_stream = offer.as_tlv_stream();
689 assert_eq!(tlv_stream.amount, Some(1000));
690 assert_eq!(tlv_stream.currency, None);
692 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
693 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
694 Ok(_) => panic!("expected error"),
695 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
700 fn builds_offer_with_features() {
701 let offer = OfferBuilder::new("foo".into(), pubkey(42))
702 .features(OfferFeatures::unknown())
705 assert_eq!(offer.features(), &OfferFeatures::unknown());
706 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
708 let offer = OfferBuilder::new("foo".into(), pubkey(42))
709 .features(OfferFeatures::unknown())
710 .features(OfferFeatures::empty())
713 assert_eq!(offer.features(), &OfferFeatures::empty());
714 assert_eq!(offer.as_tlv_stream().features, None);
718 fn builds_offer_with_absolute_expiry() {
719 let future_expiry = Duration::from_secs(u64::max_value());
720 let past_expiry = Duration::from_secs(0);
722 let offer = OfferBuilder::new("foo".into(), pubkey(42))
723 .absolute_expiry(future_expiry)
726 #[cfg(feature = "std")]
727 assert!(!offer.is_expired());
728 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
729 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
731 let offer = OfferBuilder::new("foo".into(), pubkey(42))
732 .absolute_expiry(future_expiry)
733 .absolute_expiry(past_expiry)
736 #[cfg(feature = "std")]
737 assert!(offer.is_expired());
738 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
739 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
743 fn builds_offer_with_paths() {
746 introduction_node_id: pubkey(40),
747 blinding_point: pubkey(41),
749 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
750 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
754 introduction_node_id: pubkey(40),
755 blinding_point: pubkey(41),
757 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
758 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
763 let offer = OfferBuilder::new("foo".into(), pubkey(42))
764 .path(paths[0].clone())
765 .path(paths[1].clone())
768 let tlv_stream = offer.as_tlv_stream();
769 assert_eq!(offer.paths(), paths.as_slice());
770 assert_eq!(offer.signing_pubkey(), pubkey(42));
771 assert_ne!(pubkey(42), pubkey(44));
772 assert_eq!(tlv_stream.paths, Some(&paths));
773 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
777 fn builds_offer_with_issuer() {
778 let offer = OfferBuilder::new("foo".into(), pubkey(42))
779 .issuer("bar".into())
782 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
783 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
785 let offer = OfferBuilder::new("foo".into(), pubkey(42))
786 .issuer("bar".into())
787 .issuer("baz".into())
790 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
791 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
795 fn builds_offer_with_supported_quantity() {
796 let ten = NonZeroU64::new(10).unwrap();
798 let offer = OfferBuilder::new("foo".into(), pubkey(42))
799 .supported_quantity(Quantity::one())
802 let tlv_stream = offer.as_tlv_stream();
803 assert_eq!(offer.supported_quantity(), Quantity::one());
804 assert_eq!(tlv_stream.quantity_max, None);
806 let offer = OfferBuilder::new("foo".into(), pubkey(42))
807 .supported_quantity(Quantity::Unbounded)
810 let tlv_stream = offer.as_tlv_stream();
811 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
812 assert_eq!(tlv_stream.quantity_max, Some(0));
814 let offer = OfferBuilder::new("foo".into(), pubkey(42))
815 .supported_quantity(Quantity::Bounded(ten))
818 let tlv_stream = offer.as_tlv_stream();
819 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
820 assert_eq!(tlv_stream.quantity_max, Some(10));
822 let offer = OfferBuilder::new("foo".into(), pubkey(42))
823 .supported_quantity(Quantity::Bounded(ten))
824 .supported_quantity(Quantity::one())
827 let tlv_stream = offer.as_tlv_stream();
828 assert_eq!(offer.supported_quantity(), Quantity::one());
829 assert_eq!(tlv_stream.quantity_max, None);
833 fn parses_offer_with_chains() {
834 let offer = OfferBuilder::new("foo".into(), pubkey(42))
835 .chain(Network::Bitcoin)
836 .chain(Network::Testnet)
839 if let Err(e) = offer.to_string().parse::<Offer>() {
840 panic!("error parsing offer: {:?}", e);
845 fn parses_offer_with_amount() {
846 let offer = OfferBuilder::new("foo".into(), pubkey(42))
847 .amount(Amount::Bitcoin { amount_msats: 1000 })
850 if let Err(e) = offer.to_string().parse::<Offer>() {
851 panic!("error parsing offer: {:?}", e);
854 let mut tlv_stream = offer.as_tlv_stream();
855 tlv_stream.amount = Some(1000);
856 tlv_stream.currency = Some(b"USD");
858 let mut encoded_offer = Vec::new();
859 tlv_stream.write(&mut encoded_offer).unwrap();
861 if let Err(e) = Offer::try_from(encoded_offer) {
862 panic!("error parsing offer: {:?}", e);
865 let mut tlv_stream = offer.as_tlv_stream();
866 tlv_stream.amount = None;
867 tlv_stream.currency = Some(b"USD");
869 let mut encoded_offer = Vec::new();
870 tlv_stream.write(&mut encoded_offer).unwrap();
872 match Offer::try_from(encoded_offer) {
873 Ok(_) => panic!("expected error"),
874 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
877 let mut tlv_stream = offer.as_tlv_stream();
878 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
879 tlv_stream.currency = None;
881 let mut encoded_offer = Vec::new();
882 tlv_stream.write(&mut encoded_offer).unwrap();
884 match Offer::try_from(encoded_offer) {
885 Ok(_) => panic!("expected error"),
886 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
891 fn parses_offer_with_description() {
892 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
893 if let Err(e) = offer.to_string().parse::<Offer>() {
894 panic!("error parsing offer: {:?}", e);
897 let mut tlv_stream = offer.as_tlv_stream();
898 tlv_stream.description = None;
900 let mut encoded_offer = Vec::new();
901 tlv_stream.write(&mut encoded_offer).unwrap();
903 match Offer::try_from(encoded_offer) {
904 Ok(_) => panic!("expected error"),
906 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
912 fn parses_offer_with_paths() {
913 let offer = OfferBuilder::new("foo".into(), pubkey(42))
915 introduction_node_id: pubkey(40),
916 blinding_point: pubkey(41),
918 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
919 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
923 introduction_node_id: pubkey(40),
924 blinding_point: pubkey(41),
926 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
927 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
932 if let Err(e) = offer.to_string().parse::<Offer>() {
933 panic!("error parsing offer: {:?}", e);
936 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
937 builder.offer.paths = Some(vec![]);
939 let offer = builder.build().unwrap();
940 if let Err(e) = offer.to_string().parse::<Offer>() {
941 panic!("error parsing offer: {:?}", e);
946 fn parses_offer_with_quantity() {
947 let offer = OfferBuilder::new("foo".into(), pubkey(42))
948 .supported_quantity(Quantity::one())
951 if let Err(e) = offer.to_string().parse::<Offer>() {
952 panic!("error parsing offer: {:?}", e);
955 let offer = OfferBuilder::new("foo".into(), pubkey(42))
956 .supported_quantity(Quantity::Unbounded)
959 if let Err(e) = offer.to_string().parse::<Offer>() {
960 panic!("error parsing offer: {:?}", e);
963 let offer = OfferBuilder::new("foo".into(), pubkey(42))
964 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
967 if let Err(e) = offer.to_string().parse::<Offer>() {
968 panic!("error parsing offer: {:?}", e);
971 let mut tlv_stream = offer.as_tlv_stream();
972 tlv_stream.quantity_max = Some(1);
974 let mut encoded_offer = Vec::new();
975 tlv_stream.write(&mut encoded_offer).unwrap();
977 match Offer::try_from(encoded_offer) {
978 Ok(_) => panic!("expected error"),
980 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
986 fn parses_offer_with_node_id() {
987 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
988 if let Err(e) = offer.to_string().parse::<Offer>() {
989 panic!("error parsing offer: {:?}", e);
992 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
993 builder.offer.signing_pubkey = None;
995 let offer = builder.build().unwrap();
996 match offer.to_string().parse::<Offer>() {
997 Ok(_) => panic!("expected error"),
999 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1005 fn fails_parsing_offer_with_extra_tlv_records() {
1006 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1008 let mut encoded_offer = Vec::new();
1009 offer.write(&mut encoded_offer).unwrap();
1010 BigSize(80).write(&mut encoded_offer).unwrap();
1011 BigSize(32).write(&mut encoded_offer).unwrap();
1012 [42u8; 32].write(&mut encoded_offer).unwrap();
1014 match Offer::try_from(encoded_offer) {
1015 Ok(_) => panic!("expected error"),
1016 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1023 use super::{Offer, ParseError};
1024 use bitcoin::bech32;
1025 use crate::ln::msgs::DecodeError;
1027 // TODO: Remove once test vectors are updated.
1030 fn encodes_offer_as_bech32_without_checksum() {
1031 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1032 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1033 let reencoded_offer = offer.to_string();
1034 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1035 assert_eq!(reencoded_offer, encoded_offer);
1038 // TODO: Remove once test vectors are updated.
1041 fn parses_bech32_encoded_offers() {
1043 // BOLT 12 test vectors
1044 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1045 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1046 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1047 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1048 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1049 // Two blinded paths
1050 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1052 for encoded_offer in &offers {
1053 if let Err(e) = encoded_offer.parse::<Offer>() {
1054 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1060 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1062 // BOLT 12 test vectors
1063 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1064 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1065 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1066 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1067 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1069 for encoded_offer in &offers {
1070 match encoded_offer.parse::<Offer>() {
1071 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1072 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1079 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1080 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1081 match encoded_offer.parse::<Offer>() {
1082 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1083 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1088 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1089 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1090 match encoded_offer.parse::<Offer>() {
1091 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1092 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1097 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1098 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1099 match encoded_offer.parse::<Offer>() {
1100 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1101 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),