Builder for creating offers
[rust-lightning] / lightning / src / offers / offer.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Data structures and encoding for `offer` messages.
11 //!
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.
15 //!
16 //! ```ignore
17 //! extern crate bitcoin;
18 //! extern crate core;
19 //! extern crate lightning;
20 //!
21 //! use core::num::NonZeroU64;
22 //! use core::time::Duration;
23 //!
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use lightning::offers::offer::{OfferBuilder, Quantity};
26 //!
27 //! # use bitcoin::secp256k1;
28 //! # use lightning::onion_message::BlindedPath;
29 //! # #[cfg(feature = "std")]
30 //! # use std::time::SystemTime;
31 //! #
32 //! # fn create_blinded_path() -> BlindedPath { unimplemented!() }
33 //! # fn create_another_blinded_path() -> BlindedPath { unimplemented!() }
34 //! #
35 //! # #[cfg(feature = "std")]
36 //! # fn build() -> Result<(), secp256k1::Error> {
37 //! let secp_ctx = Secp256k1::new();
38 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
39 //! let pubkey = PublicKey::from(keys);
40 //!
41 //! let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
42 //! let offer = OfferBuilder::new("coffee, large".to_string(), pubkey)
43 //!     .amount_msats(20_000)
44 //!     .supported_quantity(Quantity::Unbounded)
45 //!     .absolute_expiry(expiration.duration_since(SystemTime::UNIX_EPOCH).unwrap())
46 //!     .issuer("Foo Bar".to_string())
47 //!     .path(create_blinded_path())
48 //!     .path(create_another_blinded_path())
49 //!     .build()
50 //!     .unwrap();
51 //! # Ok(())
52 //! # }
53 //! ```
54
55 use bitcoin::blockdata::constants::ChainHash;
56 use bitcoin::network::constants::Network;
57 use bitcoin::secp256k1::PublicKey;
58 use core::num::NonZeroU64;
59 use core::time::Duration;
60 use crate::io;
61 use crate::ln::features::OfferFeatures;
62 use crate::ln::msgs::MAX_VALUE_MSAT;
63 use crate::onion_message::BlindedPath;
64 use crate::util::ser::{HighZeroBytesDroppedBigSize, WithoutLength, Writeable, Writer};
65 use crate::util::string::PrintableString;
66
67 use crate::prelude::*;
68
69 #[cfg(feature = "std")]
70 use std::time::SystemTime;
71
72 /// Builds an [`Offer`] for the "offer to be paid" flow.
73 ///
74 /// See [module-level documentation] for usage.
75 ///
76 /// [module-level documentation]: self
77 pub struct OfferBuilder {
78         offer: OfferContents,
79 }
80
81 impl OfferBuilder {
82         /// Creates a new builder for an offer setting the [`Offer::description`] and using the
83         /// [`Offer::signing_pubkey`] for signing invoices. The associated secret key must be remembered
84         /// while the offer is valid.
85         ///
86         /// Use a different pubkey per offer to avoid correlating offers.
87         pub fn new(description: String, signing_pubkey: PublicKey) -> Self {
88                 let offer = OfferContents {
89                         chains: None, metadata: None, amount: None, description,
90                         features: OfferFeatures::empty(), absolute_expiry: None, issuer: None, paths: None,
91                         supported_quantity: Quantity::one(), signing_pubkey: Some(signing_pubkey),
92                 };
93                 OfferBuilder { offer }
94         }
95
96         /// Adds the chain hash of the given [`Network`] to [`Offer::chains`]. If not called,
97         /// the chain hash of [`Network::Bitcoin`] is assumed to be the only one supported.
98         ///
99         /// See [`Offer::chains`] on how this relates to the payment currency.
100         ///
101         /// Successive calls to this method will add another chain hash.
102         pub fn chain(mut self, network: Network) -> Self {
103                 let chains = self.offer.chains.get_or_insert_with(Vec::new);
104                 let chain = ChainHash::using_genesis_block(network);
105                 if !chains.contains(&chain) {
106                         chains.push(chain);
107                 }
108
109                 self
110         }
111
112         /// Sets the [`Offer::metadata`].
113         ///
114         /// Successive calls to this method will override the previous setting.
115         pub fn metadata(mut self, metadata: Vec<u8>) -> Self {
116                 self.offer.metadata = Some(metadata);
117                 self
118         }
119
120         /// Sets the [`Offer::amount`] as an [`Amount::Bitcoin`].
121         ///
122         /// Successive calls to this method will override the previous setting.
123         pub fn amount_msats(mut self, amount_msats: u64) -> Self {
124                 self.amount(Amount::Bitcoin { amount_msats })
125         }
126
127         /// Sets the [`Offer::amount`].
128         ///
129         /// Successive calls to this method will override the previous setting.
130         fn amount(mut self, amount: Amount) -> Self {
131                 self.offer.amount = Some(amount);
132                 self
133         }
134
135         /// Sets the [`Offer::features`].
136         ///
137         /// Successive calls to this method will override the previous setting.
138         #[cfg(test)]
139         pub fn features(mut self, features: OfferFeatures) -> Self {
140                 self.offer.features = features;
141                 self
142         }
143
144         /// Sets the [`Offer::absolute_expiry`] as seconds since the Unix epoch. Any expiry that has
145         /// already passed is valid and can be checked for using [`Offer::is_expired`].
146         ///
147         /// Successive calls to this method will override the previous setting.
148         pub fn absolute_expiry(mut self, absolute_expiry: Duration) -> Self {
149                 self.offer.absolute_expiry = Some(absolute_expiry);
150                 self
151         }
152
153         /// Sets the [`Offer::issuer`].
154         ///
155         /// Successive calls to this method will override the previous setting.
156         pub fn issuer(mut self, issuer: String) -> Self {
157                 self.offer.issuer = Some(issuer);
158                 self
159         }
160
161         /// Adds a blinded path to [`Offer::paths`]. Must include at least one path if only connected by
162         /// private channels or if [`Offer::signing_pubkey`] is not a public node id.
163         ///
164         /// Successive calls to this method will add another blinded path. Caller is responsible for not
165         /// adding duplicate paths.
166         pub fn path(mut self, path: BlindedPath) -> Self {
167                 self.offer.paths.get_or_insert_with(Vec::new).push(path);
168                 self
169         }
170
171         /// Sets the quantity of items for [`Offer::supported_quantity`].
172         ///
173         /// Successive calls to this method will override the previous setting.
174         pub fn supported_quantity(mut self, quantity: Quantity) -> Self {
175                 self.offer.supported_quantity = quantity;
176                 self
177         }
178
179         /// Builds an [`Offer`] from the builder's settings.
180         pub fn build(mut self) -> Result<Offer, ()> {
181                 match self.offer.amount {
182                         Some(Amount::Bitcoin { amount_msats }) => {
183                                 if amount_msats > MAX_VALUE_MSAT {
184                                         return Err(());
185                                 }
186                         },
187                         Some(Amount::Currency { .. }) => unreachable!(),
188                         None => {},
189                 }
190
191                 if let Some(chains) = &self.offer.chains {
192                         if chains.len() == 1 && chains[0] == self.offer.implied_chain() {
193                                 self.offer.chains = None;
194                         }
195                 }
196
197                 let mut bytes = Vec::new();
198                 self.offer.write(&mut bytes).unwrap();
199
200                 Ok(Offer {
201                         bytes,
202                         contents: self.offer,
203                 })
204         }
205 }
206
207 /// An `Offer` is a potentially long-lived proposal for payment of a good or service.
208 ///
209 /// An offer is a precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
210 /// customer may request an `Invoice` for a specific quantity and using an amount sufficient to
211 /// cover that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
212 ///
213 /// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
214 /// latter.
215 ///
216 /// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
217 #[derive(Clone, Debug)]
218 pub struct Offer {
219         // The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
220         // fields.
221         bytes: Vec<u8>,
222         contents: OfferContents,
223 }
224
225 /// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
226 #[derive(Clone, Debug)]
227 pub(crate) struct OfferContents {
228         chains: Option<Vec<ChainHash>>,
229         metadata: Option<Vec<u8>>,
230         amount: Option<Amount>,
231         description: String,
232         features: OfferFeatures,
233         absolute_expiry: Option<Duration>,
234         issuer: Option<String>,
235         paths: Option<Vec<BlindedPath>>,
236         supported_quantity: Quantity,
237         signing_pubkey: Option<PublicKey>,
238 }
239
240 impl Offer {
241         // TODO: Return a slice once ChainHash has constants.
242         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
243         // - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
244         /// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
245         /// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
246         /// for the selected chain.
247         pub fn chains(&self) -> Vec<ChainHash> {
248                 self.contents.chains
249                         .as_ref()
250                         .cloned()
251                         .unwrap_or_else(|| vec![self.contents.implied_chain()])
252         }
253
254         // TODO: Link to corresponding method in `InvoiceRequest`.
255         /// Opaque bytes set by the originator. Useful for authentication and validating fields since it
256         /// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
257         pub fn metadata(&self) -> Option<&Vec<u8>> {
258                 self.contents.metadata.as_ref()
259         }
260
261         /// The minimum amount required for a successful payment of a single item.
262         pub fn amount(&self) -> Option<&Amount> {
263                 self.contents.amount.as_ref()
264         }
265
266         /// A complete description of the purpose of the payment. Intended to be displayed to the user
267         /// but with the caveat that it has not been verified in any way.
268         pub fn description(&self) -> PrintableString {
269                 PrintableString(&self.contents.description)
270         }
271
272         /// Features pertaining to the offer.
273         pub fn features(&self) -> &OfferFeatures {
274                 &self.contents.features
275         }
276
277         /// Duration since the Unix epoch when an invoice should no longer be requested.
278         ///
279         /// If `None`, the offer does not expire.
280         pub fn absolute_expiry(&self) -> Option<Duration> {
281                 self.contents.absolute_expiry
282         }
283
284         /// Whether the offer has expired.
285         #[cfg(feature = "std")]
286         pub fn is_expired(&self) -> bool {
287                 match self.absolute_expiry() {
288                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
289                                 Ok(elapsed) => elapsed > seconds_from_epoch,
290                                 Err(_) => false,
291                         },
292                         None => false,
293                 }
294         }
295
296         /// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
297         /// displayed to the user but with the caveat that it has not been verified in any way.
298         pub fn issuer(&self) -> Option<PrintableString> {
299                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
300         }
301
302         /// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
303         /// recipient privacy by obfuscating its node id.
304         pub fn paths(&self) -> &[BlindedPath] {
305                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
306         }
307
308         /// The quantity of items supported.
309         pub fn supported_quantity(&self) -> Quantity {
310                 self.contents.supported_quantity()
311         }
312
313         /// The public key used by the recipient to sign invoices.
314         pub fn signing_pubkey(&self) -> PublicKey {
315                 self.contents.signing_pubkey.unwrap()
316         }
317
318         #[cfg(test)]
319         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
320                 self.contents.as_tlv_stream()
321         }
322 }
323
324 impl OfferContents {
325         pub fn implied_chain(&self) -> ChainHash {
326                 ChainHash::using_genesis_block(Network::Bitcoin)
327         }
328
329         pub fn supported_quantity(&self) -> Quantity {
330                 self.supported_quantity
331         }
332
333         fn as_tlv_stream(&self) -> OfferTlvStreamRef {
334                 let (currency, amount) = match &self.amount {
335                         None => (None, None),
336                         Some(Amount::Bitcoin { amount_msats }) => (None, Some(*amount_msats)),
337                         Some(Amount::Currency { iso4217_code, amount }) => (
338                                 Some(iso4217_code), Some(*amount)
339                         ),
340                 };
341
342                 let features = {
343                         if self.features == OfferFeatures::empty() { None } else { Some(&self.features) }
344                 };
345
346                 OfferTlvStreamRef {
347                         chains: self.chains.as_ref(),
348                         metadata: self.metadata.as_ref(),
349                         currency,
350                         amount,
351                         description: Some(&self.description),
352                         features,
353                         absolute_expiry: self.absolute_expiry.map(|duration| duration.as_secs()),
354                         paths: self.paths.as_ref(),
355                         issuer: self.issuer.as_ref(),
356                         quantity_max: self.supported_quantity.to_tlv_record(),
357                         node_id: self.signing_pubkey.as_ref(),
358                 }
359         }
360 }
361
362 impl Writeable for OfferContents {
363         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
364                 self.as_tlv_stream().write(writer)
365         }
366 }
367
368 /// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
369 /// another currency.
370 #[derive(Clone, Debug, PartialEq)]
371 pub enum Amount {
372         /// An amount of bitcoin.
373         Bitcoin {
374                 /// The amount in millisatoshi.
375                 amount_msats: u64,
376         },
377         /// An amount of currency specified using ISO 4712.
378         Currency {
379                 /// The currency that the amount is denominated in.
380                 iso4217_code: CurrencyCode,
381                 /// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
382                 amount: u64,
383         },
384 }
385
386 /// An ISO 4712 three-letter currency code (e.g., USD).
387 pub type CurrencyCode = [u8; 3];
388
389 /// Quantity of items supported by an [`Offer`].
390 #[derive(Clone, Copy, Debug, PartialEq)]
391 pub enum Quantity {
392         /// Up to a specific number of items (inclusive).
393         Bounded(NonZeroU64),
394         /// One or more items.
395         Unbounded,
396 }
397
398 impl Quantity {
399         fn one() -> Self {
400                 Quantity::Bounded(NonZeroU64::new(1).unwrap())
401         }
402
403         fn to_tlv_record(&self) -> Option<u64> {
404                 match self {
405                         Quantity::Bounded(n) => {
406                                 let n = n.get();
407                                 if n == 1 { None } else { Some(n) }
408                         },
409                         Quantity::Unbounded => Some(0),
410                 }
411         }
412 }
413
414 tlv_stream!(OfferTlvStream, OfferTlvStreamRef, {
415         (2, chains: (Vec<ChainHash>, WithoutLength)),
416         (4, metadata: (Vec<u8>, WithoutLength)),
417         (6, currency: CurrencyCode),
418         (8, amount: (u64, HighZeroBytesDroppedBigSize)),
419         (10, description: (String, WithoutLength)),
420         (12, features: OfferFeatures),
421         (14, absolute_expiry: (u64, HighZeroBytesDroppedBigSize)),
422         (16, paths: (Vec<BlindedPath>, WithoutLength)),
423         (18, issuer: (String, WithoutLength)),
424         (20, quantity_max: (u64, HighZeroBytesDroppedBigSize)),
425         (22, node_id: PublicKey),
426 });
427
428 #[cfg(test)]
429 mod tests {
430         use super::{Amount, OfferBuilder, Quantity};
431
432         use bitcoin::blockdata::constants::ChainHash;
433         use bitcoin::network::constants::Network;
434         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
435         use core::num::NonZeroU64;
436         use core::time::Duration;
437         use crate::ln::features::OfferFeatures;
438         use crate::ln::msgs::MAX_VALUE_MSAT;
439         use crate::onion_message::{BlindedHop, BlindedPath};
440         use crate::util::ser::Writeable;
441         use crate::util::string::PrintableString;
442
443         fn pubkey(byte: u8) -> PublicKey {
444                 let secp_ctx = Secp256k1::new();
445                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
446         }
447
448         fn privkey(byte: u8) -> SecretKey {
449                 SecretKey::from_slice(&[byte; 32]).unwrap()
450         }
451
452         #[test]
453         fn builds_offer_with_defaults() {
454                 let offer = OfferBuilder::new("foo".into(), pubkey(42)).build().unwrap();
455                 let tlv_stream = offer.as_tlv_stream();
456                 let mut buffer = Vec::new();
457                 offer.contents.write(&mut buffer).unwrap();
458
459                 assert_eq!(offer.bytes, buffer.as_slice());
460                 assert_eq!(offer.chains(), vec![ChainHash::using_genesis_block(Network::Bitcoin)]);
461                 assert_eq!(offer.metadata(), None);
462                 assert_eq!(offer.amount(), None);
463                 assert_eq!(offer.description(), PrintableString("foo"));
464                 assert_eq!(offer.features(), &OfferFeatures::empty());
465                 assert_eq!(offer.absolute_expiry(), None);
466                 #[cfg(feature = "std")]
467                 assert!(!offer.is_expired());
468                 assert_eq!(offer.paths(), &[]);
469                 assert_eq!(offer.issuer(), None);
470                 assert_eq!(offer.supported_quantity(), Quantity::one());
471                 assert_eq!(offer.signing_pubkey(), pubkey(42));
472
473                 assert_eq!(tlv_stream.chains, None);
474                 assert_eq!(tlv_stream.metadata, None);
475                 assert_eq!(tlv_stream.currency, None);
476                 assert_eq!(tlv_stream.amount, None);
477                 assert_eq!(tlv_stream.description, Some(&String::from("foo")));
478                 assert_eq!(tlv_stream.features, None);
479                 assert_eq!(tlv_stream.absolute_expiry, None);
480                 assert_eq!(tlv_stream.paths, None);
481                 assert_eq!(tlv_stream.issuer, None);
482                 assert_eq!(tlv_stream.quantity_max, None);
483                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
484         }
485
486         #[test]
487         fn builds_offer_with_chains() {
488                 let mainnet = ChainHash::using_genesis_block(Network::Bitcoin);
489                 let testnet = ChainHash::using_genesis_block(Network::Testnet);
490
491                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
492                         .chain(Network::Bitcoin)
493                         .build()
494                         .unwrap();
495                 assert_eq!(offer.chains(), vec![mainnet]);
496                 assert_eq!(offer.as_tlv_stream().chains, None);
497
498                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
499                         .chain(Network::Testnet)
500                         .build()
501                         .unwrap();
502                 assert_eq!(offer.chains(), vec![testnet]);
503                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
504
505                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
506                         .chain(Network::Testnet)
507                         .chain(Network::Testnet)
508                         .build()
509                         .unwrap();
510                 assert_eq!(offer.chains(), vec![testnet]);
511                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![testnet]));
512
513                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
514                         .chain(Network::Bitcoin)
515                         .chain(Network::Testnet)
516                         .build()
517                         .unwrap();
518                 assert_eq!(offer.chains(), vec![mainnet, testnet]);
519                 assert_eq!(offer.as_tlv_stream().chains, Some(&vec![mainnet, testnet]));
520         }
521
522         #[test]
523         fn builds_offer_with_metadata() {
524                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
525                         .metadata(vec![42; 32])
526                         .build()
527                         .unwrap();
528                 assert_eq!(offer.metadata(), Some(&vec![42; 32]));
529                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![42; 32]));
530
531                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
532                         .metadata(vec![42; 32])
533                         .metadata(vec![43; 32])
534                         .build()
535                         .unwrap();
536                 assert_eq!(offer.metadata(), Some(&vec![43; 32]));
537                 assert_eq!(offer.as_tlv_stream().metadata, Some(&vec![43; 32]));
538         }
539
540         #[test]
541         fn builds_offer_with_amount() {
542                 let bitcoin_amount = Amount::Bitcoin { amount_msats: 1000 };
543                 let currency_amount = Amount::Currency { iso4217_code: *b"USD", amount: 10 };
544
545                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
546                         .amount_msats(1000)
547                         .build()
548                         .unwrap();
549                 let tlv_stream = offer.as_tlv_stream();
550                 assert_eq!(offer.amount(), Some(&bitcoin_amount));
551                 assert_eq!(tlv_stream.amount, Some(1000));
552                 assert_eq!(tlv_stream.currency, None);
553
554                 let builder = OfferBuilder::new("foo".into(), pubkey(42))
555                         .amount(currency_amount.clone());
556                 let tlv_stream = builder.offer.as_tlv_stream();
557                 assert_eq!(builder.offer.amount, Some(currency_amount.clone()));
558                 assert_eq!(tlv_stream.amount, Some(10));
559                 assert_eq!(tlv_stream.currency, Some(b"USD"));
560
561                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
562                         .amount(currency_amount.clone())
563                         .amount(bitcoin_amount.clone())
564                         .build()
565                         .unwrap();
566                 let tlv_stream = offer.as_tlv_stream();
567                 assert_eq!(tlv_stream.amount, Some(1000));
568                 assert_eq!(tlv_stream.currency, None);
569
570                 let invalid_amount = Amount::Bitcoin { amount_msats: MAX_VALUE_MSAT + 1 };
571                 match OfferBuilder::new("foo".into(), pubkey(42)).amount(invalid_amount).build() {
572                         Ok(_) => panic!("expected error"),
573                         Err(e) => assert_eq!(e, ()),
574                 }
575         }
576
577         #[test]
578         fn builds_offer_with_features() {
579                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
580                         .features(OfferFeatures::unknown())
581                         .build()
582                         .unwrap();
583                 assert_eq!(offer.features(), &OfferFeatures::unknown());
584                 assert_eq!(offer.as_tlv_stream().features, Some(&OfferFeatures::unknown()));
585
586                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
587                         .features(OfferFeatures::unknown())
588                         .features(OfferFeatures::empty())
589                         .build()
590                         .unwrap();
591                 assert_eq!(offer.features(), &OfferFeatures::empty());
592                 assert_eq!(offer.as_tlv_stream().features, None);
593         }
594
595         #[test]
596         fn builds_offer_with_absolute_expiry() {
597                 let future_expiry = Duration::from_secs(u64::max_value());
598                 let past_expiry = Duration::from_secs(0);
599
600                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
601                         .absolute_expiry(future_expiry)
602                         .build()
603                         .unwrap();
604                 #[cfg(feature = "std")]
605                 assert!(!offer.is_expired());
606                 assert_eq!(offer.absolute_expiry(), Some(future_expiry));
607                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(future_expiry.as_secs()));
608
609                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
610                         .absolute_expiry(future_expiry)
611                         .absolute_expiry(past_expiry)
612                         .build()
613                         .unwrap();
614                 #[cfg(feature = "std")]
615                 assert!(offer.is_expired());
616                 assert_eq!(offer.absolute_expiry(), Some(past_expiry));
617                 assert_eq!(offer.as_tlv_stream().absolute_expiry, Some(past_expiry.as_secs()));
618         }
619
620         #[test]
621         fn builds_offer_with_paths() {
622                 let paths = vec![
623                         BlindedPath {
624                                 introduction_node_id: pubkey(40),
625                                 blinding_point: pubkey(41),
626                                 blinded_hops: vec![
627                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
628                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
629                                 ],
630                         },
631                         BlindedPath {
632                                 introduction_node_id: pubkey(40),
633                                 blinding_point: pubkey(41),
634                                 blinded_hops: vec![
635                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
636                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
637                                 ],
638                         },
639                 ];
640
641                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
642                         .path(paths[0].clone())
643                         .path(paths[1].clone())
644                         .build()
645                         .unwrap();
646                 let tlv_stream = offer.as_tlv_stream();
647                 assert_eq!(offer.paths(), paths.as_slice());
648                 assert_eq!(offer.signing_pubkey(), pubkey(42));
649                 assert_ne!(pubkey(42), pubkey(44));
650                 assert_eq!(tlv_stream.paths, Some(&paths));
651                 assert_eq!(tlv_stream.node_id, Some(&pubkey(42)));
652         }
653
654         #[test]
655         fn builds_offer_with_issuer() {
656                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
657                         .issuer("bar".into())
658                         .build()
659                         .unwrap();
660                 assert_eq!(offer.issuer(), Some(PrintableString("bar")));
661                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("bar")));
662
663                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
664                         .issuer("bar".into())
665                         .issuer("baz".into())
666                         .build()
667                         .unwrap();
668                 assert_eq!(offer.issuer(), Some(PrintableString("baz")));
669                 assert_eq!(offer.as_tlv_stream().issuer, Some(&String::from("baz")));
670         }
671
672         #[test]
673         fn builds_offer_with_supported_quantity() {
674                 let ten = NonZeroU64::new(10).unwrap();
675
676                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
677                         .supported_quantity(Quantity::one())
678                         .build()
679                         .unwrap();
680                 let tlv_stream = offer.as_tlv_stream();
681                 assert_eq!(offer.supported_quantity(), Quantity::one());
682                 assert_eq!(tlv_stream.quantity_max, None);
683
684                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
685                         .supported_quantity(Quantity::Unbounded)
686                         .build()
687                         .unwrap();
688                 let tlv_stream = offer.as_tlv_stream();
689                 assert_eq!(offer.supported_quantity(), Quantity::Unbounded);
690                 assert_eq!(tlv_stream.quantity_max, Some(0));
691
692                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
693                         .supported_quantity(Quantity::Bounded(ten))
694                         .build()
695                         .unwrap();
696                 let tlv_stream = offer.as_tlv_stream();
697                 assert_eq!(offer.supported_quantity(), Quantity::Bounded(ten));
698                 assert_eq!(tlv_stream.quantity_max, Some(10));
699
700                 let offer = OfferBuilder::new("foo".into(), pubkey(42))
701                         .supported_quantity(Quantity::Bounded(ten))
702                         .supported_quantity(Quantity::one())
703                         .build()
704                         .unwrap();
705                 let tlv_stream = offer.as_tlv_stream();
706                 assert_eq!(offer.supported_quantity(), Quantity::one());
707                 assert_eq!(tlv_stream.quantity_max, None);
708         }
709 }