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