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