]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/offers/invoice.rs
Expand invoice module docs and include an example
[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
452 impl InvoiceContents {
453         /// Whether the original offer or refund has expired.
454         #[cfg(feature = "std")]
455         fn is_offer_or_refund_expired(&self) -> bool {
456                 match self {
457                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
458                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
459                 }
460         }
461
462         fn chain(&self) -> ChainHash {
463                 match self {
464                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
465                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
466                 }
467         }
468
469         fn fields(&self) -> &InvoiceFields {
470                 match self {
471                         InvoiceContents::ForOffer { fields, .. } => fields,
472                         InvoiceContents::ForRefund { fields, .. } => fields,
473                 }
474         }
475
476         fn fields_mut(&mut self) -> &mut InvoiceFields {
477                 match self {
478                         InvoiceContents::ForOffer { fields, .. } => fields,
479                         InvoiceContents::ForRefund { fields, .. } => fields,
480                 }
481         }
482
483         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
484                 let (payer, offer, invoice_request) = match self {
485                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
486                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
487                 };
488                 let invoice = self.fields().as_tlv_stream();
489
490                 (payer, offer, invoice_request, invoice)
491         }
492 }
493
494 impl InvoiceFields {
495         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
496                 let features = {
497                         if self.features == Bolt12InvoiceFeatures::empty() { None }
498                         else { Some(&self.features) }
499                 };
500
501                 InvoiceTlvStreamRef {
502                         paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
503                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
504                         created_at: Some(self.created_at.as_secs()),
505                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
506                         payment_hash: Some(&self.payment_hash),
507                         amount: Some(self.amount_msats),
508                         fallbacks: self.fallbacks.as_ref(),
509                         features,
510                         node_id: Some(&self.signing_pubkey),
511                 }
512         }
513 }
514
515 impl Writeable for Invoice {
516         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
517                 WithoutLength(&self.bytes).write(writer)
518         }
519 }
520
521 impl TryFrom<Vec<u8>> for Invoice {
522         type Error = ParseError;
523
524         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
525                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
526                 Invoice::try_from(parsed_invoice)
527         }
528 }
529
530 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
531         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
532         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
533         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
534         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
535         (168, payment_hash: PaymentHash),
536         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
537         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
538         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
539         (176, node_id: PublicKey),
540 });
541
542 type BlindedPathIter<'a> = core::iter::Map<
543         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
544         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
545 >;
546
547 type BlindedPayInfoIter<'a> = core::iter::Map<
548         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
549         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
550 >;
551
552 /// Information needed to route a payment across a [`BlindedPath`].
553 #[derive(Debug, PartialEq)]
554 pub struct BlindedPayInfo {
555         fee_base_msat: u32,
556         fee_proportional_millionths: u32,
557         cltv_expiry_delta: u16,
558         htlc_minimum_msat: u64,
559         htlc_maximum_msat: u64,
560         features: BlindedHopFeatures,
561 }
562
563 impl_writeable!(BlindedPayInfo, {
564         fee_base_msat,
565         fee_proportional_millionths,
566         cltv_expiry_delta,
567         htlc_minimum_msat,
568         htlc_maximum_msat,
569         features
570 });
571
572 /// Wire representation for an on-chain fallback address.
573 #[derive(Debug, PartialEq)]
574 pub(super) struct FallbackAddress {
575         version: u8,
576         program: Vec<u8>,
577 }
578
579 impl_writeable!(FallbackAddress, { version, program });
580
581 type FullInvoiceTlvStream =
582         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
583
584 impl SeekReadable for FullInvoiceTlvStream {
585         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
586                 let payer = SeekReadable::read(r)?;
587                 let offer = SeekReadable::read(r)?;
588                 let invoice_request = SeekReadable::read(r)?;
589                 let invoice = SeekReadable::read(r)?;
590                 let signature = SeekReadable::read(r)?;
591
592                 Ok((payer, offer, invoice_request, invoice, signature))
593         }
594 }
595
596 type PartialInvoiceTlvStream =
597         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
598
599 type PartialInvoiceTlvStreamRef<'a> = (
600         PayerTlvStreamRef<'a>,
601         OfferTlvStreamRef<'a>,
602         InvoiceRequestTlvStreamRef<'a>,
603         InvoiceTlvStreamRef<'a>,
604 );
605
606 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
607         type Error = ParseError;
608
609         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
610                 let ParsedMessage { bytes, tlv_stream } = invoice;
611                 let (
612                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
613                         SignatureTlvStream { signature },
614                 ) = tlv_stream;
615                 let contents = InvoiceContents::try_from(
616                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
617                 )?;
618
619                 let signature = match signature {
620                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
621                         Some(signature) => signature,
622                 };
623                 let pubkey = contents.fields().signing_pubkey;
624                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
625
626                 Ok(Invoice { bytes, contents, signature })
627         }
628 }
629
630 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
631         type Error = SemanticError;
632
633         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
634                 let (
635                         payer_tlv_stream,
636                         offer_tlv_stream,
637                         invoice_request_tlv_stream,
638                         InvoiceTlvStream {
639                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
640                                 features, node_id,
641                         },
642                 ) = tlv_stream;
643
644                 let payment_paths = match (paths, blindedpay) {
645                         (None, _) => return Err(SemanticError::MissingPaths),
646                         (_, None) => return Err(SemanticError::InvalidPayInfo),
647                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
648                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
649                                 return Err(SemanticError::InvalidPayInfo);
650                         },
651                         (Some(paths), Some(blindedpay)) => {
652                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
653                         },
654                 };
655
656                 let created_at = match created_at {
657                         None => return Err(SemanticError::MissingCreationTime),
658                         Some(timestamp) => Duration::from_secs(timestamp),
659                 };
660
661                 let relative_expiry = relative_expiry
662                         .map(Into::<u64>::into)
663                         .map(Duration::from_secs);
664
665                 let payment_hash = match payment_hash {
666                         None => return Err(SemanticError::MissingPaymentHash),
667                         Some(payment_hash) => payment_hash,
668                 };
669
670                 let amount_msats = match amount {
671                         None => return Err(SemanticError::MissingAmount),
672                         Some(amount) => amount,
673                 };
674
675                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
676
677                 let signing_pubkey = match node_id {
678                         None => return Err(SemanticError::MissingSigningPubkey),
679                         Some(node_id) => node_id,
680                 };
681
682                 let fields = InvoiceFields {
683                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
684                         features, signing_pubkey,
685                 };
686
687                 match offer_tlv_stream.node_id {
688                         Some(expected_signing_pubkey) => {
689                                 if fields.signing_pubkey != expected_signing_pubkey {
690                                         return Err(SemanticError::InvalidSigningPubkey);
691                                 }
692
693                                 let invoice_request = InvoiceRequestContents::try_from(
694                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
695                                 )?;
696                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
697                         },
698                         None => {
699                                 let refund = RefundContents::try_from(
700                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
701                                 )?;
702                                 Ok(InvoiceContents::ForRefund { refund, fields })
703                         },
704                 }
705         }
706 }