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`]. 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.
235 #[derive(Clone, Debug)]
237 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
240 contents: OfferContents,
243 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
244 #[derive(Clone, Debug)]
245 pub(crate) struct OfferContents {
246 chains: Option<Vec<ChainHash>>,
247 metadata: Option<Vec<u8>>,
248 amount: Option<Amount>,
250 features: OfferFeatures,
251 absolute_expiry: Option<Duration>,
252 issuer: Option<String>,
253 paths: Option<Vec<BlindedPath>>,
254 supported_quantity: Quantity,
255 signing_pubkey: Option<PublicKey>,
259 // TODO: Return a slice once ChainHash has constants.
260 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
261 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
262 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
263 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
264 /// for the selected chain.
265 pub fn chains(&self) -> Vec<ChainHash> {
269 .unwrap_or_else(|| vec![self.contents.implied_chain()])
272 // TODO: Link to corresponding method in `InvoiceRequest`.
273 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
274 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
275 pub fn metadata(&self) -> Option<&Vec<u8>> {
276 self.contents.metadata.as_ref()
279 /// The minimum amount required for a successful payment of a single item.
280 pub fn amount(&self) -> Option<&Amount> {
281 self.contents.amount.as_ref()
284 /// A complete description of the purpose of the payment. Intended to be displayed to the user
285 /// but with the caveat that it has not been verified in any way.
286 pub fn description(&self) -> PrintableString {
287 PrintableString(&self.contents.description)
290 /// Features pertaining to the offer.
291 pub fn features(&self) -> &OfferFeatures {
292 &self.contents.features
295 /// Duration since the Unix epoch when an invoice should no longer be requested.
297 /// If `None`, the offer does not expire.
298 pub fn absolute_expiry(&self) -> Option<Duration> {
299 self.contents.absolute_expiry
302 /// Whether the offer has expired.
303 #[cfg(feature = "std")]
304 pub fn is_expired(&self) -> bool {
305 match self.absolute_expiry() {
306 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
307 Ok(elapsed) => elapsed > seconds_from_epoch,
314 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
315 /// displayed to the user but with the caveat that it has not been verified in any way.
316 pub fn issuer(&self) -> Option<PrintableString> {
317 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
320 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
321 /// recipient privacy by obfuscating its node id.
322 pub fn paths(&self) -> &[BlindedPath] {
323 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
326 /// The quantity of items supported.
327 pub fn supported_quantity(&self) -> Quantity {
328 self.contents.supported_quantity()
331 /// The public key used by the recipient to sign invoices.
332 pub fn signing_pubkey(&self) -> PublicKey {
333 self.contents.signing_pubkey.unwrap()
337 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
338 self.contents.as_tlv_stream()
342 impl AsRef<[u8]> for Offer {
343 fn as_ref(&self) -> &[u8] {
349 pub fn implied_chain(&self) -> ChainHash {
350 ChainHash::using_genesis_block(Network::Bitcoin)
353 pub fn supported_quantity(&self) -> Quantity {
354 self.supported_quantity
357 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
358 let (currency, amount) = match &self.amount {
359 None => (None, None),
360 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
361 Some(Amount::Currency { iso4217_code, amount }) => (
362 Some(iso4217_code), Some(*amount)
367 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
371 chains: self.chains.as_ref(),
372 metadata: self.metadata.as_ref(),
375 description: Some(&self.description),
377 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
378 paths: self.paths.as_ref(),
379 issuer: self.issuer.as_ref(),
380 quantity_max: self.supported_quantity.to_tlv_record(),
381 node_id: self.signing_pubkey.as_ref(),
386 impl Writeable for Offer {
387 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
388 WithoutLength(&self.bytes).write(writer)
392 impl Writeable for OfferContents {
393 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
394 self.as_tlv_stream().write(writer)
398 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
399 /// another currency.
400 #[derive(Clone, Debug, PartialEq)]
402 /// An amount of bitcoin.
404 /// The amount in millisatoshi.
407 /// An amount of currency specified using ISO 4712.
409 /// The currency that the amount is denominated in.
410 iso4217_code: CurrencyCode,
411 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
416 /// An ISO 4712 three-letter currency code (e.g., USD).
417 pub type CurrencyCode = [u8; 3];
419 /// Quantity of items supported by an [`Offer`].
420 #[derive(Clone, Copy, Debug, PartialEq)]
422 /// Up to a specific number of items (inclusive).
424 /// One or more items.
429 /// The default quantity of one.
430 pub fn one() -> Self {
431 Quantity::Bounded(NonZeroU64::new(1).unwrap())
434 fn to_tlv_record(&self) -> Option<u64> {
436 Quantity::Bounded(n) => {
438 if n == 1 { None } else { Some(n) }
440 Quantity::Unbounded => Some(0),
445 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, 1..80, {
446 (2, chains: (Vec<ChainHash>, WithoutLength)),
447 (4, metadata: (Vec<u8>, WithoutLength)),
448 (6, currency: CurrencyCode),
449 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
450 (10, description: (String, WithoutLength)),
451 (12, features: OfferFeatures),
452 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
453 (16, paths: (Vec<BlindedPath>, WithoutLength)),
454 (18, issuer: (String, WithoutLength)),
455 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
456 (22, node_id: PublicKey),
459 impl Bech32Encode for Offer {
460 const BECH32_HRP: &'static str = "lno";
463 impl FromStr for Offer {
464 type Err = ParseError;
466 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
467 Self::from_bech32_str(s)
471 impl TryFrom<Vec<u8>> for Offer {
472 type Error = ParseError;
474 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
475 let offer = ParsedMessage::<OfferTlvStream>::try_from(bytes)?;
476 let ParsedMessage { bytes, tlv_stream } = offer;
477 let contents = OfferContents::try_from(tlv_stream)?;
478 Ok(Offer { bytes, contents })
482 impl TryFrom<OfferTlvStream> for OfferContents {
483 type Error = SemanticError;
485 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
487 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
488 issuer, quantity_max, node_id,
491 let amount = match (currency, amount) {
492 (None, None) => None,
493 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
494 return Err(SemanticError::InvalidAmount);
496 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
497 (Some(_), None) => return Err(SemanticError::MissingAmount),
498 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
501 let description = match description {
502 None => return Err(SemanticError::MissingDescription),
503 Some(description) => description,
506 let features = features.unwrap_or_else(OfferFeatures::empty);
508 let absolute_expiry = absolute_expiry
509 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
511 let supported_quantity = match quantity_max {
512 None => Quantity::one(),
513 Some(0) => Quantity::Unbounded,
514 Some(1) => return Err(SemanticError::InvalidQuantity),
515 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
518 if node_id.is_none() {
519 return Err(SemanticError::MissingSigningPubkey);
523 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
524 supported_quantity, signing_pubkey: node_id,
529 impl core::fmt::Display for Offer {
530 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
531 self.fmt_bech32_str(f)
537 use super::{Amount, Offer, OfferBuilder, Quantity};
539 use bitcoin::blockdata::constants::ChainHash;
540 use bitcoin::network::constants::Network;
541 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
542 use core::convert::TryFrom;
543 use core::num::NonZeroU64;
544 use core::time::Duration;
545 use crate::ln::features::OfferFeatures;
546 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
547 use crate::offers::parse::{ParseError, SemanticError};
548 use crate::onion_message::{BlindedHop, BlindedPath};
549 use crate::util::ser::{BigSize, Writeable};
550 use crate::util::string::PrintableString;
552 fn pubkey(byte: u8) -> PublicKey {
553 let secp_ctx = Secp256k1::new();
554 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
557 fn privkey(byte: u8) -> SecretKey {
558 SecretKey::from_slice(&[byte; 32]).unwrap()
562 fn builds_offer_with_defaults() {
563 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
564 let tlv_stream = offer.as_tlv_stream();
565 let mut buffer = Vec::new();
566 offer.write(&mut buffer).unwrap();
568 assert_eq!(offer.bytes, buffer.as_slice());
569 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
570 assert_eq!(offer.metadata(), None);
571 assert_eq!(offer.amount(), None);
572 assert_eq!(offer.description(), PrintableString("foo"));
573 assert_eq!(offer.features(), &OfferFeatures::empty());
574 assert_eq!(offer.absolute_expiry(), None);
575 #[cfg(feature = "std")]
576 assert!(!offer.is_expired());
577 assert_eq!(offer.paths(), &[]);
578 assert_eq!(offer.issuer(), None);
579 assert_eq!(offer.supported_quantity(), Quantity::one());
580 assert_eq!(offer.signing_pubkey(), pubkey(42));
582 assert_eq!(tlv_stream.chains, None);
583 assert_eq!(tlv_stream.metadata, None);
584 assert_eq!(tlv_stream.currency, None);
585 assert_eq!(tlv_stream.amount, None);
586 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
587 assert_eq!(tlv_stream.features, None);
588 assert_eq!(tlv_stream.absolute_expiry, None);
589 assert_eq!(tlv_stream.paths, None);
590 assert_eq!(tlv_stream.issuer, None);
591 assert_eq!(tlv_stream.quantity_max, None);
592 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
594 if let Err(e) = Offer::try_from(buffer) {
595 panic!("error parsing offer: {:?}", e);
600 fn builds_offer_with_chains() {
601 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
602 let testnet = ChainHash::using_genesis_block(Network::Testnet);
604 let offer = OfferBuilder::new("foo".into(), pubkey(42))
605 .chain(Network::Bitcoin)
608 assert_eq!(offer.chains(), vec![mainnet]);
609 assert_eq!(offer.as_tlv_stream().chains, None);
611 let offer = OfferBuilder::new("foo".into(), pubkey(42))
612 .chain(Network::Testnet)
615 assert_eq!(offer.chains(), vec![testnet]);
616 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
618 let offer = OfferBuilder::new("foo".into(), pubkey(42))
619 .chain(Network::Testnet)
620 .chain(Network::Testnet)
623 assert_eq!(offer.chains(), vec![testnet]);
624 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
626 let offer = OfferBuilder::new("foo".into(), pubkey(42))
627 .chain(Network::Bitcoin)
628 .chain(Network::Testnet)
631 assert_eq!(offer.chains(), vec![mainnet, testnet]);
632 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
636 fn builds_offer_with_metadata() {
637 let offer = OfferBuilder::new("foo".into(), pubkey(42))
638 .metadata(vec![42; 32])
641 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
642 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
644 let offer = OfferBuilder::new("foo".into(), pubkey(42))
645 .metadata(vec![42; 32])
646 .metadata(vec![43; 32])
649 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
650 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
654 fn builds_offer_with_amount() {
655 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
656 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
658 let offer = OfferBuilder::new("foo".into(), pubkey(42))
662 let tlv_stream = offer.as_tlv_stream();
663 assert_eq!(offer.amount(), Some(&bitcoin_amount));
664 assert_eq!(tlv_stream.amount, Some(1000));
665 assert_eq!(tlv_stream.currency, None);
667 let builder = OfferBuilder::new("foo".into(), pubkey(42))
668 .amount(currency_amount.clone());
669 let tlv_stream = builder.offer.as_tlv_stream();
670 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
671 assert_eq!(tlv_stream.amount, Some(10));
672 assert_eq!(tlv_stream.currency, Some(b"USD"));
673 match builder.build() {
674 Ok(_) => panic!("expected error"),
675 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
678 let offer = OfferBuilder::new("foo".into(), pubkey(42))
679 .amount(currency_amount.clone())
680 .amount(bitcoin_amount.clone())
683 let tlv_stream = offer.as_tlv_stream();
684 assert_eq!(tlv_stream.amount, Some(1000));
685 assert_eq!(tlv_stream.currency, None);
687 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
688 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
689 Ok(_) => panic!("expected error"),
690 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
695 fn builds_offer_with_features() {
696 let offer = OfferBuilder::new("foo".into(), pubkey(42))
697 .features(OfferFeatures::unknown())
700 assert_eq!(offer.features(), &OfferFeatures::unknown());
701 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
703 let offer = OfferBuilder::new("foo".into(), pubkey(42))
704 .features(OfferFeatures::unknown())
705 .features(OfferFeatures::empty())
708 assert_eq!(offer.features(), &OfferFeatures::empty());
709 assert_eq!(offer.as_tlv_stream().features, None);
713 fn builds_offer_with_absolute_expiry() {
714 let future_expiry = Duration::from_secs(u64::max_value());
715 let past_expiry = Duration::from_secs(0);
717 let offer = OfferBuilder::new("foo".into(), pubkey(42))
718 .absolute_expiry(future_expiry)
721 #[cfg(feature = "std")]
722 assert!(!offer.is_expired());
723 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
724 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
726 let offer = OfferBuilder::new("foo".into(), pubkey(42))
727 .absolute_expiry(future_expiry)
728 .absolute_expiry(past_expiry)
731 #[cfg(feature = "std")]
732 assert!(offer.is_expired());
733 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
734 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
738 fn builds_offer_with_paths() {
741 introduction_node_id: pubkey(40),
742 blinding_point: pubkey(41),
744 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
745 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
749 introduction_node_id: pubkey(40),
750 blinding_point: pubkey(41),
752 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
753 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
758 let offer = OfferBuilder::new("foo".into(), pubkey(42))
759 .path(paths[0].clone())
760 .path(paths[1].clone())
763 let tlv_stream = offer.as_tlv_stream();
764 assert_eq!(offer.paths(), paths.as_slice());
765 assert_eq!(offer.signing_pubkey(), pubkey(42));
766 assert_ne!(pubkey(42), pubkey(44));
767 assert_eq!(tlv_stream.paths, Some(&paths));
768 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
772 fn builds_offer_with_issuer() {
773 let offer = OfferBuilder::new("foo".into(), pubkey(42))
774 .issuer("bar".into())
777 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
778 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
780 let offer = OfferBuilder::new("foo".into(), pubkey(42))
781 .issuer("bar".into())
782 .issuer("baz".into())
785 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
786 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
790 fn builds_offer_with_supported_quantity() {
791 let ten = NonZeroU64::new(10).unwrap();
793 let offer = OfferBuilder::new("foo".into(), pubkey(42))
794 .supported_quantity(Quantity::one())
797 let tlv_stream = offer.as_tlv_stream();
798 assert_eq!(offer.supported_quantity(), Quantity::one());
799 assert_eq!(tlv_stream.quantity_max, None);
801 let offer = OfferBuilder::new("foo".into(), pubkey(42))
802 .supported_quantity(Quantity::Unbounded)
805 let tlv_stream = offer.as_tlv_stream();
806 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
807 assert_eq!(tlv_stream.quantity_max, Some(0));
809 let offer = OfferBuilder::new("foo".into(), pubkey(42))
810 .supported_quantity(Quantity::Bounded(ten))
813 let tlv_stream = offer.as_tlv_stream();
814 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
815 assert_eq!(tlv_stream.quantity_max, Some(10));
817 let offer = OfferBuilder::new("foo".into(), pubkey(42))
818 .supported_quantity(Quantity::Bounded(ten))
819 .supported_quantity(Quantity::one())
822 let tlv_stream = offer.as_tlv_stream();
823 assert_eq!(offer.supported_quantity(), Quantity::one());
824 assert_eq!(tlv_stream.quantity_max, None);
828 fn parses_offer_with_chains() {
829 let offer = OfferBuilder::new("foo".into(), pubkey(42))
830 .chain(Network::Bitcoin)
831 .chain(Network::Testnet)
834 if let Err(e) = offer.to_string().parse::<Offer>() {
835 panic!("error parsing offer: {:?}", e);
840 fn parses_offer_with_amount() {
841 let offer = OfferBuilder::new("foo".into(), pubkey(42))
842 .amount(Amount::Bitcoin { amount_msats: 1000 })
845 if let Err(e) = offer.to_string().parse::<Offer>() {
846 panic!("error parsing offer: {:?}", e);
849 let mut tlv_stream = offer.as_tlv_stream();
850 tlv_stream.amount = Some(1000);
851 tlv_stream.currency = Some(b"USD");
853 let mut encoded_offer = Vec::new();
854 tlv_stream.write(&mut encoded_offer).unwrap();
856 if let Err(e) = Offer::try_from(encoded_offer) {
857 panic!("error parsing offer: {:?}", e);
860 let mut tlv_stream = offer.as_tlv_stream();
861 tlv_stream.amount = None;
862 tlv_stream.currency = Some(b"USD");
864 let mut encoded_offer = Vec::new();
865 tlv_stream.write(&mut encoded_offer).unwrap();
867 match Offer::try_from(encoded_offer) {
868 Ok(_) => panic!("expected error"),
869 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
872 let mut tlv_stream = offer.as_tlv_stream();
873 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
874 tlv_stream.currency = None;
876 let mut encoded_offer = Vec::new();
877 tlv_stream.write(&mut encoded_offer).unwrap();
879 match Offer::try_from(encoded_offer) {
880 Ok(_) => panic!("expected error"),
881 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
886 fn parses_offer_with_description() {
887 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
888 if let Err(e) = offer.to_string().parse::<Offer>() {
889 panic!("error parsing offer: {:?}", e);
892 let mut tlv_stream = offer.as_tlv_stream();
893 tlv_stream.description = None;
895 let mut encoded_offer = Vec::new();
896 tlv_stream.write(&mut encoded_offer).unwrap();
898 match Offer::try_from(encoded_offer) {
899 Ok(_) => panic!("expected error"),
901 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
907 fn parses_offer_with_paths() {
908 let offer = OfferBuilder::new("foo".into(), pubkey(42))
910 introduction_node_id: pubkey(40),
911 blinding_point: pubkey(41),
913 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
914 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
918 introduction_node_id: pubkey(40),
919 blinding_point: pubkey(41),
921 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
922 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
927 if let Err(e) = offer.to_string().parse::<Offer>() {
928 panic!("error parsing offer: {:?}", e);
931 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
932 builder.offer.paths = Some(vec![]);
934 let offer = builder.build().unwrap();
935 if let Err(e) = offer.to_string().parse::<Offer>() {
936 panic!("error parsing offer: {:?}", e);
941 fn parses_offer_with_quantity() {
942 let offer = OfferBuilder::new("foo".into(), pubkey(42))
943 .supported_quantity(Quantity::one())
946 if let Err(e) = offer.to_string().parse::<Offer>() {
947 panic!("error parsing offer: {:?}", e);
950 let offer = OfferBuilder::new("foo".into(), pubkey(42))
951 .supported_quantity(Quantity::Unbounded)
954 if let Err(e) = offer.to_string().parse::<Offer>() {
955 panic!("error parsing offer: {:?}", e);
958 let offer = OfferBuilder::new("foo".into(), pubkey(42))
959 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
962 if let Err(e) = offer.to_string().parse::<Offer>() {
963 panic!("error parsing offer: {:?}", e);
966 let mut tlv_stream = offer.as_tlv_stream();
967 tlv_stream.quantity_max = Some(1);
969 let mut encoded_offer = Vec::new();
970 tlv_stream.write(&mut encoded_offer).unwrap();
972 match Offer::try_from(encoded_offer) {
973 Ok(_) => panic!("expected error"),
975 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
981 fn parses_offer_with_node_id() {
982 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
983 if let Err(e) = offer.to_string().parse::<Offer>() {
984 panic!("error parsing offer: {:?}", e);
987 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
988 builder.offer.signing_pubkey = None;
990 let offer = builder.build().unwrap();
991 match offer.to_string().parse::<Offer>() {
992 Ok(_) => panic!("expected error"),
994 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1000 fn fails_parsing_offer_with_extra_tlv_records() {
1001 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
1003 let mut encoded_offer = Vec::new();
1004 offer.write(&mut encoded_offer).unwrap();
1005 BigSize(80).write(&mut encoded_offer).unwrap();
1006 BigSize(32).write(&mut encoded_offer).unwrap();
1007 [42u8; 32].write(&mut encoded_offer).unwrap();
1009 match Offer::try_from(encoded_offer) {
1010 Ok(_) => panic!("expected error"),
1011 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1018 use super::{Offer, ParseError};
1019 use bitcoin::bech32;
1020 use crate::ln::msgs::DecodeError;
1022 // TODO: Remove once test vectors are updated.
1025 fn encodes_offer_as_bech32_without_checksum() {
1026 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1027 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1028 let reencoded_offer = offer.to_string();
1029 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1030 assert_eq!(reencoded_offer, encoded_offer);
1033 // TODO: Remove once test vectors are updated.
1036 fn parses_bech32_encoded_offers() {
1038 // BOLT 12 test vectors
1039 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1040 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1041 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1042 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1043 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1044 // Two blinded paths
1045 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1047 for encoded_offer in &offers {
1048 if let Err(e) = encoded_offer.parse::<Offer>() {
1049 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1055 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1057 // BOLT 12 test vectors
1058 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1059 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1060 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1061 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1062 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1064 for encoded_offer in &offers {
1065 match encoded_offer.parse::<Offer>() {
1066 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1067 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1074 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1075 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1076 match encoded_offer.parse::<Offer>() {
1077 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1078 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1083 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1084 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1085 match encoded_offer.parse::<Offer>() {
1086 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1087 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1092 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1093 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1094 match encoded_offer.parse::<Offer>() {
1095 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1096 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),