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 /// Returns whether the given chain is supported by the offer.
274 pub fn supports_chain(&self, chain: ChainHash) -> bool {
275 self.contents.supports_chain(chain)
278 // TODO: Link to corresponding method in `InvoiceRequest`.
279 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
280 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
281 pub fn metadata(&self) -> Option<&Vec<u8>> {
282 self.contents.metadata.as_ref()
285 /// The minimum amount required for a successful payment of a single item.
286 pub fn amount(&self) -> Option<&Amount> {
287 self.contents.amount()
290 /// A complete description of the purpose of the payment. Intended to be displayed to the user
291 /// but with the caveat that it has not been verified in any way.
292 pub fn description(&self) -> PrintableString {
293 PrintableString(&self.contents.description)
296 /// Features pertaining to the offer.
297 pub fn features(&self) -> &OfferFeatures {
298 &self.contents.features
301 /// Duration since the Unix epoch when an invoice should no longer be requested.
303 /// If `None`, the offer does not expire.
304 pub fn absolute_expiry(&self) -> Option<Duration> {
305 self.contents.absolute_expiry
308 /// Whether the offer has expired.
309 #[cfg(feature = "std")]
310 pub fn is_expired(&self) -> bool {
311 match self.absolute_expiry() {
312 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
313 Ok(elapsed) => elapsed > seconds_from_epoch,
320 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
321 /// displayed to the user but with the caveat that it has not been verified in any way.
322 pub fn issuer(&self) -> Option<PrintableString> {
323 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
326 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
327 /// recipient privacy by obfuscating its node id.
328 pub fn paths(&self) -> &[BlindedPath] {
329 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
332 /// The quantity of items supported.
333 pub fn supported_quantity(&self) -> Quantity {
334 self.contents.supported_quantity()
337 /// Returns whether the given quantity is valid for the offer.
338 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
339 self.contents.is_valid_quantity(quantity)
342 /// Returns whether a quantity is expected in an [`InvoiceRequest`] for the offer.
344 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
345 pub fn expects_quantity(&self) -> bool {
346 self.contents.expects_quantity()
349 /// The public key used by the recipient to sign invoices.
350 pub fn signing_pubkey(&self) -> PublicKey {
351 self.contents.signing_pubkey.unwrap()
355 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
356 self.contents.as_tlv_stream()
360 impl AsRef<[u8]> for Offer {
361 fn as_ref(&self) -> &[u8] {
367 pub fn chains(&self) -> Vec<ChainHash> {
368 self.chains.as_ref().cloned().unwrap_or_else(|| vec![self.implied_chain()])
371 pub fn implied_chain(&self) -> ChainHash {
372 ChainHash::using_genesis_block(Network::Bitcoin)
375 pub fn supports_chain(&self, chain: ChainHash) -> bool {
376 self.chains().contains(&chain)
379 pub fn amount(&self) -> Option<&Amount> {
383 pub fn amount_msats(&self) -> u64 {
384 match self.amount() {
386 Some(&Amount::Bitcoin { amount_msats }) => amount_msats,
387 Some(&Amount::Currency { .. }) => unreachable!(),
391 pub fn expected_invoice_amount_msats(&self, quantity: u64) -> u64 {
392 self.amount_msats() * quantity
395 pub fn supported_quantity(&self) -> Quantity {
396 self.supported_quantity
399 pub fn is_valid_quantity(&self, quantity: u64) -> bool {
400 match self.supported_quantity {
401 Quantity::Bounded(n) => {
404 else { quantity > 0 && quantity <= n }
406 Quantity::Unbounded => quantity > 0,
410 pub fn expects_quantity(&self) -> bool {
411 match self.supported_quantity {
412 Quantity::Bounded(n) => n.get() != 1,
413 Quantity::Unbounded => true,
417 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
418 let (currency, amount) = match &self.amount {
419 None => (None, None),
420 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
421 Some(Amount::Currency { iso4217_code, amount }) => (
422 Some(iso4217_code), Some(*amount)
427 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
431 chains: self.chains.as_ref(),
432 metadata: self.metadata.as_ref(),
435 description: Some(&self.description),
437 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
438 paths: self.paths.as_ref(),
439 issuer: self.issuer.as_ref(),
440 quantity_max: self.supported_quantity.to_tlv_record(),
441 node_id: self.signing_pubkey.as_ref(),
446 impl Writeable for Offer {
447 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
448 WithoutLength(&self.bytes).write(writer)
452 impl Writeable for OfferContents {
453 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
454 self.as_tlv_stream().write(writer)
458 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
459 /// another currency.
460 #[derive(Clone, Debug, PartialEq)]
462 /// An amount of bitcoin.
464 /// The amount in millisatoshi.
467 /// An amount of currency specified using ISO 4712.
469 /// The currency that the amount is denominated in.
470 iso4217_code: CurrencyCode,
471 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
476 /// An ISO 4712 three-letter currency code (e.g., USD).
477 pub type CurrencyCode = [u8; 3];
479 /// Quantity of items supported by an [`Offer`].
480 #[derive(Clone, Copy, Debug, PartialEq)]
482 /// Up to a specific number of items (inclusive).
484 /// One or more items.
489 /// The default quantity of one.
490 pub fn one() -> Self {
491 Quantity::Bounded(NonZeroU64::new(1).unwrap())
494 fn to_tlv_record(&self) -> Option<u64> {
496 Quantity::Bounded(n) => {
498 if n == 1 { None } else { Some(n) }
500 Quantity::Unbounded => Some(0),
505 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
506 (2, chains: (Vec<ChainHash>, WithoutLength)),
507 (4, metadata: (Vec<u8>, WithoutLength)),
508 (6, currency: CurrencyCode),
509 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
510 (10, description: (String, WithoutLength)),
511 (12, features: OfferFeatures),
512 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
513 (16, paths: (Vec<BlindedPath>, WithoutLength)),
514 (18, issuer: (String, WithoutLength)),
515 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
516 (22, node_id: PublicKey),
519 impl Bech32Encode for Offer {
520 const BECH32_HRP: &'static str = "lno";
523 impl FromStr for Offer {
524 type Err = ParseError;
526 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
527 Self::from_bech32_str(s)
531 impl TryFrom<Vec<u8>> for Offer {
532 type Error = ParseError;
534 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
535 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
536 let ParsedMessage { bytes, tlv_stream } = offer;
537 let contents = OfferContents::try_from(tlv_stream)?;
538 Ok(Offer { bytes, contents })
542 impl TryFrom<OfferTlvStream> for OfferContents {
543 type Error = SemanticError;
545 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
547 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
548 issuer, quantity_max, node_id,
551 let amount = match (currency, amount) {
552 (None, None) => None,
553 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
554 return Err(SemanticError::InvalidAmount);
556 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
557 (Some(_), None) => return Err(SemanticError::MissingAmount),
558 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
561 let description = match description {
562 None => return Err(SemanticError::MissingDescription),
563 Some(description) => description,
566 let features = features.unwrap_or_else(OfferFeatures::empty);
568 let absolute_expiry = absolute_expiry
569 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
571 let supported_quantity = match quantity_max {
572 None => Quantity::one(),
573 Some(0) => Quantity::Unbounded,
574 Some(1) => return Err(SemanticError::InvalidQuantity),
575 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
578 if node_id.is_none() {
579 return Err(SemanticError::MissingSigningPubkey);
583 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
584 supported_quantity, signing_pubkey: node_id,
589 impl core::fmt::Display for Offer {
590 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
591 self.fmt_bech32_str(f)
597 use super::{Amount, Offer, OfferBuilder, Quantity};
599 use bitcoin::blockdata::constants::ChainHash;
600 use bitcoin::network::constants::Network;
601 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
602 use core::convert::TryFrom;
603 use core::num::NonZeroU64;
604 use core::time::Duration;
605 use crate::ln::features::OfferFeatures;
606 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
607 use crate::offers::parse::{ParseError, SemanticError};
608 use crate::onion_message::{BlindedHop, BlindedPath};
609 use crate::util::ser::{BigSize, Writeable};
610 use crate::util::string::PrintableString;
612 fn pubkey(byte: u8) -> PublicKey {
613 let secp_ctx = Secp256k1::new();
614 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
617 fn privkey(byte: u8) -> SecretKey {
618 SecretKey::from_slice(&[byte; 32]).unwrap()
622 fn builds_offer_with_defaults() {
623 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
624 let tlv_stream = offer.as_tlv_stream();
625 let mut buffer = Vec::new();
626 offer.write(&mut buffer).unwrap();
628 assert_eq!(offer.bytes, buffer.as_slice());
629 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
630 assert!(offer.supports_chain(ChainHash::using_genesis_block(Network::Bitcoin)));
631 assert_eq!(offer.metadata(), None);
632 assert_eq!(offer.amount(), None);
633 assert_eq!(offer.description(), PrintableString("foo"));
634 assert_eq!(offer.features(), &OfferFeatures::empty());
635 assert_eq!(offer.absolute_expiry(), None);
636 #[cfg(feature = "std")]
637 assert!(!offer.is_expired());
638 assert_eq!(offer.paths(), &[]);
639 assert_eq!(offer.issuer(), None);
640 assert_eq!(offer.supported_quantity(), Quantity::one());
641 assert_eq!(offer.signing_pubkey(), pubkey(42));
643 assert_eq!(tlv_stream.chains, None);
644 assert_eq!(tlv_stream.metadata, None);
645 assert_eq!(tlv_stream.currency, None);
646 assert_eq!(tlv_stream.amount, None);
647 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
648 assert_eq!(tlv_stream.features, None);
649 assert_eq!(tlv_stream.absolute_expiry, None);
650 assert_eq!(tlv_stream.paths, None);
651 assert_eq!(tlv_stream.issuer, None);
652 assert_eq!(tlv_stream.quantity_max, None);
653 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
655 if let Err(e) = Offer::try_from(buffer) {
656 panic!("error parsing offer: {:?}", e);
661 fn builds_offer_with_chains() {
662 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
663 let testnet = ChainHash::using_genesis_block(Network::Testnet);
665 let offer = OfferBuilder::new("foo".into(), pubkey(42))
666 .chain(Network::Bitcoin)
669 assert!(offer.supports_chain(mainnet));
670 assert_eq!(offer.chains(), vec![mainnet]);
671 assert_eq!(offer.as_tlv_stream().chains, None);
673 let offer = OfferBuilder::new("foo".into(), pubkey(42))
674 .chain(Network::Testnet)
677 assert!(offer.supports_chain(testnet));
678 assert_eq!(offer.chains(), vec![testnet]);
679 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
681 let offer = OfferBuilder::new("foo".into(), pubkey(42))
682 .chain(Network::Testnet)
683 .chain(Network::Testnet)
686 assert!(offer.supports_chain(testnet));
687 assert_eq!(offer.chains(), vec![testnet]);
688 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
690 let offer = OfferBuilder::new("foo".into(), pubkey(42))
691 .chain(Network::Bitcoin)
692 .chain(Network::Testnet)
695 assert!(offer.supports_chain(mainnet));
696 assert!(offer.supports_chain(testnet));
697 assert_eq!(offer.chains(), vec![mainnet, testnet]);
698 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
702 fn builds_offer_with_metadata() {
703 let offer = OfferBuilder::new("foo".into(), pubkey(42))
704 .metadata(vec![42; 32])
707 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
708 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
710 let offer = OfferBuilder::new("foo".into(), pubkey(42))
711 .metadata(vec![42; 32])
712 .metadata(vec![43; 32])
715 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
716 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
720 fn builds_offer_with_amount() {
721 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
722 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
724 let offer = OfferBuilder::new("foo".into(), pubkey(42))
728 let tlv_stream = offer.as_tlv_stream();
729 assert_eq!(offer.amount(), Some(&bitcoin_amount));
730 assert_eq!(tlv_stream.amount, Some(1000));
731 assert_eq!(tlv_stream.currency, None);
733 let builder = OfferBuilder::new("foo".into(), pubkey(42))
734 .amount(currency_amount.clone());
735 let tlv_stream = builder.offer.as_tlv_stream();
736 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
737 assert_eq!(tlv_stream.amount, Some(10));
738 assert_eq!(tlv_stream.currency, Some(b"USD"));
739 match builder.build() {
740 Ok(_) => panic!("expected error"),
741 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
744 let offer = OfferBuilder::new("foo".into(), pubkey(42))
745 .amount(currency_amount.clone())
746 .amount(bitcoin_amount.clone())
749 let tlv_stream = offer.as_tlv_stream();
750 assert_eq!(tlv_stream.amount, Some(1000));
751 assert_eq!(tlv_stream.currency, None);
753 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
754 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
755 Ok(_) => panic!("expected error"),
756 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
761 fn builds_offer_with_features() {
762 let offer = OfferBuilder::new("foo".into(), pubkey(42))
763 .features(OfferFeatures::unknown())
766 assert_eq!(offer.features(), &OfferFeatures::unknown());
767 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
769 let offer = OfferBuilder::new("foo".into(), pubkey(42))
770 .features(OfferFeatures::unknown())
771 .features(OfferFeatures::empty())
774 assert_eq!(offer.features(), &OfferFeatures::empty());
775 assert_eq!(offer.as_tlv_stream().features, None);
779 fn builds_offer_with_absolute_expiry() {
780 let future_expiry = Duration::from_secs(u64::max_value());
781 let past_expiry = Duration::from_secs(0);
783 let offer = OfferBuilder::new("foo".into(), pubkey(42))
784 .absolute_expiry(future_expiry)
787 #[cfg(feature = "std")]
788 assert!(!offer.is_expired());
789 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
790 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
792 let offer = OfferBuilder::new("foo".into(), pubkey(42))
793 .absolute_expiry(future_expiry)
794 .absolute_expiry(past_expiry)
797 #[cfg(feature = "std")]
798 assert!(offer.is_expired());
799 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
800 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
804 fn builds_offer_with_paths() {
807 introduction_node_id: pubkey(40),
808 blinding_point: pubkey(41),
810 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
811 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
815 introduction_node_id: pubkey(40),
816 blinding_point: pubkey(41),
818 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
819 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
824 let offer = OfferBuilder::new("foo".into(), pubkey(42))
825 .path(paths[0].clone())
826 .path(paths[1].clone())
829 let tlv_stream = offer.as_tlv_stream();
830 assert_eq!(offer.paths(), paths.as_slice());
831 assert_eq!(offer.signing_pubkey(), pubkey(42));
832 assert_ne!(pubkey(42), pubkey(44));
833 assert_eq!(tlv_stream.paths, Some(&paths));
834 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
838 fn builds_offer_with_issuer() {
839 let offer = OfferBuilder::new("foo".into(), pubkey(42))
840 .issuer("bar".into())
843 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
844 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
846 let offer = OfferBuilder::new("foo".into(), pubkey(42))
847 .issuer("bar".into())
848 .issuer("baz".into())
851 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
852 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
856 fn builds_offer_with_supported_quantity() {
857 let ten = NonZeroU64::new(10).unwrap();
859 let offer = OfferBuilder::new("foo".into(), pubkey(42))
860 .supported_quantity(Quantity::one())
863 let tlv_stream = offer.as_tlv_stream();
864 assert_eq!(offer.supported_quantity(), Quantity::one());
865 assert_eq!(tlv_stream.quantity_max, None);
867 let offer = OfferBuilder::new("foo".into(), pubkey(42))
868 .supported_quantity(Quantity::Unbounded)
871 let tlv_stream = offer.as_tlv_stream();
872 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
873 assert_eq!(tlv_stream.quantity_max, Some(0));
875 let offer = OfferBuilder::new("foo".into(), pubkey(42))
876 .supported_quantity(Quantity::Bounded(ten))
879 let tlv_stream = offer.as_tlv_stream();
880 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
881 assert_eq!(tlv_stream.quantity_max, Some(10));
883 let offer = OfferBuilder::new("foo".into(), pubkey(42))
884 .supported_quantity(Quantity::Bounded(ten))
885 .supported_quantity(Quantity::one())
888 let tlv_stream = offer.as_tlv_stream();
889 assert_eq!(offer.supported_quantity(), Quantity::one());
890 assert_eq!(tlv_stream.quantity_max, None);
894 fn parses_offer_with_chains() {
895 let offer = OfferBuilder::new("foo".into(), pubkey(42))
896 .chain(Network::Bitcoin)
897 .chain(Network::Testnet)
900 if let Err(e) = offer.to_string().parse::<Offer>() {
901 panic!("error parsing offer: {:?}", e);
906 fn parses_offer_with_amount() {
907 let offer = OfferBuilder::new("foo".into(), pubkey(42))
908 .amount(Amount::Bitcoin { amount_msats: 1000 })
911 if let Err(e) = offer.to_string().parse::<Offer>() {
912 panic!("error parsing offer: {:?}", e);
915 let mut tlv_stream = offer.as_tlv_stream();
916 tlv_stream.amount = Some(1000);
917 tlv_stream.currency = Some(b"USD");
919 let mut encoded_offer = Vec::new();
920 tlv_stream.write(&mut encoded_offer).unwrap();
922 if let Err(e) = Offer::try_from(encoded_offer) {
923 panic!("error parsing offer: {:?}", e);
926 let mut tlv_stream = offer.as_tlv_stream();
927 tlv_stream.amount = None;
928 tlv_stream.currency = Some(b"USD");
930 let mut encoded_offer = Vec::new();
931 tlv_stream.write(&mut encoded_offer).unwrap();
933 match Offer::try_from(encoded_offer) {
934 Ok(_) => panic!("expected error"),
935 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
938 let mut tlv_stream = offer.as_tlv_stream();
939 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
940 tlv_stream.currency = None;
942 let mut encoded_offer = Vec::new();
943 tlv_stream.write(&mut encoded_offer).unwrap();
945 match Offer::try_from(encoded_offer) {
946 Ok(_) => panic!("expected error"),
947 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
952 fn parses_offer_with_description() {
953 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
954 if let Err(e) = offer.to_string().parse::<Offer>() {
955 panic!("error parsing offer: {:?}", e);
958 let mut tlv_stream = offer.as_tlv_stream();
959 tlv_stream.description = None;
961 let mut encoded_offer = Vec::new();
962 tlv_stream.write(&mut encoded_offer).unwrap();
964 match Offer::try_from(encoded_offer) {
965 Ok(_) => panic!("expected error"),
967 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
973 fn parses_offer_with_paths() {
974 let offer = OfferBuilder::new("foo".into(), pubkey(42))
976 introduction_node_id: pubkey(40),
977 blinding_point: pubkey(41),
979 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
980 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
984 introduction_node_id: pubkey(40),
985 blinding_point: pubkey(41),
987 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
988 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
993 if let Err(e) = offer.to_string().parse::<Offer>() {
994 panic!("error parsing offer: {:?}", e);
997 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
998 builder.offer.paths = Some(vec![]);
1000 let offer = builder.build().unwrap();
1001 if let Err(e) = offer.to_string().parse::<Offer>() {
1002 panic!("error parsing offer: {:?}", e);
1007 fn parses_offer_with_quantity() {
1008 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1009 .supported_quantity(Quantity::one())
1012 if let Err(e) = offer.to_string().parse::<Offer>() {
1013 panic!("error parsing offer: {:?}", e);
1016 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1017 .supported_quantity(Quantity::Unbounded)
1020 if let Err(e) = offer.to_string().parse::<Offer>() {
1021 panic!("error parsing offer: {:?}", e);
1024 let offer = OfferBuilder::new("foo".into(), pubkey(42))
1025 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
1028 if let Err(e) = offer.to_string().parse::<Offer>() {
1029 panic!("error parsing offer: {:?}", e);
1032 let mut tlv_stream = offer.as_tlv_stream();
1033 tlv_stream.quantity_max = Some(1);
1035 let mut encoded_offer = Vec::new();
1036 tlv_stream.write(&mut encoded_offer).unwrap();
1038 match Offer::try_from(encoded_offer) {
1039 Ok(_) => panic!("expected error"),
1041 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
1047 fn parses_offer_with_node_id() {
1048 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1049 if let Err(e) = offer.to_string().parse::<Offer>() {
1050 panic!("error parsing offer: {:?}", e);
1053 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
1054 builder.offer.signing_pubkey = None;
1056 let offer = builder.build().unwrap();
1057 match offer.to_string().parse::<Offer>() {
1058 Ok(_) => panic!("expected error"),
1060 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1066 fn fails_parsing_offer_with_extra_tlv_records() {
1067 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1069 let mut encoded_offer = Vec::new();
1070 offer.write(&mut encoded_offer).unwrap();
1071 BigSize(80).write(&mut encoded_offer).unwrap();
1072 BigSize(32).write(&mut encoded_offer).unwrap();
1073 [42u8; 32].write(&mut encoded_offer).unwrap();
1075 match Offer::try_from(encoded_offer) {
1076 Ok(_) => panic!("expected error"),
1077 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1084 use super::{Offer, ParseError};
1085 use bitcoin::bech32;
1086 use crate::ln::msgs::DecodeError;
1088 // TODO: Remove once test vectors are updated.
1091 fn encodes_offer_as_bech32_without_checksum() {
1092 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1093 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1094 let reencoded_offer = offer.to_string();
1095 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1096 assert_eq!(reencoded_offer, encoded_offer);
1099 // TODO: Remove once test vectors are updated.
1102 fn parses_bech32_encoded_offers() {
1104 // BOLT 12 test vectors
1105 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1106 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1107 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1108 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1109 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1110 // Two blinded paths
1111 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1113 for encoded_offer in &offers {
1114 if let Err(e) = encoded_offer.parse::<Offer>() {
1115 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1121 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1123 // BOLT 12 test vectors
1124 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1125 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1126 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1127 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1128 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1130 for encoded_offer in &offers {
1131 match encoded_offer.parse::<Offer>() {
1132 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1133 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1140 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1141 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1142 match encoded_offer.parse::<Offer>() {
1143 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1144 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1149 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1150 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1151 match encoded_offer.parse::<Offer>() {
1152 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1153 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1158 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1159 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1160 match encoded_offer.parse::<Offer>() {
1161 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1162 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),