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, SemanticError};
80 use crate::onion_message::BlindedPath;
81 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
82 use crate::util::string::PrintableString;
84 use crate::prelude::*;
86 #[cfg(feature = "std")]
87 use std::time::SystemTime;
89 /// Builds an [`Offer`] for the "offer to be paid" flow.
91 /// See [module-level documentation] for usage.
93 /// [module-level documentation]: self
94 pub struct OfferBuilder {
99 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
100 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
101 /// while the offer is valid.
103 /// Use a different pubkey per offer to avoid correlating offers.
104 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
105 let offer = OfferContents {
106 chains: None, metadata: None, amount: None, description,
107 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
108 supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
110 OfferBuilder { offer }
113 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
114 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
116 /// See [`Offer::chains`] on how this relates to the payment currency.
118 /// Successive calls to this method will add another chain hash.
119 pub fn chain(mut self, network: Network) -> Self {
120 let chains = self.offer.chains.get_or_insert_with(Vec::new);
121 let chain = ChainHash::using_genesis_block(network);
122 if !chains.contains(&chain) {
129 /// Sets the [`Offer::metadata`].
131 /// Successive calls to this method will override the previous setting.
132 pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
133 self.offer.metadata = Some(metadata);
137 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
139 /// Successive calls to this method will override the previous setting.
140 pub fn amount_msats(mut self, amount_msats: u64) -> Self {
141 self.amount(Amount::Bitcoin { amount_msats })
144 /// Sets the [`Offer::amount`].
146 /// Successive calls to this method will override the previous setting.
147 fn amount(mut self, amount: Amount) -> Self {
148 self.offer.amount = Some(amount);
152 /// Sets the [`Offer::features`].
154 /// Successive calls to this method will override the previous setting.
156 pub fn features(mut self, features: OfferFeatures) -> Self {
157 self.offer.features = features;
161 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
162 /// already passed is valid and can be checked for using [`Offer::is_expired`].
164 /// Successive calls to this method will override the previous setting.
165 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
166 self.offer.absolute_expiry = Some(absolute_expiry);
170 /// Sets the [`Offer::issuer`].
172 /// Successive calls to this method will override the previous setting.
173 pub fn issuer(mut self, issuer: String) -> Self {
174 self.offer.issuer = Some(issuer);
178 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
179 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
181 /// Successive calls to this method will add another blinded path. Caller is responsible for not
182 /// adding duplicate paths.
183 pub fn path(mut self, path: BlindedPath) -> Self {
184 self.offer.paths.get_or_insert_with(Vec::new).push(path);
188 /// Sets the quantity of items for [`Offer::supported_quantity`].
190 /// Successive calls to this method will override the previous setting.
191 pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
192 self.offer.supported_quantity = quantity;
196 /// Builds an [`Offer`] from the builder's settings.
197 pub fn build(mut self) -> Result<Offer, SemanticError> {
198 match self.offer.amount {
199 Some(Amount::Bitcoin { amount_msats }) => {
200 if amount_msats > MAX_VALUE_MSAT {
201 return Err(SemanticError::InvalidAmount);
204 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
208 if let Some(chains) = &self.offer.chains {
209 if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
210 self.offer.chains = None;
214 let mut bytes = Vec::new();
215 self.offer.write(&mut bytes).unwrap();
219 contents: self.offer,
224 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
226 /// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
227 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
228 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
230 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
233 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
234 #[derive(Clone, Debug)]
236 // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
239 contents: OfferContents,
242 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
243 #[derive(Clone, Debug)]
244 pub(crate) struct OfferContents {
245 chains: Option<Vec<ChainHash>>,
246 metadata: Option<Vec<u8>>,
247 amount: Option<Amount>,
249 features: OfferFeatures,
250 absolute_expiry: Option<Duration>,
251 issuer: Option<String>,
252 paths: Option<Vec<BlindedPath>>,
253 supported_quantity: Quantity,
254 signing_pubkey: Option<PublicKey>,
258 // TODO: Return a slice once ChainHash has constants.
259 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
260 // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
261 /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
262 /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
263 /// for the selected chain.
264 pub fn chains(&self) -> Vec<ChainHash> {
268 .unwrap_or_else(|| vec![self.contents.implied_chain()])
271 // TODO: Link to corresponding method in `InvoiceRequest`.
272 /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
273 /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
274 pub fn metadata(&self) -> Option<&Vec<u8>> {
275 self.contents.metadata.as_ref()
278 /// The minimum amount required for a successful payment of a single item.
279 pub fn amount(&self) -> Option<&Amount> {
280 self.contents.amount.as_ref()
283 /// A complete description of the purpose of the payment. Intended to be displayed to the user
284 /// but with the caveat that it has not been verified in any way.
285 pub fn description(&self) -> PrintableString {
286 PrintableString(&self.contents.description)
289 /// Features pertaining to the offer.
290 pub fn features(&self) -> &OfferFeatures {
291 &self.contents.features
294 /// Duration since the Unix epoch when an invoice should no longer be requested.
296 /// If `None`, the offer does not expire.
297 pub fn absolute_expiry(&self) -> Option<Duration> {
298 self.contents.absolute_expiry
301 /// Whether the offer has expired.
302 #[cfg(feature = "std")]
303 pub fn is_expired(&self) -> bool {
304 match self.absolute_expiry() {
305 Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
306 Ok(elapsed) => elapsed > seconds_from_epoch,
313 /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
314 /// displayed to the user but with the caveat that it has not been verified in any way.
315 pub fn issuer(&self) -> Option<PrintableString> {
316 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
319 /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
320 /// recipient privacy by obfuscating its node id.
321 pub fn paths(&self) -> &[BlindedPath] {
322 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
325 /// The quantity of items supported.
326 pub fn supported_quantity(&self) -> Quantity {
327 self.contents.supported_quantity()
330 /// The public key used by the recipient to sign invoices.
331 pub fn signing_pubkey(&self) -> PublicKey {
332 self.contents.signing_pubkey.unwrap()
336 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
337 self.contents.as_tlv_stream()
341 impl AsRef<[u8]> for Offer {
342 fn as_ref(&self) -> &[u8] {
348 pub fn implied_chain(&self) -> ChainHash {
349 ChainHash::using_genesis_block(Network::Bitcoin)
352 pub fn supported_quantity(&self) -> Quantity {
353 self.supported_quantity
356 fn as_tlv_stream(&self) -> OfferTlvStreamRef {
357 let (currency, amount) = match &self.amount {
358 None => (None, None),
359 Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
360 Some(Amount::Currency { iso4217_code, amount }) => (
361 Some(iso4217_code), Some(*amount)
366 if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
370 chains: self.chains.as_ref(),
371 metadata: self.metadata.as_ref(),
374 description: Some(&self.description),
376 absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
377 paths: self.paths.as_ref(),
378 issuer: self.issuer.as_ref(),
379 quantity_max: self.supported_quantity.to_tlv_record(),
380 node_id: self.signing_pubkey.as_ref(),
385 impl Writeable for Offer {
386 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
387 WithoutLength(&self.bytes).write(writer)
391 impl Writeable for OfferContents {
392 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
393 self.as_tlv_stream().write(writer)
397 impl TryFrom<Vec<u8>> for Offer {
398 type Error = ParseError;
400 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
401 let tlv_stream: OfferTlvStream = Readable::read(&mut &bytes[..])?;
402 Offer::try_from((bytes, tlv_stream))
406 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
407 /// another currency.
408 #[derive(Clone, Debug, PartialEq)]
410 /// An amount of bitcoin.
412 /// The amount in millisatoshi.
415 /// An amount of currency specified using ISO 4712.
417 /// The currency that the amount is denominated in.
418 iso4217_code: CurrencyCode,
419 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
424 /// An ISO 4712 three-letter currency code (e.g., USD).
425 pub type CurrencyCode = [u8; 3];
427 /// Quantity of items supported by an [`Offer`].
428 #[derive(Clone, Copy, Debug, PartialEq)]
430 /// Up to a specific number of items (inclusive).
432 /// One or more items.
438 Quantity::Bounded(NonZeroU64::new(1).unwrap())
441 fn to_tlv_record(&self) -> Option<u64> {
443 Quantity::Bounded(n) => {
445 if n == 1 { None } else { Some(n) }
447 Quantity::Unbounded => Some(0),
452 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
453 (2, chains: (Vec<ChainHash>, WithoutLength)),
454 (4, metadata: (Vec<u8>, WithoutLength)),
455 (6, currency: CurrencyCode),
456 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
457 (10, description: (String, WithoutLength)),
458 (12, features: OfferFeatures),
459 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
460 (16, paths: (Vec<BlindedPath>, WithoutLength)),
461 (18, issuer: (String, WithoutLength)),
462 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
463 (22, node_id: PublicKey),
466 impl Bech32Encode for Offer {
467 const BECH32_HRP: &'static str = "lno";
470 type ParsedOffer = (Vec<u8>, OfferTlvStream);
472 impl FromStr for Offer {
473 type Err = ParseError;
475 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
476 Self::from_bech32_str(s)
480 impl TryFrom<ParsedOffer> for Offer {
481 type Error = ParseError;
483 fn try_from(offer: ParsedOffer) -> Result<Self, Self::Error> {
484 let (bytes, tlv_stream) = offer;
485 let contents = OfferContents::try_from(tlv_stream)?;
486 Ok(Offer { bytes, contents })
490 impl TryFrom<OfferTlvStream> for OfferContents {
491 type Error = SemanticError;
493 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
495 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
496 issuer, quantity_max, node_id,
499 let amount = match (currency, amount) {
500 (None, None) => None,
501 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
502 return Err(SemanticError::InvalidAmount);
504 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
505 (Some(_), None) => return Err(SemanticError::MissingAmount),
506 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
509 let description = match description {
510 None => return Err(SemanticError::MissingDescription),
511 Some(description) => description,
514 let features = features.unwrap_or_else(OfferFeatures::empty);
516 let absolute_expiry = absolute_expiry
517 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
519 let supported_quantity = match quantity_max {
520 None => Quantity::one(),
521 Some(0) => Quantity::Unbounded,
522 Some(1) => return Err(SemanticError::InvalidQuantity),
523 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
526 if node_id.is_none() {
527 return Err(SemanticError::MissingSigningPubkey);
531 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
532 supported_quantity, signing_pubkey: node_id,
537 impl core::fmt::Display for Offer {
538 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
539 self.fmt_bech32_str(f)
545 use super::{Amount, Offer, OfferBuilder, Quantity};
547 use bitcoin::blockdata::constants::ChainHash;
548 use bitcoin::network::constants::Network;
549 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
550 use core::convert::TryFrom;
551 use core::num::NonZeroU64;
552 use core::time::Duration;
553 use crate::ln::features::OfferFeatures;
554 use crate::ln::msgs::MAX_VALUE_MSAT;
555 use crate::offers::parse::{ParseError, SemanticError};
556 use crate::onion_message::{BlindedHop, BlindedPath};
557 use crate::util::ser::Writeable;
558 use crate::util::string::PrintableString;
560 fn pubkey(byte: u8) -> PublicKey {
561 let secp_ctx = Secp256k1::new();
562 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
565 fn privkey(byte: u8) -> SecretKey {
566 SecretKey::from_slice(&[byte; 32]).unwrap()
570 fn builds_offer_with_defaults() {
571 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
572 let tlv_stream = offer.as_tlv_stream();
573 let mut buffer = Vec::new();
574 offer.write(&mut buffer).unwrap();
576 assert_eq!(offer.bytes, buffer.as_slice());
577 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
578 assert_eq!(offer.metadata(), None);
579 assert_eq!(offer.amount(), None);
580 assert_eq!(offer.description(), PrintableString("foo"));
581 assert_eq!(offer.features(), &OfferFeatures::empty());
582 assert_eq!(offer.absolute_expiry(), None);
583 #[cfg(feature = "std")]
584 assert!(!offer.is_expired());
585 assert_eq!(offer.paths(), &[]);
586 assert_eq!(offer.issuer(), None);
587 assert_eq!(offer.supported_quantity(), Quantity::one());
588 assert_eq!(offer.signing_pubkey(), pubkey(42));
590 assert_eq!(tlv_stream.chains, None);
591 assert_eq!(tlv_stream.metadata, None);
592 assert_eq!(tlv_stream.currency, None);
593 assert_eq!(tlv_stream.amount, None);
594 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
595 assert_eq!(tlv_stream.features, None);
596 assert_eq!(tlv_stream.absolute_expiry, None);
597 assert_eq!(tlv_stream.paths, None);
598 assert_eq!(tlv_stream.issuer, None);
599 assert_eq!(tlv_stream.quantity_max, None);
600 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
602 if let Err(e) = Offer::try_from(buffer) {
603 panic!("error parsing offer: {:?}", e);
608 fn builds_offer_with_chains() {
609 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
610 let testnet = ChainHash::using_genesis_block(Network::Testnet);
612 let offer = OfferBuilder::new("foo".into(), pubkey(42))
613 .chain(Network::Bitcoin)
616 assert_eq!(offer.chains(), vec![mainnet]);
617 assert_eq!(offer.as_tlv_stream().chains, None);
619 let offer = OfferBuilder::new("foo".into(), pubkey(42))
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::Testnet)
628 .chain(Network::Testnet)
631 assert_eq!(offer.chains(), vec![testnet]);
632 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
634 let offer = OfferBuilder::new("foo".into(), pubkey(42))
635 .chain(Network::Bitcoin)
636 .chain(Network::Testnet)
639 assert_eq!(offer.chains(), vec![mainnet, testnet]);
640 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
644 fn builds_offer_with_metadata() {
645 let offer = OfferBuilder::new("foo".into(), pubkey(42))
646 .metadata(vec![42; 32])
649 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
650 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
652 let offer = OfferBuilder::new("foo".into(), pubkey(42))
653 .metadata(vec![42; 32])
654 .metadata(vec![43; 32])
657 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
658 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
662 fn builds_offer_with_amount() {
663 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
664 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
666 let offer = OfferBuilder::new("foo".into(), pubkey(42))
670 let tlv_stream = offer.as_tlv_stream();
671 assert_eq!(offer.amount(), Some(&bitcoin_amount));
672 assert_eq!(tlv_stream.amount, Some(1000));
673 assert_eq!(tlv_stream.currency, None);
675 let builder = OfferBuilder::new("foo".into(), pubkey(42))
676 .amount(currency_amount.clone());
677 let tlv_stream = builder.offer.as_tlv_stream();
678 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
679 assert_eq!(tlv_stream.amount, Some(10));
680 assert_eq!(tlv_stream.currency, Some(b"USD"));
681 match builder.build() {
682 Ok(_) => panic!("expected error"),
683 Err(e) => assert_eq!(e, SemanticError::UnsupportedCurrency),
686 let offer = OfferBuilder::new("foo".into(), pubkey(42))
687 .amount(currency_amount.clone())
688 .amount(bitcoin_amount.clone())
691 let tlv_stream = offer.as_tlv_stream();
692 assert_eq!(tlv_stream.amount, Some(1000));
693 assert_eq!(tlv_stream.currency, None);
695 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
696 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
697 Ok(_) => panic!("expected error"),
698 Err(e) => assert_eq!(e, SemanticError::InvalidAmount),
703 fn builds_offer_with_features() {
704 let offer = OfferBuilder::new("foo".into(), pubkey(42))
705 .features(OfferFeatures::unknown())
708 assert_eq!(offer.features(), &OfferFeatures::unknown());
709 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
711 let offer = OfferBuilder::new("foo".into(), pubkey(42))
712 .features(OfferFeatures::unknown())
713 .features(OfferFeatures::empty())
716 assert_eq!(offer.features(), &OfferFeatures::empty());
717 assert_eq!(offer.as_tlv_stream().features, None);
721 fn builds_offer_with_absolute_expiry() {
722 let future_expiry = Duration::from_secs(u64::max_value());
723 let past_expiry = Duration::from_secs(0);
725 let offer = OfferBuilder::new("foo".into(), pubkey(42))
726 .absolute_expiry(future_expiry)
729 #[cfg(feature = "std")]
730 assert!(!offer.is_expired());
731 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
732 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
734 let offer = OfferBuilder::new("foo".into(), pubkey(42))
735 .absolute_expiry(future_expiry)
736 .absolute_expiry(past_expiry)
739 #[cfg(feature = "std")]
740 assert!(offer.is_expired());
741 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
742 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
746 fn builds_offer_with_paths() {
749 introduction_node_id: pubkey(40),
750 blinding_point: pubkey(41),
752 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
753 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
757 introduction_node_id: pubkey(40),
758 blinding_point: pubkey(41),
760 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
761 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
766 let offer = OfferBuilder::new("foo".into(), pubkey(42))
767 .path(paths[0].clone())
768 .path(paths[1].clone())
771 let tlv_stream = offer.as_tlv_stream();
772 assert_eq!(offer.paths(), paths.as_slice());
773 assert_eq!(offer.signing_pubkey(), pubkey(42));
774 assert_ne!(pubkey(42), pubkey(44));
775 assert_eq!(tlv_stream.paths, Some(&paths));
776 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
780 fn builds_offer_with_issuer() {
781 let offer = OfferBuilder::new("foo".into(), pubkey(42))
782 .issuer("bar".into())
785 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
786 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
788 let offer = OfferBuilder::new("foo".into(), pubkey(42))
789 .issuer("bar".into())
790 .issuer("baz".into())
793 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
794 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
798 fn builds_offer_with_supported_quantity() {
799 let ten = NonZeroU64::new(10).unwrap();
801 let offer = OfferBuilder::new("foo".into(), pubkey(42))
802 .supported_quantity(Quantity::one())
805 let tlv_stream = offer.as_tlv_stream();
806 assert_eq!(offer.supported_quantity(), Quantity::one());
807 assert_eq!(tlv_stream.quantity_max, None);
809 let offer = OfferBuilder::new("foo".into(), pubkey(42))
810 .supported_quantity(Quantity::Unbounded)
813 let tlv_stream = offer.as_tlv_stream();
814 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
815 assert_eq!(tlv_stream.quantity_max, Some(0));
817 let offer = OfferBuilder::new("foo".into(), pubkey(42))
818 .supported_quantity(Quantity::Bounded(ten))
821 let tlv_stream = offer.as_tlv_stream();
822 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
823 assert_eq!(tlv_stream.quantity_max, Some(10));
825 let offer = OfferBuilder::new("foo".into(), pubkey(42))
826 .supported_quantity(Quantity::Bounded(ten))
827 .supported_quantity(Quantity::one())
830 let tlv_stream = offer.as_tlv_stream();
831 assert_eq!(offer.supported_quantity(), Quantity::one());
832 assert_eq!(tlv_stream.quantity_max, None);
836 fn parses_offer_with_chains() {
837 let offer = OfferBuilder::new("foo".into(), pubkey(42))
838 .chain(Network::Bitcoin)
839 .chain(Network::Testnet)
842 if let Err(e) = offer.to_string().parse::<Offer>() {
843 panic!("error parsing offer: {:?}", e);
848 fn parses_offer_with_amount() {
849 let offer = OfferBuilder::new("foo".into(), pubkey(42))
850 .amount(Amount::Bitcoin { amount_msats: 1000 })
853 if let Err(e) = offer.to_string().parse::<Offer>() {
854 panic!("error parsing offer: {:?}", e);
857 let mut tlv_stream = offer.as_tlv_stream();
858 tlv_stream.amount = Some(1000);
859 tlv_stream.currency = Some(b"USD");
861 let mut encoded_offer = Vec::new();
862 tlv_stream.write(&mut encoded_offer).unwrap();
864 if let Err(e) = Offer::try_from(encoded_offer) {
865 panic!("error parsing offer: {:?}", e);
868 let mut tlv_stream = offer.as_tlv_stream();
869 tlv_stream.amount = None;
870 tlv_stream.currency = Some(b"USD");
872 let mut encoded_offer = Vec::new();
873 tlv_stream.write(&mut encoded_offer).unwrap();
875 match Offer::try_from(encoded_offer) {
876 Ok(_) => panic!("expected error"),
877 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
880 let mut tlv_stream = offer.as_tlv_stream();
881 tlv_stream.amount = Some(MAX_VALUE_MSAT + 1);
882 tlv_stream.currency = None;
884 let mut encoded_offer = Vec::new();
885 tlv_stream.write(&mut encoded_offer).unwrap();
887 match Offer::try_from(encoded_offer) {
888 Ok(_) => panic!("expected error"),
889 Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidAmount)),
894 fn parses_offer_with_description() {
895 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
896 if let Err(e) = offer.to_string().parse::<Offer>() {
897 panic!("error parsing offer: {:?}", e);
900 let mut tlv_stream = offer.as_tlv_stream();
901 tlv_stream.description = None;
903 let mut encoded_offer = Vec::new();
904 tlv_stream.write(&mut encoded_offer).unwrap();
906 match Offer::try_from(encoded_offer) {
907 Ok(_) => panic!("expected error"),
909 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingDescription));
915 fn parses_offer_with_paths() {
916 let offer = OfferBuilder::new("foo".into(), pubkey(42))
918 introduction_node_id: pubkey(40),
919 blinding_point: pubkey(41),
921 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
922 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
926 introduction_node_id: pubkey(40),
927 blinding_point: pubkey(41),
929 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
930 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
935 if let Err(e) = offer.to_string().parse::<Offer>() {
936 panic!("error parsing offer: {:?}", e);
939 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
940 builder.offer.paths = Some(vec![]);
942 let offer = builder.build().unwrap();
943 if let Err(e) = offer.to_string().parse::<Offer>() {
944 panic!("error parsing offer: {:?}", e);
949 fn parses_offer_with_quantity() {
950 let offer = OfferBuilder::new("foo".into(), pubkey(42))
951 .supported_quantity(Quantity::one())
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::Unbounded)
962 if let Err(e) = offer.to_string().parse::<Offer>() {
963 panic!("error parsing offer: {:?}", e);
966 let offer = OfferBuilder::new("foo".into(), pubkey(42))
967 .supported_quantity(Quantity::Bounded(NonZeroU64::new(10).unwrap()))
970 if let Err(e) = offer.to_string().parse::<Offer>() {
971 panic!("error parsing offer: {:?}", e);
974 let mut tlv_stream = offer.as_tlv_stream();
975 tlv_stream.quantity_max = Some(1);
977 let mut encoded_offer = Vec::new();
978 tlv_stream.write(&mut encoded_offer).unwrap();
980 match Offer::try_from(encoded_offer) {
981 Ok(_) => panic!("expected error"),
983 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidQuantity));
989 fn parses_offer_with_node_id() {
990 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
991 if let Err(e) = offer.to_string().parse::<Offer>() {
992 panic!("error parsing offer: {:?}", e);
995 let mut builder = OfferBuilder::new("foo".into(), pubkey(42));
996 builder.offer.signing_pubkey = None;
998 let offer = builder.build().unwrap();
999 match offer.to_string().parse::<Offer>() {
1000 Ok(_) => panic!("expected error"),
1002 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1010 use super::{Offer, ParseError};
1011 use bitcoin::bech32;
1012 use crate::ln::msgs::DecodeError;
1014 // TODO: Remove once test vectors are updated.
1017 fn encodes_offer_as_bech32_without_checksum() {
1018 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1019 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
1020 let reencoded_offer = offer.to_string();
1021 dbg!(reencoded_offer.parse::<Offer>().unwrap());
1022 assert_eq!(reencoded_offer, encoded_offer);
1025 // TODO: Remove once test vectors are updated.
1028 fn parses_bech32_encoded_offers() {
1030 // BOLT 12 test vectors
1031 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1032 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1033 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1034 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
1035 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
1036 // Two blinded paths
1037 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1039 for encoded_offer in &offers {
1040 if let Err(e) = encoded_offer.parse::<Offer>() {
1041 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
1047 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
1049 // BOLT 12 test vectors
1050 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
1051 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
1052 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1053 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1054 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
1056 for encoded_offer in &offers {
1057 match encoded_offer.parse::<Offer>() {
1058 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1059 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
1066 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
1067 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
1068 match encoded_offer.parse::<Offer>() {
1069 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1070 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
1075 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
1076 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
1077 match encoded_offer.parse::<Offer>() {
1078 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1079 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
1084 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
1085 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
1086 match encoded_offer.parse::<Offer>() {
1087 Ok(_) => panic!("Valid offer: {}", encoded_offer),
1088 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),