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