Derive traits for InvoiceRequest and Invoice
[rust-lightning] / lightning / src / offers / invoice.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 `invoice` messages.
11 //!
12 //! An [`Invoice`] can be built from a parsed [`InvoiceRequest`] for the "offer to be paid" flow or
13 //! from a [`Refund`] as an "offer for money" flow. The expected recipient of the payment then sends
14 //! the invoice to the intended payer, who will then pay it.
15 //!
16 //! The payment recipient must include a [`PaymentHash`], so as to reveal the preimage upon payment
17 //! receipt, and one or more [`BlindedPath`]s for the payer to use when sending the payment.
18 //!
19 //! ```
20 //! extern crate bitcoin;
21 //! extern crate lightning;
22 //!
23 //! use bitcoin::hashes::Hash;
24 //! use bitcoin::secp256k1::{KeyPair, PublicKey, Secp256k1, SecretKey};
25 //! use core::convert::{Infallible, TryFrom};
26 //! use lightning::offers::invoice_request::InvoiceRequest;
27 //! use lightning::offers::refund::Refund;
28 //! use lightning::util::ser::Writeable;
29 //!
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::onion_message::BlindedPath;
33 //! #
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
36 //! #
37 //! # fn parse_invoice_request(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
38 //! let payment_paths = create_payment_paths();
39 //! let payment_hash = create_payment_hash();
40 //! let secp_ctx = Secp256k1::new();
41 //! let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
42 //! let pubkey = PublicKey::from(keys);
43 //! let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
44 //! let mut buffer = Vec::new();
45 //!
46 //! // Invoice for the "offer to be paid" flow.
47 //! InvoiceRequest::try_from(bytes)?
48 #![cfg_attr(feature = "std", doc = "
49     .respond_with(payment_paths, payment_hash)?
50 ")]
51 #![cfg_attr(not(feature = "std"), doc = "
52     .respond_with_no_std(payment_paths, payment_hash, core::time::Duration::from_secs(0))?
53 ")]
54 //!     .relative_expiry(3600)
55 //!     .allow_mpp()
56 //!     .fallback_v0_p2wpkh(&wpubkey_hash)
57 //!     .build()?
58 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
59 //!     .expect("failed verifying signature")
60 //!     .write(&mut buffer)
61 //!     .unwrap();
62 //! # Ok(())
63 //! # }
64 //!
65 //! # fn parse_refund(bytes: Vec<u8>) -> Result<(), lightning::offers::parse::ParseError> {
66 //! # let payment_paths = create_payment_paths();
67 //! # let payment_hash = create_payment_hash();
68 //! # let secp_ctx = Secp256k1::new();
69 //! # let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32])?);
70 //! # let pubkey = PublicKey::from(keys);
71 //! # let wpubkey_hash = bitcoin::util::key::PublicKey::new(pubkey).wpubkey_hash().unwrap();
72 //! # let mut buffer = Vec::new();
73 //!
74 //! // Invoice for the "offer for money" flow.
75 //! "lnr1qcp4256ypq"
76 //!     .parse::<Refund>()?
77 #![cfg_attr(feature = "std", doc = "
78     .respond_with(payment_paths, payment_hash, pubkey)?
79 ")]
80 #![cfg_attr(not(feature = "std"), doc = "
81     .respond_with_no_std(payment_paths, payment_hash, pubkey, core::time::Duration::from_secs(0))?
82 ")]
83 //!     .relative_expiry(3600)
84 //!     .allow_mpp()
85 //!     .fallback_v0_p2wpkh(&wpubkey_hash)
86 //!     .build()?
87 //!     .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
88 //!     .expect("failed verifying signature")
89 //!     .write(&mut buffer)
90 //!     .unwrap();
91 //! # Ok(())
92 //! # }
93 //!
94 //! ```
95
96 use bitcoin::blockdata::constants::ChainHash;
97 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
98 use bitcoin::hashes::Hash;
99 use bitcoin::network::constants::Network;
100 use bitcoin::secp256k1::{Message, PublicKey};
101 use bitcoin::secp256k1::schnorr::Signature;
102 use bitcoin::util::address::{Address, Payload, WitnessVersion};
103 use bitcoin::util::schnorr::TweakedPublicKey;
104 use core::convert::TryFrom;
105 use core::time::Duration;
106 use crate::io;
107 use crate::ln::PaymentHash;
108 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
109 use crate::ln::msgs::DecodeError;
110 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
111 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
112 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
113 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
114 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
115 use crate::offers::refund::{Refund, RefundContents};
116 use crate::onion_message::BlindedPath;
117 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
118
119 use crate::prelude::*;
120
121 #[cfg(feature = "std")]
122 use std::time::SystemTime;
123
124 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
125
126 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
127
128 /// Builds an [`Invoice`] from either:
129 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
130 /// - a [`Refund`] for the "offer for money" flow.
131 ///
132 /// See [module-level documentation] for usage.
133 ///
134 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
135 /// [`Refund`]: crate::offers::refund::Refund
136 /// [module-level documentation]: self
137 pub struct InvoiceBuilder<'a> {
138         invreq_bytes: &'a Vec<u8>,
139         invoice: InvoiceContents,
140 }
141
142 impl<'a> InvoiceBuilder<'a> {
143         pub(super) fn for_offer(
144                 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
145                 created_at: Duration, payment_hash: PaymentHash
146         ) -> Result<Self, SemanticError> {
147                 let amount_msats = match invoice_request.amount_msats() {
148                         Some(amount_msats) => amount_msats,
149                         None => match invoice_request.contents.offer.amount() {
150                                 Some(Amount::Bitcoin { amount_msats }) => {
151                                         amount_msats * invoice_request.quantity().unwrap_or(1)
152                                 },
153                                 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
154                                 None => return Err(SemanticError::MissingAmount),
155                         },
156                 };
157
158                 let contents = InvoiceContents::ForOffer {
159                         invoice_request: invoice_request.contents.clone(),
160                         fields: InvoiceFields {
161                                 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
162                                 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
163                                 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
164                         },
165                 };
166
167                 Self::new(&invoice_request.bytes, contents)
168         }
169
170         pub(super) fn for_refund(
171                 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
172                 payment_hash: PaymentHash, signing_pubkey: PublicKey
173         ) -> Result<Self, SemanticError> {
174                 let contents = InvoiceContents::ForRefund {
175                         refund: refund.contents.clone(),
176                         fields: InvoiceFields {
177                                 payment_paths, created_at, relative_expiry: None, payment_hash,
178                                 amount_msats: refund.amount_msats(), fallbacks: None,
179                                 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
180                         },
181                 };
182
183                 Self::new(&refund.bytes, contents)
184         }
185
186         fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
187                 if contents.fields().payment_paths.is_empty() {
188                         return Err(SemanticError::MissingPaths);
189                 }
190
191                 Ok(Self { invreq_bytes, invoice: contents })
192         }
193
194         /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
195         /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
196         ///
197         /// Successive calls to this method will override the previous setting.
198         pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
199                 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
200                 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
201                 self
202         }
203
204         /// Adds a P2WSH address to [`Invoice::fallbacks`].
205         ///
206         /// Successive calls to this method will add another address. Caller is responsible for not
207         /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
208         pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
209                 let address = FallbackAddress {
210                         version: WitnessVersion::V0.to_num(),
211                         program: Vec::from(&script_hash.into_inner()[..]),
212                 };
213                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
214                 self
215         }
216
217         /// Adds a P2WPKH address to [`Invoice::fallbacks`].
218         ///
219         /// Successive calls to this method will add another address. Caller is responsible for not
220         /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
221         pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
222                 let address = FallbackAddress {
223                         version: WitnessVersion::V0.to_num(),
224                         program: Vec::from(&pubkey_hash.into_inner()[..]),
225                 };
226                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
227                 self
228         }
229
230         /// Adds a P2TR address to [`Invoice::fallbacks`].
231         ///
232         /// Successive calls to this method will add another address. Caller is responsible for not
233         /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
234         pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
235                 let address = FallbackAddress {
236                         version: WitnessVersion::V1.to_num(),
237                         program: Vec::from(&output_key.serialize()[..]),
238                 };
239                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
240                 self
241         }
242
243         /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
244         pub fn allow_mpp(mut self) -> Self {
245                 self.invoice.fields_mut().features.set_basic_mpp_optional();
246                 self
247         }
248
249         /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
250         /// [`UnsignedInvoice::sign`].
251         pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
252                 #[cfg(feature = "std")] {
253                         if self.invoice.is_offer_or_refund_expired() {
254                                 return Err(SemanticError::AlreadyExpired);
255                         }
256                 }
257
258                 let InvoiceBuilder { invreq_bytes, invoice } = self;
259                 Ok(UnsignedInvoice { invreq_bytes, invoice })
260         }
261 }
262
263 /// A semantically valid [`Invoice`] that hasn't been signed.
264 pub struct UnsignedInvoice<'a> {
265         invreq_bytes: &'a Vec<u8>,
266         invoice: InvoiceContents,
267 }
268
269 impl<'a> UnsignedInvoice<'a> {
270         /// Signs the invoice using the given function.
271         pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
272         where
273                 F: FnOnce(&Message) -> Result<Signature, E>
274         {
275                 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
276                 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
277                 // `RefundContents`.
278                 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
279                 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
280                 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
281
282                 let mut bytes = Vec::new();
283                 unsigned_tlv_stream.write(&mut bytes).unwrap();
284
285                 let pubkey = self.invoice.fields().signing_pubkey;
286                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
287
288                 // Append the signature TLV record to the bytes.
289                 let signature_tlv_stream = SignatureTlvStreamRef {
290                         signature: Some(&signature),
291                 };
292                 signature_tlv_stream.write(&mut bytes).unwrap();
293
294                 Ok(Invoice {
295                         bytes,
296                         contents: self.invoice,
297                         signature,
298                 })
299         }
300 }
301
302 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
303 ///
304 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
305 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
306 ///
307 /// [`Offer`]: crate::offers::offer::Offer
308 /// [`Refund`]: crate::offers::refund::Refund
309 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
310 #[derive(Clone, Debug, PartialEq)]
311 pub struct Invoice {
312         bytes: Vec<u8>,
313         contents: InvoiceContents,
314         signature: Signature,
315 }
316
317 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
318 ///
319 /// [`Offer`]: crate::offers::offer::Offer
320 /// [`Refund`]: crate::offers::refund::Refund
321 #[derive(Clone, Debug, PartialEq)]
322 enum InvoiceContents {
323         /// Contents for an [`Invoice`] corresponding to an [`Offer`].
324         ///
325         /// [`Offer`]: crate::offers::offer::Offer
326         ForOffer {
327                 invoice_request: InvoiceRequestContents,
328                 fields: InvoiceFields,
329         },
330         /// Contents for an [`Invoice`] corresponding to a [`Refund`].
331         ///
332         /// [`Refund`]: crate::offers::refund::Refund
333         ForRefund {
334                 refund: RefundContents,
335                 fields: InvoiceFields,
336         },
337 }
338
339 /// Invoice-specific fields for an `invoice` message.
340 #[derive(Clone, Debug, PartialEq)]
341 struct InvoiceFields {
342         payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
343         created_at: Duration,
344         relative_expiry: Option<Duration>,
345         payment_hash: PaymentHash,
346         amount_msats: u64,
347         fallbacks: Option<Vec<FallbackAddress>>,
348         features: Bolt12InvoiceFeatures,
349         signing_pubkey: PublicKey,
350 }
351
352 impl Invoice {
353         /// Paths to the recipient originating from publicly reachable nodes, including information
354         /// needed for routing payments across them.
355         ///
356         /// Blinded paths provide recipient privacy by obfuscating its node id. Note, however, that this
357         /// privacy is lost if a public node id is used for [`Invoice::signing_pubkey`].
358         pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
359                 &self.contents.fields().payment_paths[..]
360         }
361
362         /// Duration since the Unix epoch when the invoice was created.
363         pub fn created_at(&self) -> Duration {
364                 self.contents.fields().created_at
365         }
366
367         /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
368         /// longer be paid.
369         pub fn relative_expiry(&self) -> Duration {
370                 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
371         }
372
373         /// Whether the invoice has expired.
374         #[cfg(feature = "std")]
375         pub fn is_expired(&self) -> bool {
376                 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
377                 match absolute_expiry {
378                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
379                                 Ok(elapsed) => elapsed > seconds_from_epoch,
380                                 Err(_) => false,
381                         },
382                         None => false,
383                 }
384         }
385
386         /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
387         pub fn payment_hash(&self) -> PaymentHash {
388                 self.contents.fields().payment_hash
389         }
390
391         /// The minimum amount required for a successful payment of the invoice.
392         pub fn amount_msats(&self) -> u64 {
393                 self.contents.fields().amount_msats
394         }
395
396         /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
397         /// least-preferred.
398         pub fn fallbacks(&self) -> Vec<Address> {
399                 let network = match self.network() {
400                         None => return Vec::new(),
401                         Some(network) => network,
402                 };
403
404                 let to_valid_address = |address: &FallbackAddress| {
405                         let version = match WitnessVersion::try_from(address.version) {
406                                 Ok(version) => version,
407                                 Err(_) => return None,
408                         };
409
410                         let program = &address.program;
411                         if program.len() < 2 || program.len() > 40 {
412                                 return None;
413                         }
414
415                         let address = Address {
416                                 payload: Payload::WitnessProgram {
417                                         version,
418                                         program: address.program.clone(),
419                                 },
420                                 network,
421                         };
422
423                         if !address.is_standard() && version == WitnessVersion::V0 {
424                                 return None;
425                         }
426
427                         Some(address)
428                 };
429
430                 self.contents.fields().fallbacks
431                         .as_ref()
432                         .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
433                         .unwrap_or_else(Vec::new)
434         }
435
436         fn network(&self) -> Option<Network> {
437                 let chain = self.contents.chain();
438                 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
439                         Some(Network::Bitcoin)
440                 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
441                         Some(Network::Testnet)
442                 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
443                         Some(Network::Signet)
444                 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
445                         Some(Network::Regtest)
446                 } else {
447                         None
448                 }
449         }
450
451         /// Features pertaining to paying an invoice.
452         pub fn features(&self) -> &Bolt12InvoiceFeatures {
453                 &self.contents.fields().features
454         }
455
456         /// The public key used to sign invoices.
457         pub fn signing_pubkey(&self) -> PublicKey {
458                 self.contents.fields().signing_pubkey
459         }
460
461         /// Signature of the invoice using [`Invoice::signing_pubkey`].
462         pub fn signature(&self) -> Signature {
463                 self.signature
464         }
465
466         #[cfg(test)]
467         fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef {
468                 let (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream) =
469                         self.contents.as_tlv_stream();
470                 let signature_tlv_stream = SignatureTlvStreamRef {
471                         signature: Some(&self.signature),
472                 };
473                 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
474                  signature_tlv_stream)
475         }
476 }
477
478 impl InvoiceContents {
479         /// Whether the original offer or refund has expired.
480         #[cfg(feature = "std")]
481         fn is_offer_or_refund_expired(&self) -> bool {
482                 match self {
483                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
484                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
485                 }
486         }
487
488         fn chain(&self) -> ChainHash {
489                 match self {
490                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
491                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
492                 }
493         }
494
495         fn fields(&self) -> &InvoiceFields {
496                 match self {
497                         InvoiceContents::ForOffer { fields, .. } => fields,
498                         InvoiceContents::ForRefund { fields, .. } => fields,
499                 }
500         }
501
502         fn fields_mut(&mut self) -> &mut InvoiceFields {
503                 match self {
504                         InvoiceContents::ForOffer { fields, .. } => fields,
505                         InvoiceContents::ForRefund { fields, .. } => fields,
506                 }
507         }
508
509         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
510                 let (payer, offer, invoice_request) = match self {
511                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
512                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
513                 };
514                 let invoice = self.fields().as_tlv_stream();
515
516                 (payer, offer, invoice_request, invoice)
517         }
518 }
519
520 impl InvoiceFields {
521         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
522                 let features = {
523                         if self.features == Bolt12InvoiceFeatures::empty() { None }
524                         else { Some(&self.features) }
525                 };
526
527                 InvoiceTlvStreamRef {
528                         paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
529                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
530                         created_at: Some(self.created_at.as_secs()),
531                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
532                         payment_hash: Some(&self.payment_hash),
533                         amount: Some(self.amount_msats),
534                         fallbacks: self.fallbacks.as_ref(),
535                         features,
536                         node_id: Some(&self.signing_pubkey),
537                 }
538         }
539 }
540
541 impl Writeable for Invoice {
542         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
543                 WithoutLength(&self.bytes).write(writer)
544         }
545 }
546
547 impl Writeable for InvoiceContents {
548         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
549                 self.as_tlv_stream().write(writer)
550         }
551 }
552
553 impl TryFrom<Vec<u8>> for Invoice {
554         type Error = ParseError;
555
556         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
557                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
558                 Invoice::try_from(parsed_invoice)
559         }
560 }
561
562 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
563         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
564         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
565         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
566         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
567         (168, payment_hash: PaymentHash),
568         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
569         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
570         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
571         (176, node_id: PublicKey),
572 });
573
574 type BlindedPathIter<'a> = core::iter::Map<
575         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
576         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
577 >;
578
579 type BlindedPayInfoIter<'a> = core::iter::Map<
580         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
581         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
582 >;
583
584 /// Information needed to route a payment across a [`BlindedPath`].
585 #[derive(Clone, Debug, PartialEq)]
586 pub struct BlindedPayInfo {
587         /// Base fee charged (in millisatoshi) for the entire blinded path.
588         pub fee_base_msat: u32,
589
590         /// Liquidity fee charged (in millionths of the amount transferred) for the entire blinded path
591         /// (i.e., 10,000 is 1%).
592         pub fee_proportional_millionths: u32,
593
594         /// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for the entire blinded
595         /// path.
596         pub cltv_expiry_delta: u16,
597
598         /// The minimum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
599         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
600         /// seen by the recipient.
601         pub htlc_minimum_msat: u64,
602
603         /// The maximum HTLC value (in millisatoshi) that is acceptable to all channel peers on the
604         /// blinded path from the introduction node to the recipient, accounting for any fees, i.e., as
605         /// seen by the recipient.
606         pub htlc_maximum_msat: u64,
607
608         /// Features set in `encrypted_data_tlv` for the `encrypted_recipient_data` TLV record in an
609         /// onion payload.
610         pub features: BlindedHopFeatures,
611 }
612
613 impl_writeable!(BlindedPayInfo, {
614         fee_base_msat,
615         fee_proportional_millionths,
616         cltv_expiry_delta,
617         htlc_minimum_msat,
618         htlc_maximum_msat,
619         features
620 });
621
622 /// Wire representation for an on-chain fallback address.
623 #[derive(Clone, Debug, PartialEq)]
624 pub(super) struct FallbackAddress {
625         version: u8,
626         program: Vec<u8>,
627 }
628
629 impl_writeable!(FallbackAddress, { version, program });
630
631 type FullInvoiceTlvStream =
632         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
633
634 #[cfg(test)]
635 type FullInvoiceTlvStreamRef<'a> = (
636         PayerTlvStreamRef<'a>,
637         OfferTlvStreamRef<'a>,
638         InvoiceRequestTlvStreamRef<'a>,
639         InvoiceTlvStreamRef<'a>,
640         SignatureTlvStreamRef<'a>,
641 );
642
643 impl SeekReadable for FullInvoiceTlvStream {
644         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
645                 let payer = SeekReadable::read(r)?;
646                 let offer = SeekReadable::read(r)?;
647                 let invoice_request = SeekReadable::read(r)?;
648                 let invoice = SeekReadable::read(r)?;
649                 let signature = SeekReadable::read(r)?;
650
651                 Ok((payer, offer, invoice_request, invoice, signature))
652         }
653 }
654
655 type PartialInvoiceTlvStream =
656         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
657
658 type PartialInvoiceTlvStreamRef<'a> = (
659         PayerTlvStreamRef<'a>,
660         OfferTlvStreamRef<'a>,
661         InvoiceRequestTlvStreamRef<'a>,
662         InvoiceTlvStreamRef<'a>,
663 );
664
665 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
666         type Error = ParseError;
667
668         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
669                 let ParsedMessage { bytes, tlv_stream } = invoice;
670                 let (
671                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
672                         SignatureTlvStream { signature },
673                 ) = tlv_stream;
674                 let contents = InvoiceContents::try_from(
675                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
676                 )?;
677
678                 let signature = match signature {
679                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
680                         Some(signature) => signature,
681                 };
682                 let pubkey = contents.fields().signing_pubkey;
683                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
684
685                 Ok(Invoice { bytes, contents, signature })
686         }
687 }
688
689 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
690         type Error = SemanticError;
691
692         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
693                 let (
694                         payer_tlv_stream,
695                         offer_tlv_stream,
696                         invoice_request_tlv_stream,
697                         InvoiceTlvStream {
698                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
699                                 features, node_id,
700                         },
701                 ) = tlv_stream;
702
703                 let payment_paths = match (paths, blindedpay) {
704                         (None, _) => return Err(SemanticError::MissingPaths),
705                         (_, None) => return Err(SemanticError::InvalidPayInfo),
706                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
707                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
708                                 return Err(SemanticError::InvalidPayInfo);
709                         },
710                         (Some(paths), Some(blindedpay)) => {
711                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
712                         },
713                 };
714
715                 let created_at = match created_at {
716                         None => return Err(SemanticError::MissingCreationTime),
717                         Some(timestamp) => Duration::from_secs(timestamp),
718                 };
719
720                 let relative_expiry = relative_expiry
721                         .map(Into::<u64>::into)
722                         .map(Duration::from_secs);
723
724                 let payment_hash = match payment_hash {
725                         None => return Err(SemanticError::MissingPaymentHash),
726                         Some(payment_hash) => payment_hash,
727                 };
728
729                 let amount_msats = match amount {
730                         None => return Err(SemanticError::MissingAmount),
731                         Some(amount) => amount,
732                 };
733
734                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
735
736                 let signing_pubkey = match node_id {
737                         None => return Err(SemanticError::MissingSigningPubkey),
738                         Some(node_id) => node_id,
739                 };
740
741                 let fields = InvoiceFields {
742                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
743                         features, signing_pubkey,
744                 };
745
746                 match offer_tlv_stream.node_id {
747                         Some(expected_signing_pubkey) => {
748                                 if fields.signing_pubkey != expected_signing_pubkey {
749                                         return Err(SemanticError::InvalidSigningPubkey);
750                                 }
751
752                                 let invoice_request = InvoiceRequestContents::try_from(
753                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
754                                 )?;
755                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
756                         },
757                         None => {
758                                 let refund = RefundContents::try_from(
759                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
760                                 )?;
761                                 Ok(InvoiceContents::ForRefund { refund, fields })
762                         },
763                 }
764         }
765 }
766
767 #[cfg(test)]
768 mod tests {
769         use super::{DEFAULT_RELATIVE_EXPIRY, BlindedPayInfo, FallbackAddress, FullInvoiceTlvStreamRef, Invoice, InvoiceTlvStreamRef, SIGNATURE_TAG};
770
771         use bitcoin::blockdata::script::Script;
772         use bitcoin::hashes::Hash;
773         use bitcoin::network::constants::Network;
774         use bitcoin::secp256k1::{KeyPair, Message, PublicKey, Secp256k1, SecretKey, XOnlyPublicKey, self};
775         use bitcoin::secp256k1::schnorr::Signature;
776         use bitcoin::util::address::{Address, Payload, WitnessVersion};
777         use bitcoin::util::schnorr::TweakedPublicKey;
778         use core::convert::{Infallible, TryFrom};
779         use core::time::Duration;
780         use crate::ln::PaymentHash;
781         use crate::ln::msgs::DecodeError;
782         use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
783         use crate::offers::invoice_request::InvoiceRequestTlvStreamRef;
784         use crate::offers::merkle::{SignError, SignatureTlvStreamRef, self};
785         use crate::offers::offer::{OfferBuilder, OfferTlvStreamRef};
786         use crate::offers::parse::{ParseError, SemanticError};
787         use crate::offers::payer::PayerTlvStreamRef;
788         use crate::offers::refund::RefundBuilder;
789         use crate::onion_message::{BlindedHop, BlindedPath};
790         use crate::util::ser::{BigSize, Iterable, Writeable};
791
792         fn payer_keys() -> KeyPair {
793                 let secp_ctx = Secp256k1::new();
794                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
795         }
796
797         fn payer_sign(digest: &Message) -> Result<Signature, Infallible> {
798                 let secp_ctx = Secp256k1::new();
799                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
800                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
801         }
802
803         fn payer_pubkey() -> PublicKey {
804                 payer_keys().public_key()
805         }
806
807         fn recipient_keys() -> KeyPair {
808                 let secp_ctx = Secp256k1::new();
809                 KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap())
810         }
811
812         fn recipient_sign(digest: &Message) -> Result<Signature, Infallible> {
813                 let secp_ctx = Secp256k1::new();
814                 let keys = KeyPair::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
815                 Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys))
816         }
817
818         fn recipient_pubkey() -> PublicKey {
819                 recipient_keys().public_key()
820         }
821
822         fn pubkey(byte: u8) -> PublicKey {
823                 let secp_ctx = Secp256k1::new();
824                 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
825         }
826
827         fn privkey(byte: u8) -> SecretKey {
828                 SecretKey::from_slice(&[byte; 32]).unwrap()
829         }
830
831         trait ToBytes {
832                 fn to_bytes(&self) -> Vec<u8>;
833         }
834
835         impl<'a> ToBytes for FullInvoiceTlvStreamRef<'a> {
836                 fn to_bytes(&self) -> Vec<u8> {
837                         let mut buffer = Vec::new();
838                         self.0.write(&mut buffer).unwrap();
839                         self.1.write(&mut buffer).unwrap();
840                         self.2.write(&mut buffer).unwrap();
841                         self.3.write(&mut buffer).unwrap();
842                         self.4.write(&mut buffer).unwrap();
843                         buffer
844                 }
845         }
846
847         fn payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> {
848                 let paths = vec![
849                         BlindedPath {
850                                 introduction_node_id: pubkey(40),
851                                 blinding_point: pubkey(41),
852                                 blinded_hops: vec![
853                                         BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
854                                         BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
855                                 ],
856                         },
857                         BlindedPath {
858                                 introduction_node_id: pubkey(40),
859                                 blinding_point: pubkey(41),
860                                 blinded_hops: vec![
861                                         BlindedHop { blinded_node_id: pubkey(45), encrypted_payload: vec![0; 45] },
862                                         BlindedHop { blinded_node_id: pubkey(46), encrypted_payload: vec![0; 46] },
863                                 ],
864                         },
865                 ];
866
867                 let payinfo = vec![
868                         BlindedPayInfo {
869                                 fee_base_msat: 1,
870                                 fee_proportional_millionths: 1_000,
871                                 cltv_expiry_delta: 42,
872                                 htlc_minimum_msat: 100,
873                                 htlc_maximum_msat: 1_000_000_000_000,
874                                 features: BlindedHopFeatures::empty(),
875                         },
876                         BlindedPayInfo {
877                                 fee_base_msat: 1,
878                                 fee_proportional_millionths: 1_000,
879                                 cltv_expiry_delta: 42,
880                                 htlc_minimum_msat: 100,
881                                 htlc_maximum_msat: 1_000_000_000_000,
882                                 features: BlindedHopFeatures::empty(),
883                         },
884                 ];
885
886                 paths.into_iter().zip(payinfo.into_iter()).collect()
887         }
888
889         fn payment_hash() -> PaymentHash {
890                 PaymentHash([42; 32])
891         }
892
893         fn now() -> Duration {
894                 std::time::SystemTime::now()
895                         .duration_since(std::time::SystemTime::UNIX_EPOCH)
896                         .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH")
897         }
898
899         #[test]
900         fn builds_invoice_for_offer_with_defaults() {
901                 let payment_paths = payment_paths();
902                 let payment_hash = payment_hash();
903                 let now = now();
904                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
905                         .amount_msats(1000)
906                         .build().unwrap()
907                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
908                         .build().unwrap()
909                         .sign(payer_sign).unwrap()
910                         .respond_with_no_std(payment_paths.clone(), payment_hash, now).unwrap()
911                         .build().unwrap()
912                         .sign(recipient_sign).unwrap();
913
914                 let mut buffer = Vec::new();
915                 invoice.write(&mut buffer).unwrap();
916
917                 assert_eq!(invoice.bytes, buffer.as_slice());
918                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
919                 assert_eq!(invoice.created_at(), now);
920                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
921                 #[cfg(feature = "std")]
922                 assert!(!invoice.is_expired());
923                 assert_eq!(invoice.payment_hash(), payment_hash);
924                 assert_eq!(invoice.amount_msats(), 1000);
925                 assert_eq!(invoice.fallbacks(), vec![]);
926                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
927                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
928                 assert!(
929                         merkle::verify_signature(
930                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
931                         ).is_ok()
932                 );
933
934                 assert_eq!(
935                         invoice.as_tlv_stream(),
936                         (
937                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
938                                 OfferTlvStreamRef {
939                                         chains: None,
940                                         metadata: None,
941                                         currency: None,
942                                         amount: Some(1000),
943                                         description: Some(&String::from("foo")),
944                                         features: None,
945                                         absolute_expiry: None,
946                                         paths: None,
947                                         issuer: None,
948                                         quantity_max: None,
949                                         node_id: Some(&recipient_pubkey()),
950                                 },
951                                 InvoiceRequestTlvStreamRef {
952                                         chain: None,
953                                         amount: None,
954                                         features: None,
955                                         quantity: None,
956                                         payer_id: Some(&payer_pubkey()),
957                                         payer_note: None,
958                                 },
959                                 InvoiceTlvStreamRef {
960                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
961                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
962                                         created_at: Some(now.as_secs()),
963                                         relative_expiry: None,
964                                         payment_hash: Some(&payment_hash),
965                                         amount: Some(1000),
966                                         fallbacks: None,
967                                         features: None,
968                                         node_id: Some(&recipient_pubkey()),
969                                 },
970                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
971                         ),
972                 );
973
974                 if let Err(e) = Invoice::try_from(buffer) {
975                         panic!("error parsing invoice: {:?}", e);
976                 }
977         }
978
979         #[test]
980         fn builds_invoice_for_refund_with_defaults() {
981                 let payment_paths = payment_paths();
982                 let payment_hash = payment_hash();
983                 let now = now();
984                 let invoice = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
985                         .build().unwrap()
986                         .respond_with_no_std(payment_paths.clone(), payment_hash, recipient_pubkey(), now)
987                         .unwrap()
988                         .build().unwrap()
989                         .sign(recipient_sign).unwrap();
990
991                 let mut buffer = Vec::new();
992                 invoice.write(&mut buffer).unwrap();
993
994                 assert_eq!(invoice.bytes, buffer.as_slice());
995                 assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
996                 assert_eq!(invoice.created_at(), now);
997                 assert_eq!(invoice.relative_expiry(), DEFAULT_RELATIVE_EXPIRY);
998                 #[cfg(feature = "std")]
999                 assert!(!invoice.is_expired());
1000                 assert_eq!(invoice.payment_hash(), payment_hash);
1001                 assert_eq!(invoice.amount_msats(), 1000);
1002                 assert_eq!(invoice.fallbacks(), vec![]);
1003                 assert_eq!(invoice.features(), &Bolt12InvoiceFeatures::empty());
1004                 assert_eq!(invoice.signing_pubkey(), recipient_pubkey());
1005                 assert!(
1006                         merkle::verify_signature(
1007                                 &invoice.signature, SIGNATURE_TAG, &invoice.bytes, recipient_pubkey()
1008                         ).is_ok()
1009                 );
1010
1011                 assert_eq!(
1012                         invoice.as_tlv_stream(),
1013                         (
1014                                 PayerTlvStreamRef { metadata: Some(&vec![1; 32]) },
1015                                 OfferTlvStreamRef {
1016                                         chains: None,
1017                                         metadata: None,
1018                                         currency: None,
1019                                         amount: None,
1020                                         description: Some(&String::from("foo")),
1021                                         features: None,
1022                                         absolute_expiry: None,
1023                                         paths: None,
1024                                         issuer: None,
1025                                         quantity_max: None,
1026                                         node_id: None,
1027                                 },
1028                                 InvoiceRequestTlvStreamRef {
1029                                         chain: None,
1030                                         amount: Some(1000),
1031                                         features: None,
1032                                         quantity: None,
1033                                         payer_id: Some(&payer_pubkey()),
1034                                         payer_note: None,
1035                                 },
1036                                 InvoiceTlvStreamRef {
1037                                         paths: Some(Iterable(payment_paths.iter().map(|(path, _)| path))),
1038                                         blindedpay: Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo))),
1039                                         created_at: Some(now.as_secs()),
1040                                         relative_expiry: None,
1041                                         payment_hash: Some(&payment_hash),
1042                                         amount: Some(1000),
1043                                         fallbacks: None,
1044                                         features: None,
1045                                         node_id: Some(&recipient_pubkey()),
1046                                 },
1047                                 SignatureTlvStreamRef { signature: Some(&invoice.signature()) },
1048                         ),
1049                 );
1050
1051                 if let Err(e) = Invoice::try_from(buffer) {
1052                         panic!("error parsing invoice: {:?}", e);
1053                 }
1054         }
1055
1056         #[cfg(feature = "std")]
1057         #[test]
1058         fn builds_invoice_from_offer_with_expiration() {
1059                 let future_expiry = Duration::from_secs(u64::max_value());
1060                 let past_expiry = Duration::from_secs(0);
1061
1062                 if let Err(e) = OfferBuilder::new("foo".into(), recipient_pubkey())
1063                         .amount_msats(1000)
1064                         .absolute_expiry(future_expiry)
1065                         .build().unwrap()
1066                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1067                         .build().unwrap()
1068                         .sign(payer_sign).unwrap()
1069                         .respond_with(payment_paths(), payment_hash())
1070                         .unwrap()
1071                         .build()
1072                 {
1073                         panic!("error building invoice: {:?}", e);
1074                 }
1075
1076                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1077                         .amount_msats(1000)
1078                         .absolute_expiry(past_expiry)
1079                         .build().unwrap()
1080                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1081                         .build_unchecked()
1082                         .sign(payer_sign).unwrap()
1083                         .respond_with(payment_paths(), payment_hash())
1084                         .unwrap()
1085                         .build()
1086                 {
1087                         Ok(_) => panic!("expected error"),
1088                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1089                 }
1090         }
1091
1092         #[cfg(feature = "std")]
1093         #[test]
1094         fn builds_invoice_from_refund_with_expiration() {
1095                 let future_expiry = Duration::from_secs(u64::max_value());
1096                 let past_expiry = Duration::from_secs(0);
1097
1098                 if let Err(e) = RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1099                         .absolute_expiry(future_expiry)
1100                         .build().unwrap()
1101                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1102                         .unwrap()
1103                         .build()
1104                 {
1105                         panic!("error building invoice: {:?}", e);
1106                 }
1107
1108                 match RefundBuilder::new("foo".into(), vec![1; 32], payer_pubkey(), 1000).unwrap()
1109                         .absolute_expiry(past_expiry)
1110                         .build().unwrap()
1111                         .respond_with(payment_paths(), payment_hash(), recipient_pubkey())
1112                         .unwrap()
1113                         .build()
1114                 {
1115                         Ok(_) => panic!("expected error"),
1116                         Err(e) => assert_eq!(e, SemanticError::AlreadyExpired),
1117                 }
1118         }
1119
1120         #[test]
1121         fn builds_invoice_with_relative_expiry() {
1122                 let now = now();
1123                 let one_hour = Duration::from_secs(3600);
1124
1125                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1126                         .amount_msats(1000)
1127                         .build().unwrap()
1128                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1129                         .build().unwrap()
1130                         .sign(payer_sign).unwrap()
1131                         .respond_with_no_std(payment_paths(), payment_hash(), now).unwrap()
1132                         .relative_expiry(one_hour.as_secs() as u32)
1133                         .build().unwrap()
1134                         .sign(recipient_sign).unwrap();
1135                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1136                 #[cfg(feature = "std")]
1137                 assert!(!invoice.is_expired());
1138                 assert_eq!(invoice.relative_expiry(), one_hour);
1139                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32));
1140
1141                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1142                         .amount_msats(1000)
1143                         .build().unwrap()
1144                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1145                         .build().unwrap()
1146                         .sign(payer_sign).unwrap()
1147                         .respond_with_no_std(payment_paths(), payment_hash(), now - one_hour).unwrap()
1148                         .relative_expiry(one_hour.as_secs() as u32 - 1)
1149                         .build().unwrap()
1150                         .sign(recipient_sign).unwrap();
1151                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1152                 #[cfg(feature = "std")]
1153                 assert!(invoice.is_expired());
1154                 assert_eq!(invoice.relative_expiry(), one_hour - Duration::from_secs(1));
1155                 assert_eq!(tlv_stream.relative_expiry, Some(one_hour.as_secs() as u32 - 1));
1156         }
1157
1158         #[test]
1159         fn builds_invoice_with_amount_from_request() {
1160                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1161                         .amount_msats(1000)
1162                         .build().unwrap()
1163                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1164                         .amount_msats(1001).unwrap()
1165                         .build().unwrap()
1166                         .sign(payer_sign).unwrap()
1167                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1168                         .build().unwrap()
1169                         .sign(recipient_sign).unwrap();
1170                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1171                 assert_eq!(invoice.amount_msats(), 1001);
1172                 assert_eq!(tlv_stream.amount, Some(1001));
1173         }
1174
1175         #[test]
1176         fn builds_invoice_with_fallback_address() {
1177                 let script = Script::new();
1178                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1179                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1180                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1181
1182                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1183                         .amount_msats(1000)
1184                         .build().unwrap()
1185                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1186                         .build().unwrap()
1187                         .sign(payer_sign).unwrap()
1188                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1189                         .fallback_v0_p2wsh(&script.wscript_hash())
1190                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1191                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1192                         .build().unwrap()
1193                         .sign(recipient_sign).unwrap();
1194                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1195                 assert_eq!(
1196                         invoice.fallbacks(),
1197                         vec![
1198                                 Address::p2wsh(&script, Network::Bitcoin),
1199                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1200                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1201                         ],
1202                 );
1203                 assert_eq!(
1204                         tlv_stream.fallbacks,
1205                         Some(&vec![
1206                                 FallbackAddress {
1207                                         version: WitnessVersion::V0.to_num(),
1208                                         program: Vec::from(&script.wscript_hash().into_inner()[..]),
1209                                 },
1210                                 FallbackAddress {
1211                                         version: WitnessVersion::V0.to_num(),
1212                                         program: Vec::from(&pubkey.wpubkey_hash().unwrap().into_inner()[..]),
1213                                 },
1214                                 FallbackAddress {
1215                                         version: WitnessVersion::V1.to_num(),
1216                                         program: Vec::from(&tweaked_pubkey.serialize()[..]),
1217                                 },
1218                         ])
1219                 );
1220         }
1221
1222         #[test]
1223         fn builds_invoice_with_allow_mpp() {
1224                 let mut features = Bolt12InvoiceFeatures::empty();
1225                 features.set_basic_mpp_optional();
1226
1227                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1228                         .amount_msats(1000)
1229                         .build().unwrap()
1230                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1231                         .build().unwrap()
1232                         .sign(payer_sign).unwrap()
1233                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1234                         .allow_mpp()
1235                         .build().unwrap()
1236                         .sign(recipient_sign).unwrap();
1237                 let (_, _, _, tlv_stream, _) = invoice.as_tlv_stream();
1238                 assert_eq!(invoice.features(), &features);
1239                 assert_eq!(tlv_stream.features, Some(&features));
1240         }
1241
1242         #[test]
1243         fn fails_signing_invoice() {
1244                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1245                         .amount_msats(1000)
1246                         .build().unwrap()
1247                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1248                         .build().unwrap()
1249                         .sign(payer_sign).unwrap()
1250                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1251                         .build().unwrap()
1252                         .sign(|_| Err(()))
1253                 {
1254                         Ok(_) => panic!("expected error"),
1255                         Err(e) => assert_eq!(e, SignError::Signing(())),
1256                 }
1257
1258                 match OfferBuilder::new("foo".into(), recipient_pubkey())
1259                         .amount_msats(1000)
1260                         .build().unwrap()
1261                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1262                         .build().unwrap()
1263                         .sign(payer_sign).unwrap()
1264                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1265                         .build().unwrap()
1266                         .sign(payer_sign)
1267                 {
1268                         Ok(_) => panic!("expected error"),
1269                         Err(e) => assert_eq!(e, SignError::Verification(secp256k1::Error::InvalidSignature)),
1270                 }
1271         }
1272
1273         #[test]
1274         fn parses_invoice_with_payment_paths() {
1275                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1276                         .amount_msats(1000)
1277                         .build().unwrap()
1278                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1279                         .build().unwrap()
1280                         .sign(payer_sign).unwrap()
1281                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1282                         .build().unwrap()
1283                         .sign(recipient_sign).unwrap();
1284
1285                 let mut buffer = Vec::new();
1286                 invoice.write(&mut buffer).unwrap();
1287
1288                 if let Err(e) = Invoice::try_from(buffer) {
1289                         panic!("error parsing invoice: {:?}", e);
1290                 }
1291
1292                 let mut tlv_stream = invoice.as_tlv_stream();
1293                 tlv_stream.3.paths = None;
1294
1295                 match Invoice::try_from(tlv_stream.to_bytes()) {
1296                         Ok(_) => panic!("expected error"),
1297                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1298                 }
1299
1300                 let mut tlv_stream = invoice.as_tlv_stream();
1301                 tlv_stream.3.blindedpay = None;
1302
1303                 match Invoice::try_from(tlv_stream.to_bytes()) {
1304                         Ok(_) => panic!("expected error"),
1305                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1306                 }
1307
1308                 let empty_payment_paths = vec![];
1309                 let mut tlv_stream = invoice.as_tlv_stream();
1310                 tlv_stream.3.paths = Some(Iterable(empty_payment_paths.iter().map(|(path, _)| path)));
1311
1312                 match Invoice::try_from(tlv_stream.to_bytes()) {
1313                         Ok(_) => panic!("expected error"),
1314                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaths)),
1315                 }
1316
1317                 let mut payment_paths = payment_paths();
1318                 payment_paths.pop();
1319                 let mut tlv_stream = invoice.as_tlv_stream();
1320                 tlv_stream.3.blindedpay = Some(Iterable(payment_paths.iter().map(|(_, payinfo)| payinfo)));
1321
1322                 match Invoice::try_from(tlv_stream.to_bytes()) {
1323                         Ok(_) => panic!("expected error"),
1324                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidPayInfo)),
1325                 }
1326         }
1327
1328         #[test]
1329         fn parses_invoice_with_created_at() {
1330                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1331                         .amount_msats(1000)
1332                         .build().unwrap()
1333                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1334                         .build().unwrap()
1335                         .sign(payer_sign).unwrap()
1336                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1337                         .build().unwrap()
1338                         .sign(recipient_sign).unwrap();
1339
1340                 let mut buffer = Vec::new();
1341                 invoice.write(&mut buffer).unwrap();
1342
1343                 if let Err(e) = Invoice::try_from(buffer) {
1344                         panic!("error parsing invoice: {:?}", e);
1345                 }
1346
1347                 let mut tlv_stream = invoice.as_tlv_stream();
1348                 tlv_stream.3.created_at = None;
1349
1350                 match Invoice::try_from(tlv_stream.to_bytes()) {
1351                         Ok(_) => panic!("expected error"),
1352                         Err(e) => {
1353                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingCreationTime));
1354                         },
1355                 }
1356         }
1357
1358         #[test]
1359         fn parses_invoice_with_relative_expiry() {
1360                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1361                         .amount_msats(1000)
1362                         .build().unwrap()
1363                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1364                         .build().unwrap()
1365                         .sign(payer_sign).unwrap()
1366                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1367                         .relative_expiry(3600)
1368                         .build().unwrap()
1369                         .sign(recipient_sign).unwrap();
1370
1371                 let mut buffer = Vec::new();
1372                 invoice.write(&mut buffer).unwrap();
1373
1374                 match Invoice::try_from(buffer) {
1375                         Ok(invoice) => assert_eq!(invoice.relative_expiry(), Duration::from_secs(3600)),
1376                         Err(e) => panic!("error parsing invoice: {:?}", e),
1377                 }
1378         }
1379
1380         #[test]
1381         fn parses_invoice_with_payment_hash() {
1382                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1383                         .amount_msats(1000)
1384                         .build().unwrap()
1385                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1386                         .build().unwrap()
1387                         .sign(payer_sign).unwrap()
1388                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1389                         .build().unwrap()
1390                         .sign(recipient_sign).unwrap();
1391
1392                 let mut buffer = Vec::new();
1393                 invoice.write(&mut buffer).unwrap();
1394
1395                 if let Err(e) = Invoice::try_from(buffer) {
1396                         panic!("error parsing invoice: {:?}", e);
1397                 }
1398
1399                 let mut tlv_stream = invoice.as_tlv_stream();
1400                 tlv_stream.3.payment_hash = None;
1401
1402                 match Invoice::try_from(tlv_stream.to_bytes()) {
1403                         Ok(_) => panic!("expected error"),
1404                         Err(e) => {
1405                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingPaymentHash));
1406                         },
1407                 }
1408         }
1409
1410         #[test]
1411         fn parses_invoice_with_amount() {
1412                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1413                         .amount_msats(1000)
1414                         .build().unwrap()
1415                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1416                         .build().unwrap()
1417                         .sign(payer_sign).unwrap()
1418                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1419                         .build().unwrap()
1420                         .sign(recipient_sign).unwrap();
1421
1422                 let mut buffer = Vec::new();
1423                 invoice.write(&mut buffer).unwrap();
1424
1425                 if let Err(e) = Invoice::try_from(buffer) {
1426                         panic!("error parsing invoice: {:?}", e);
1427                 }
1428
1429                 let mut tlv_stream = invoice.as_tlv_stream();
1430                 tlv_stream.3.amount = None;
1431
1432                 match Invoice::try_from(tlv_stream.to_bytes()) {
1433                         Ok(_) => panic!("expected error"),
1434                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingAmount)),
1435                 }
1436         }
1437
1438         #[test]
1439         fn parses_invoice_with_allow_mpp() {
1440                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1441                         .amount_msats(1000)
1442                         .build().unwrap()
1443                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1444                         .build().unwrap()
1445                         .sign(payer_sign).unwrap()
1446                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1447                         .allow_mpp()
1448                         .build().unwrap()
1449                         .sign(recipient_sign).unwrap();
1450
1451                 let mut buffer = Vec::new();
1452                 invoice.write(&mut buffer).unwrap();
1453
1454                 match Invoice::try_from(buffer) {
1455                         Ok(invoice) => {
1456                                 let mut features = Bolt12InvoiceFeatures::empty();
1457                                 features.set_basic_mpp_optional();
1458                                 assert_eq!(invoice.features(), &features);
1459                         },
1460                         Err(e) => panic!("error parsing invoice: {:?}", e),
1461                 }
1462         }
1463
1464         #[test]
1465         fn parses_invoice_with_fallback_address() {
1466                 let script = Script::new();
1467                 let pubkey = bitcoin::util::key::PublicKey::new(recipient_pubkey());
1468                 let x_only_pubkey = XOnlyPublicKey::from_keypair(&recipient_keys()).0;
1469                 let tweaked_pubkey = TweakedPublicKey::dangerous_assume_tweaked(x_only_pubkey);
1470
1471                 let offer = OfferBuilder::new("foo".into(), recipient_pubkey())
1472                         .amount_msats(1000)
1473                         .build().unwrap();
1474                 let invoice_request = offer
1475                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1476                         .build().unwrap()
1477                         .sign(payer_sign).unwrap();
1478                 let mut unsigned_invoice = invoice_request
1479                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1480                         .fallback_v0_p2wsh(&script.wscript_hash())
1481                         .fallback_v0_p2wpkh(&pubkey.wpubkey_hash().unwrap())
1482                         .fallback_v1_p2tr_tweaked(&tweaked_pubkey)
1483                         .build().unwrap();
1484
1485                 // Only standard addresses will be included.
1486                 let fallbacks = unsigned_invoice.invoice.fields_mut().fallbacks.as_mut().unwrap();
1487                 // Non-standard addresses
1488                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 41] });
1489                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 1] });
1490                 fallbacks.push(FallbackAddress { version: 17, program: vec![0u8; 40] });
1491                 // Standard address
1492                 fallbacks.push(FallbackAddress { version: 1, program: vec![0u8; 33] });
1493                 fallbacks.push(FallbackAddress { version: 2, program: vec![0u8; 40] });
1494
1495                 let invoice = unsigned_invoice.sign(recipient_sign).unwrap();
1496                 let mut buffer = Vec::new();
1497                 invoice.write(&mut buffer).unwrap();
1498
1499                 match Invoice::try_from(buffer) {
1500                         Ok(invoice) => {
1501                                 assert_eq!(
1502                                         invoice.fallbacks(),
1503                                         vec![
1504                                                 Address::p2wsh(&script, Network::Bitcoin),
1505                                                 Address::p2wpkh(&pubkey, Network::Bitcoin).unwrap(),
1506                                                 Address::p2tr_tweaked(tweaked_pubkey, Network::Bitcoin),
1507                                                 Address {
1508                                                         payload: Payload::WitnessProgram {
1509                                                                 version: WitnessVersion::V1,
1510                                                                 program: vec![0u8; 33],
1511                                                         },
1512                                                         network: Network::Bitcoin,
1513                                                 },
1514                                                 Address {
1515                                                         payload: Payload::WitnessProgram {
1516                                                                 version: WitnessVersion::V2,
1517                                                                 program: vec![0u8; 40],
1518                                                         },
1519                                                         network: Network::Bitcoin,
1520                                                 },
1521                                         ],
1522                                 );
1523                         },
1524                         Err(e) => panic!("error parsing invoice: {:?}", e),
1525                 }
1526         }
1527
1528         #[test]
1529         fn parses_invoice_with_node_id() {
1530                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1531                         .amount_msats(1000)
1532                         .build().unwrap()
1533                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1534                         .build().unwrap()
1535                         .sign(payer_sign).unwrap()
1536                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1537                         .build().unwrap()
1538                         .sign(recipient_sign).unwrap();
1539
1540                 let mut buffer = Vec::new();
1541                 invoice.write(&mut buffer).unwrap();
1542
1543                 if let Err(e) = Invoice::try_from(buffer) {
1544                         panic!("error parsing invoice: {:?}", e);
1545                 }
1546
1547                 let mut tlv_stream = invoice.as_tlv_stream();
1548                 tlv_stream.3.node_id = None;
1549
1550                 match Invoice::try_from(tlv_stream.to_bytes()) {
1551                         Ok(_) => panic!("expected error"),
1552                         Err(e) => {
1553                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSigningPubkey));
1554                         },
1555                 }
1556
1557                 let invalid_pubkey = payer_pubkey();
1558                 let mut tlv_stream = invoice.as_tlv_stream();
1559                 tlv_stream.3.node_id = Some(&invalid_pubkey);
1560
1561                 match Invoice::try_from(tlv_stream.to_bytes()) {
1562                         Ok(_) => panic!("expected error"),
1563                         Err(e) => {
1564                                 assert_eq!(e, ParseError::InvalidSemantics(SemanticError::InvalidSigningPubkey));
1565                         },
1566                 }
1567         }
1568
1569         #[test]
1570         fn fails_parsing_invoice_without_signature() {
1571                 let mut buffer = Vec::new();
1572                 OfferBuilder::new("foo".into(), recipient_pubkey())
1573                         .amount_msats(1000)
1574                         .build().unwrap()
1575                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1576                         .build().unwrap()
1577                         .sign(payer_sign).unwrap()
1578                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1579                         .build().unwrap()
1580                         .invoice
1581                         .write(&mut buffer).unwrap();
1582
1583                 match Invoice::try_from(buffer) {
1584                         Ok(_) => panic!("expected error"),
1585                         Err(e) => assert_eq!(e, ParseError::InvalidSemantics(SemanticError::MissingSignature)),
1586                 }
1587         }
1588
1589         #[test]
1590         fn fails_parsing_invoice_with_invalid_signature() {
1591                 let mut invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1592                         .amount_msats(1000)
1593                         .build().unwrap()
1594                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1595                         .build().unwrap()
1596                         .sign(payer_sign).unwrap()
1597                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1598                         .build().unwrap()
1599                         .sign(recipient_sign).unwrap();
1600                 let last_signature_byte = invoice.bytes.last_mut().unwrap();
1601                 *last_signature_byte = last_signature_byte.wrapping_add(1);
1602
1603                 let mut buffer = Vec::new();
1604                 invoice.write(&mut buffer).unwrap();
1605
1606                 match Invoice::try_from(buffer) {
1607                         Ok(_) => panic!("expected error"),
1608                         Err(e) => {
1609                                 assert_eq!(e, ParseError::InvalidSignature(secp256k1::Error::InvalidSignature));
1610                         },
1611                 }
1612         }
1613
1614         #[test]
1615         fn fails_parsing_invoice_with_extra_tlv_records() {
1616                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1617                         .amount_msats(1000)
1618                         .build().unwrap()
1619                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1620                         .build().unwrap()
1621                         .sign(payer_sign).unwrap()
1622                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
1623                         .build().unwrap()
1624                         .sign(recipient_sign).unwrap();
1625
1626                 let mut encoded_invoice = Vec::new();
1627                 invoice.write(&mut encoded_invoice).unwrap();
1628                 BigSize(1002).write(&mut encoded_invoice).unwrap();
1629                 BigSize(32).write(&mut encoded_invoice).unwrap();
1630                 [42u8; 32].write(&mut encoded_invoice).unwrap();
1631
1632                 match Invoice::try_from(encoded_invoice) {
1633                         Ok(_) => panic!("expected error"),
1634                         Err(e) => assert_eq!(e, ParseError::Decode(DecodeError::InvalidValue)),
1635                 }
1636         }
1637 }