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())
54 //! // Encode as a bech32 string for use in a QR code.
55 //! let encoded_offer = offer.to_string();
57 //! // Parse from a bech32 string after scanning from a QR code.
58 //! let offer = encoded_offer.parse::<Offer>()?;
60 //! // Encode offer as raw bytes.
61 //! let mut bytes = Vec::new();
62 //! offer.write(&mut bytes).unwrap();
64 //! // Decode raw bytes into an offer.
65 //! let offer = Offer::try_from(bytes)?;
70 use bitcoin::blockdata::constants::ChainHash;
71 use bitcoin::network::constants::Network;
72 use bitcoin::secp256k1::PublicKey;
73 use core::convert::TryFrom;
74 use core::num::NonZeroU64;
75 use core::str::FromStr;
76 use core::time::Duration;
78 use crate::ln::features::OfferFeatures;
79 use crate::ln::msgs::MAX_VALUE_MSAT;
80 use crate::offers::parse::{Bech32Encode, ParseError, SemanticError};
81 use crate::onion_message::BlindedPath;
82 use crate::util::ser::{HighZeroBytesDroppedBigSize, Readable, WithoutLength, Writeable, Writer};
83 use crate::util::string::PrintableString;
85 use crate::prelude::*;
87 #[cfg(feature = "std")]
88 use std::time::SystemTime;
90 /// Builds an [`Offer`] for the "offer to be paid" flow.
92 /// See [module-level documentation] for usage.
94 /// [module-level documentation]: self
95 pub struct OfferBuilder {
100 /// Creates a new builder for an offer setting the [`Offer::description`] and using the
101 /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
102 /// while the offer is valid.
104 /// Use a different pubkey per offer to avoid correlating offers.
105 pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
106 let offer = OfferContents {
107 chains: None, metadata: None, amount: None, description,
108 features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
109 supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
111 OfferBuilder { offer }
114 /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
115 /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
117 /// See [`Offer::chains`] on how this relates to the payment currency.
119 /// Successive calls to this method will add another chain hash.
120 pub fn chain(mut self, network: Network) -> Self {
121 let chains = self.offer.chains.get_or_insert_with(Vec::new);
122 let chain = ChainHash::using_genesis_block(network);
123 if !chains.contains(&chain) {
130 /// Sets the [`Offer::metadata`].
132 /// Successive calls to this method will override the previous setting.
133 pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
134 self.offer.metadata = Some(metadata);
138 /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
140 /// Successive calls to this method will override the previous setting.
141 pub fn amount_msats(mut self, amount_msats: u64) -> Self {
142 self.amount(Amount::Bitcoin { amount_msats })
145 /// Sets the [`Offer::amount`].
147 /// Successive calls to this method will override the previous setting.
148 fn amount(mut self, amount: Amount) -> Self {
149 self.offer.amount = Some(amount);
153 /// Sets the [`Offer::features`].
155 /// Successive calls to this method will override the previous setting.
157 pub fn features(mut self, features: OfferFeatures) -> Self {
158 self.offer.features = features;
162 /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
163 /// already passed is valid and can be checked for using [`Offer::is_expired`].
165 /// Successive calls to this method will override the previous setting.
166 pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
167 self.offer.absolute_expiry = Some(absolute_expiry);
171 /// Sets the [`Offer::issuer`].
173 /// Successive calls to this method will override the previous setting.
174 pub fn issuer(mut self, issuer: String) -> Self {
175 self.offer.issuer = Some(issuer);
179 /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
180 /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
182 /// Successive calls to this method will add another blinded path. Caller is responsible for not
183 /// adding duplicate paths.
184 pub fn path(mut self, path: BlindedPath) -> Self {
185 self.offer.paths.get_or_insert_with(Vec::new).push(path);
189 /// Sets the quantity of items for [`Offer::supported_quantity`].
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, ()> {
199 match self.offer.amount {
200 Some(Amount::Bitcoin { amount_msats }) => {
201 if amount_msats > MAX_VALUE_MSAT {
205 Some(Amount::Currency { .. }) => unreachable!(),
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 impl TryFrom<Vec<u8>> for Offer {
399 type Error = ParseError;
401 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
402 let tlv_stream: OfferTlvStream = Readable::read(&mut &bytes[..])?;
403 Offer::try_from((bytes, tlv_stream))
407 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
408 /// another currency.
409 #[derive(Clone, Debug, PartialEq)]
411 /// An amount of bitcoin.
413 /// The amount in millisatoshi.
416 /// An amount of currency specified using ISO 4712.
418 /// The currency that the amount is denominated in.
419 iso4217_code: CurrencyCode,
420 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
425 /// An ISO 4712 three-letter currency code (e.g., USD).
426 pub type CurrencyCode = [u8; 3];
428 /// Quantity of items supported by an [`Offer`].
429 #[derive(Clone, Copy, Debug, PartialEq)]
431 /// Up to a specific number of items (inclusive).
433 /// One or more items.
439 Quantity::Bounded(NonZeroU64::new(1).unwrap())
442 fn to_tlv_record(&self) -> Option<u64> {
444 Quantity::Bounded(n) => {
446 if n == 1 { None } else { Some(n) }
448 Quantity::Unbounded => Some(0),
453 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
454 (2, chains: (Vec<ChainHash>, WithoutLength)),
455 (4, metadata: (Vec<u8>, WithoutLength)),
456 (6, currency: CurrencyCode),
457 (8, amount: (u64, HighZeroBytesDroppedBigSize)),
458 (10, description: (String, WithoutLength)),
459 (12, features: OfferFeatures),
460 (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
461 (16, paths: (Vec<BlindedPath>, WithoutLength)),
462 (18, issuer: (String, WithoutLength)),
463 (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
464 (22, node_id: PublicKey),
467 impl Bech32Encode for Offer {
468 const BECH32_HRP: &'static str = "lno";
471 type ParsedOffer = (Vec<u8>, OfferTlvStream);
473 impl FromStr for Offer {
474 type Err = ParseError;
476 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
477 Self::from_bech32_str(s)
481 impl TryFrom<ParsedOffer> for Offer {
482 type Error = ParseError;
484 fn try_from(offer: ParsedOffer) -> Result<Self, Self::Error> {
485 let (bytes, tlv_stream) = offer;
486 let contents = OfferContents::try_from(tlv_stream)?;
487 Ok(Offer { bytes, contents })
491 impl TryFrom<OfferTlvStream> for OfferContents {
492 type Error = SemanticError;
494 fn try_from(tlv_stream: OfferTlvStream) -> Result<Self, Self::Error> {
496 chains, metadata, currency, amount, description, features, absolute_expiry, paths,
497 issuer, quantity_max, node_id,
500 let amount = match (currency, amount) {
501 (None, None) => None,
502 (None, Some(amount_msats)) if amount_msats > MAX_VALUE_MSAT => {
503 return Err(SemanticError::InvalidAmount);
505 (None, Some(amount_msats)) => Some(Amount::Bitcoin { amount_msats }),
506 (Some(_), None) => return Err(SemanticError::MissingAmount),
507 (Some(iso4217_code), Some(amount)) => Some(Amount::Currency { iso4217_code, amount }),
510 let description = match description {
511 None => return Err(SemanticError::MissingDescription),
512 Some(description) => description,
515 let features = features.unwrap_or_else(OfferFeatures::empty);
517 let absolute_expiry = absolute_expiry
518 .map(|seconds_from_epoch| Duration::from_secs(seconds_from_epoch));
520 let supported_quantity = match quantity_max {
521 None => Quantity::one(),
522 Some(0) => Quantity::Unbounded,
523 Some(1) => return Err(SemanticError::InvalidQuantity),
524 Some(n) => Quantity::Bounded(NonZeroU64::new(n).unwrap()),
527 if node_id.is_none() {
528 return Err(SemanticError::MissingSigningPubkey);
532 chains, metadata, amount, description, features, absolute_expiry, issuer, paths,
533 supported_quantity, signing_pubkey: node_id,
538 impl core::fmt::Display for Offer {
539 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
540 self.fmt_bech32_str(f)
546 use super::{Amount, Offer, OfferBuilder, Quantity};
548 use bitcoin::blockdata::constants::ChainHash;
549 use bitcoin::network::constants::Network;
550 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
551 use core::convert::TryFrom;
552 use core::num::NonZeroU64;
553 use core::time::Duration;
554 use crate::ln::features::OfferFeatures;
555 use crate::ln::msgs::MAX_VALUE_MSAT;
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"));
682 let offer = OfferBuilder::new("foo".into(), pubkey(42))
683 .amount(currency_amount.clone())
684 .amount(bitcoin_amount.clone())
687 let tlv_stream = offer.as_tlv_stream();
688 assert_eq!(tlv_stream.amount, Some(1000));
689 assert_eq!(tlv_stream.currency, None);
691 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
692 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
693 Ok(_) => panic!("expected error"),
694 Err(e) => assert_eq!(e, ()),
699 fn builds_offer_with_features() {
700 let offer = OfferBuilder::new("foo".into(), pubkey(42))
701 .features(OfferFeatures::unknown())
704 assert_eq!(offer.features(), &OfferFeatures::unknown());
705 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
707 let offer = OfferBuilder::new("foo".into(), pubkey(42))
708 .features(OfferFeatures::unknown())
709 .features(OfferFeatures::empty())
712 assert_eq!(offer.features(), &OfferFeatures::empty());
713 assert_eq!(offer.as_tlv_stream().features, None);
717 fn builds_offer_with_absolute_expiry() {
718 let future_expiry = Duration::from_secs(u64::max_value());
719 let past_expiry = Duration::from_secs(0);
721 let offer = OfferBuilder::new("foo".into(), pubkey(42))
722 .absolute_expiry(future_expiry)
725 #[cfg(feature = "std")]
726 assert!(!offer.is_expired());
727 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
728 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
730 let offer = OfferBuilder::new("foo".into(), pubkey(42))
731 .absolute_expiry(future_expiry)
732 .absolute_expiry(past_expiry)
735 #[cfg(feature = "std")]
736 assert!(offer.is_expired());
737 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
738 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
742 fn builds_offer_with_paths() {
745 introduction_node_id: pubkey(40),
746 blinding_point: pubkey(41),
748 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
749 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
753 introduction_node_id: pubkey(40),
754 blinding_point: pubkey(41),
756 BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
757 BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
762 let offer = OfferBuilder::new("foo".into(), pubkey(42))
763 .path(paths[0].clone())
764 .path(paths[1].clone())
767 let tlv_stream = offer.as_tlv_stream();
768 assert_eq!(offer.paths(), paths.as_slice());
769 assert_eq!(offer.signing_pubkey(), pubkey(42));
770 assert_ne!(pubkey(42), pubkey(44));
771 assert_eq!(tlv_stream.paths, Some(&paths));
772 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
776 fn builds_offer_with_issuer() {
777 let offer = OfferBuilder::new("foo".into(), pubkey(42))
778 .issuer("bar".into())
781 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
782 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
784 let offer = OfferBuilder::new("foo".into(), pubkey(42))
785 .issuer("bar".into())
786 .issuer("baz".into())
789 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
790 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
794 fn builds_offer_with_supported_quantity() {
795 let ten = NonZeroU64::new(10).unwrap();
797 let offer = OfferBuilder::new("foo".into(), pubkey(42))
798 .supported_quantity(Quantity::one())
801 let tlv_stream = offer.as_tlv_stream();
802 assert_eq!(offer.supported_quantity(), Quantity::one());
803 assert_eq!(tlv_stream.quantity_max, None);
805 let offer = OfferBuilder::new("foo".into(), pubkey(42))
806 .supported_quantity(Quantity::Unbounded)
809 let tlv_stream = offer.as_tlv_stream();
810 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
811 assert_eq!(tlv_stream.quantity_max, Some(0));
813 let offer = OfferBuilder::new("foo".into(), pubkey(42))
814 .supported_quantity(Quantity::Bounded(ten))
817 let tlv_stream = offer.as_tlv_stream();
818 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
819 assert_eq!(tlv_stream.quantity_max, Some(10));
821 let offer = OfferBuilder::new("foo".into(), pubkey(42))
822 .supported_quantity(Quantity::Bounded(ten))
823 .supported_quantity(Quantity::one())
826 let tlv_stream = offer.as_tlv_stream();
827 assert_eq!(offer.supported_quantity(), Quantity::one());
828 assert_eq!(tlv_stream.quantity_max, None);
834 use super::{Offer, ParseError};
836 use crate::ln::msgs::DecodeError;
838 // TODO: Remove once test vectors are updated.
841 fn encodes_offer_as_bech32_without_checksum() {
842 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
843 let offer = dbg!(encoded_offer.parse::<Offer>().unwrap());
844 let reencoded_offer = offer.to_string();
845 dbg!(reencoded_offer.parse::<Offer>().unwrap());
846 assert_eq!(reencoded_offer, encoded_offer);
849 // TODO: Remove once test vectors are updated.
852 fn parses_bech32_encoded_offers() {
854 // BOLT 12 test vectors
855 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
856 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
857 "l+no1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
858 "lno1qcp4256ypqpq+86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qs+y",
859 "lno1qcp4256ypqpq+ 86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn0+ 0fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0+\nsqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43l+\r\nastpwuh73k29qs+\r y",
861 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0yg06qg2qdd7t628sgykwj5kuc837qmlv9m9gr7sq8ap6erfgacv26nhp8zzcqgzhdvttlk22pw8fmwqqrvzst792mj35ypylj886ljkcmug03wg6heqqsqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6muh550qsfva9fdes0ruph7ctk2s8aqq06r4jxj3msc448wzwy9sqs9w6ckhlv55zuwnkuqqxc9qhu24h9rggzflyw04l9d3hcslzu340jqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
863 for encoded_offer in &offers {
864 if let Err(e) = encoded_offer.parse::<Offer>() {
865 panic!("Invalid offer ({:?}): {}", e, encoded_offer);
871 fn fails_parsing_bech32_encoded_offers_with_invalid_continuations() {
873 // BOLT 12 test vectors
874 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+",
875 "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy+ ",
876 "+lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
877 "+ lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
878 "ln++o1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy",
880 for encoded_offer in &offers {
881 match encoded_offer.parse::<Offer>() {
882 Ok(_) => panic!("Valid offer: {}", encoded_offer),
883 Err(e) => assert_eq!(e, ParseError::InvalidContinuation),
890 fn fails_parsing_bech32_encoded_offer_with_invalid_hrp() {
891 let encoded_offer = "lni1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsy";
892 match encoded_offer.parse::<Offer>() {
893 Ok(_) => panic!("Valid offer: {}", encoded_offer),
894 Err(e) => assert_eq!(e, ParseError::InvalidBech32Hrp),
899 fn fails_parsing_bech32_encoded_offer_with_invalid_bech32_data() {
900 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qso";
901 match encoded_offer.parse::<Offer>() {
902 Ok(_) => panic!("Valid offer: {}", encoded_offer),
903 Err(e) => assert_eq!(e, ParseError::Bech32(bech32::Error::InvalidChar('o'))),
908 fn fails_parsing_bech32_encoded_offer_with_invalid_tlv_data() {
909 let encoded_offer = "lno1qcp4256ypqpq86q2pucnq42ngssx2an9wfujqerp0y2pqun4wd68jtn00fkxzcnn9ehhyec6qgqsz83qfwdpl28qqmc78ymlvhmxcsywdk5wrjnj36jryg488qwlrnzyjczlqsp9nyu4phcg6dqhlhzgxagfu7zh3d9re0sqp9ts2yfugvnnm9gxkcnnnkdpa084a6t520h5zhkxsdnghvpukvd43lastpwuh73k29qsyqqqqq";
910 match encoded_offer.parse::<Offer>() {
911 Ok(_) => panic!("Valid offer: {}", encoded_offer),
912 Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),