Builder for creating invoices for refunds
[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 use bitcoin::blockdata::constants::ChainHash;
13 use bitcoin::hash_types::{WPubkeyHash, WScriptHash};
14 use bitcoin::hashes::Hash;
15 use bitcoin::network::constants::Network;
16 use bitcoin::secp256k1::{Message, PublicKey};
17 use bitcoin::secp256k1::schnorr::Signature;
18 use bitcoin::util::address::{Address, Payload, WitnessVersion};
19 use bitcoin::util::schnorr::TweakedPublicKey;
20 use core::convert::TryFrom;
21 use core::time::Duration;
22 use crate::io;
23 use crate::ln::PaymentHash;
24 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
25 use crate::ln::msgs::DecodeError;
26 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestContents, InvoiceRequestTlvStream, InvoiceRequestTlvStreamRef};
27 use crate::offers::merkle::{SignError, SignatureTlvStream, SignatureTlvStreamRef, WithoutSignatures, self};
28 use crate::offers::offer::{Amount, OfferTlvStream, OfferTlvStreamRef};
29 use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
30 use crate::offers::payer::{PayerTlvStream, PayerTlvStreamRef};
31 use crate::offers::refund::{Refund, RefundContents};
32 use crate::onion_message::BlindedPath;
33 use crate::util::ser::{HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer};
34
35 use crate::prelude::*;
36
37 #[cfg(feature = "std")]
38 use std::time::SystemTime;
39
40 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
41
42 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
43
44 /// Builds an [`Invoice`] from either:
45 /// - an [`InvoiceRequest`] for the "offer to be paid" flow or
46 /// - a [`Refund`] for the "offer for money" flow.
47 ///
48 /// See [module-level documentation] for usage.
49 ///
50 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
51 /// [`Refund`]: crate::offers::refund::Refund
52 /// [module-level documentation]: self
53 pub struct InvoiceBuilder<'a> {
54         invreq_bytes: &'a Vec<u8>,
55         invoice: InvoiceContents,
56 }
57
58 impl<'a> InvoiceBuilder<'a> {
59         pub(super) fn for_offer(
60                 invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
61                 created_at: Duration, payment_hash: PaymentHash
62         ) -> Result<Self, SemanticError> {
63                 let amount_msats = match invoice_request.amount_msats() {
64                         Some(amount_msats) => amount_msats,
65                         None => match invoice_request.contents.offer.amount() {
66                                 Some(Amount::Bitcoin { amount_msats }) => {
67                                         amount_msats * invoice_request.quantity().unwrap_or(1)
68                                 },
69                                 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
70                                 None => return Err(SemanticError::MissingAmount),
71                         },
72                 };
73
74                 let contents = InvoiceContents::ForOffer {
75                         invoice_request: invoice_request.contents.clone(),
76                         fields: InvoiceFields {
77                                 payment_paths, created_at, relative_expiry: None, payment_hash, amount_msats,
78                                 fallbacks: None, features: Bolt12InvoiceFeatures::empty(),
79                                 signing_pubkey: invoice_request.contents.offer.signing_pubkey(),
80                         },
81                 };
82
83                 Self::new(&invoice_request.bytes, contents)
84         }
85
86         pub(super) fn for_refund(
87                 refund: &'a Refund, payment_paths: Vec<(BlindedPath, BlindedPayInfo)>, created_at: Duration,
88                 payment_hash: PaymentHash, signing_pubkey: PublicKey
89         ) -> Result<Self, SemanticError> {
90                 let contents = InvoiceContents::ForRefund {
91                         refund: refund.contents.clone(),
92                         fields: InvoiceFields {
93                                 payment_paths, created_at, relative_expiry: None, payment_hash,
94                                 amount_msats: refund.amount_msats(), fallbacks: None,
95                                 features: Bolt12InvoiceFeatures::empty(), signing_pubkey,
96                         },
97                 };
98
99                 Self::new(&refund.bytes, contents)
100         }
101
102         fn new(invreq_bytes: &'a Vec<u8>, contents: InvoiceContents) -> Result<Self, SemanticError> {
103                 if contents.fields().payment_paths.is_empty() {
104                         return Err(SemanticError::MissingPaths);
105                 }
106
107                 Ok(Self { invreq_bytes, invoice: contents })
108         }
109
110         /// Sets the [`Invoice::relative_expiry`] as seconds since [`Invoice::created_at`]. Any expiry
111         /// that has already passed is valid and can be checked for using [`Invoice::is_expired`].
112         ///
113         /// Successive calls to this method will override the previous setting.
114         pub fn relative_expiry(mut self, relative_expiry_secs: u32) -> Self {
115                 let relative_expiry = Duration::from_secs(relative_expiry_secs as u64);
116                 self.invoice.fields_mut().relative_expiry = Some(relative_expiry);
117                 self
118         }
119
120         /// Adds a P2WSH address to [`Invoice::fallbacks`].
121         ///
122         /// Successive calls to this method will add another address. Caller is responsible for not
123         /// adding duplicate addresses and only calling if capable of receiving to P2WSH addresses.
124         pub fn fallback_v0_p2wsh(mut self, script_hash: &WScriptHash) -> Self {
125                 let address = FallbackAddress {
126                         version: WitnessVersion::V0.to_num(),
127                         program: Vec::from(&script_hash.into_inner()[..]),
128                 };
129                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
130                 self
131         }
132
133         /// Adds a P2WPKH address to [`Invoice::fallbacks`].
134         ///
135         /// Successive calls to this method will add another address. Caller is responsible for not
136         /// adding duplicate addresses and only calling if capable of receiving to P2WPKH addresses.
137         pub fn fallback_v0_p2wpkh(mut self, pubkey_hash: &WPubkeyHash) -> Self {
138                 let address = FallbackAddress {
139                         version: WitnessVersion::V0.to_num(),
140                         program: Vec::from(&pubkey_hash.into_inner()[..]),
141                 };
142                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
143                 self
144         }
145
146         /// Adds a P2TR address to [`Invoice::fallbacks`].
147         ///
148         /// Successive calls to this method will add another address. Caller is responsible for not
149         /// adding duplicate addresses and only calling if capable of receiving to P2TR addresses.
150         pub fn fallback_v1_p2tr_tweaked(mut self, output_key: &TweakedPublicKey) -> Self {
151                 let address = FallbackAddress {
152                         version: WitnessVersion::V1.to_num(),
153                         program: Vec::from(&output_key.serialize()[..]),
154                 };
155                 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
156                 self
157         }
158
159         /// Sets [`Invoice::features`] to indicate MPP may be used. Otherwise, MPP is disallowed.
160         pub fn allow_mpp(mut self) -> Self {
161                 self.invoice.fields_mut().features.set_basic_mpp_optional();
162                 self
163         }
164
165         /// Builds an unsigned [`Invoice`] after checking for valid semantics. It can be signed by
166         /// [`UnsignedInvoice::sign`].
167         pub fn build(self) -> Result<UnsignedInvoice<'a>, SemanticError> {
168                 #[cfg(feature = "std")] {
169                         if self.invoice.is_offer_or_refund_expired() {
170                                 return Err(SemanticError::AlreadyExpired);
171                         }
172                 }
173
174                 let InvoiceBuilder { invreq_bytes, invoice } = self;
175                 Ok(UnsignedInvoice { invreq_bytes, invoice })
176         }
177 }
178
179 /// A semantically valid [`Invoice`] that hasn't been signed.
180 pub struct UnsignedInvoice<'a> {
181         invreq_bytes: &'a Vec<u8>,
182         invoice: InvoiceContents,
183 }
184
185 impl<'a> UnsignedInvoice<'a> {
186         /// Signs the invoice using the given function.
187         pub fn sign<F, E>(self, sign: F) -> Result<Invoice, SignError<E>>
188         where
189                 F: FnOnce(&Message) -> Result<Signature, E>
190         {
191                 // Use the invoice_request bytes instead of the invoice_request TLV stream as the latter may
192                 // have contained unknown TLV records, which are not stored in `InvoiceRequestContents` or
193                 // `RefundContents`.
194                 let (_, _, _, invoice_tlv_stream) = self.invoice.as_tlv_stream();
195                 let invoice_request_bytes = WithoutSignatures(self.invreq_bytes);
196                 let unsigned_tlv_stream = (invoice_request_bytes, invoice_tlv_stream);
197
198                 let mut bytes = Vec::new();
199                 unsigned_tlv_stream.write(&mut bytes).unwrap();
200
201                 let pubkey = self.invoice.fields().signing_pubkey;
202                 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
203
204                 // Append the signature TLV record to the bytes.
205                 let signature_tlv_stream = SignatureTlvStreamRef {
206                         signature: Some(&signature),
207                 };
208                 signature_tlv_stream.write(&mut bytes).unwrap();
209
210                 Ok(Invoice {
211                         bytes,
212                         contents: self.invoice,
213                         signature,
214                 })
215         }
216 }
217
218 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
219 ///
220 /// An invoice may be sent in response to an [`InvoiceRequest`] in the case of an offer or sent
221 /// directly after scanning a refund. It includes all the information needed to pay a recipient.
222 ///
223 /// [`Offer`]: crate::offers::offer::Offer
224 /// [`Refund`]: crate::offers::refund::Refund
225 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
226 pub struct Invoice {
227         bytes: Vec<u8>,
228         contents: InvoiceContents,
229         signature: Signature,
230 }
231
232 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
233 ///
234 /// [`Offer`]: crate::offers::offer::Offer
235 /// [`Refund`]: crate::offers::refund::Refund
236 enum InvoiceContents {
237         /// Contents for an [`Invoice`] corresponding to an [`Offer`].
238         ///
239         /// [`Offer`]: crate::offers::offer::Offer
240         ForOffer {
241                 invoice_request: InvoiceRequestContents,
242                 fields: InvoiceFields,
243         },
244         /// Contents for an [`Invoice`] corresponding to a [`Refund`].
245         ///
246         /// [`Refund`]: crate::offers::refund::Refund
247         ForRefund {
248                 refund: RefundContents,
249                 fields: InvoiceFields,
250         },
251 }
252
253 /// Invoice-specific fields for an `invoice` message.
254 struct InvoiceFields {
255         payment_paths: Vec<(BlindedPath, BlindedPayInfo)>,
256         created_at: Duration,
257         relative_expiry: Option<Duration>,
258         payment_hash: PaymentHash,
259         amount_msats: u64,
260         fallbacks: Option<Vec<FallbackAddress>>,
261         features: Bolt12InvoiceFeatures,
262         signing_pubkey: PublicKey,
263 }
264
265 impl Invoice {
266         /// Paths to the recipient originating from publicly reachable nodes, including information
267         /// needed for routing payments across them. Blinded paths provide recipient privacy by
268         /// obfuscating its node id.
269         pub fn payment_paths(&self) -> &[(BlindedPath, BlindedPayInfo)] {
270                 &self.contents.fields().payment_paths[..]
271         }
272
273         /// Duration since the Unix epoch when the invoice was created.
274         pub fn created_at(&self) -> Duration {
275                 self.contents.fields().created_at
276         }
277
278         /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
279         /// longer be paid.
280         pub fn relative_expiry(&self) -> Duration {
281                 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
282         }
283
284         /// Whether the invoice has expired.
285         #[cfg(feature = "std")]
286         pub fn is_expired(&self) -> bool {
287                 let absolute_expiry = self.created_at().checked_add(self.relative_expiry());
288                 match absolute_expiry {
289                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
290                                 Ok(elapsed) => elapsed > seconds_from_epoch,
291                                 Err(_) => false,
292                         },
293                         None => false,
294                 }
295         }
296
297         /// SHA256 hash of the payment preimage that will be given in return for paying the invoice.
298         pub fn payment_hash(&self) -> PaymentHash {
299                 self.contents.fields().payment_hash
300         }
301
302         /// The minimum amount required for a successful payment of the invoice.
303         pub fn amount_msats(&self) -> u64 {
304                 self.contents.fields().amount_msats
305         }
306
307         /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
308         /// least-preferred.
309         pub fn fallbacks(&self) -> Vec<Address> {
310                 let network = match self.network() {
311                         None => return Vec::new(),
312                         Some(network) => network,
313                 };
314
315                 let to_valid_address = |address: &FallbackAddress| {
316                         let version = match WitnessVersion::try_from(address.version) {
317                                 Ok(version) => version,
318                                 Err(_) => return None,
319                         };
320
321                         let program = &address.program;
322                         if program.len() < 2 || program.len() > 40 {
323                                 return None;
324                         }
325
326                         let address = Address {
327                                 payload: Payload::WitnessProgram {
328                                         version,
329                                         program: address.program.clone(),
330                                 },
331                                 network,
332                         };
333
334                         if !address.is_standard() && version == WitnessVersion::V0 {
335                                 return None;
336                         }
337
338                         Some(address)
339                 };
340
341                 self.contents.fields().fallbacks
342                         .as_ref()
343                         .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
344                         .unwrap_or_else(Vec::new)
345         }
346
347         fn network(&self) -> Option<Network> {
348                 let chain = self.contents.chain();
349                 if chain == ChainHash::using_genesis_block(Network::Bitcoin) {
350                         Some(Network::Bitcoin)
351                 } else if chain == ChainHash::using_genesis_block(Network::Testnet) {
352                         Some(Network::Testnet)
353                 } else if chain == ChainHash::using_genesis_block(Network::Signet) {
354                         Some(Network::Signet)
355                 } else if chain == ChainHash::using_genesis_block(Network::Regtest) {
356                         Some(Network::Regtest)
357                 } else {
358                         None
359                 }
360         }
361
362         /// Features pertaining to paying an invoice.
363         pub fn features(&self) -> &Bolt12InvoiceFeatures {
364                 &self.contents.fields().features
365         }
366
367         /// The public key used to sign invoices.
368         pub fn signing_pubkey(&self) -> PublicKey {
369                 self.contents.fields().signing_pubkey
370         }
371
372         /// Signature of the invoice using [`Invoice::signing_pubkey`].
373         pub fn signature(&self) -> Signature {
374                 self.signature
375         }
376 }
377
378 impl InvoiceContents {
379         /// Whether the original offer or refund has expired.
380         #[cfg(feature = "std")]
381         fn is_offer_or_refund_expired(&self) -> bool {
382                 match self {
383                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
384                         InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
385                 }
386         }
387
388         fn chain(&self) -> ChainHash {
389                 match self {
390                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
391                         InvoiceContents::ForRefund { refund, .. } => refund.chain(),
392                 }
393         }
394
395         fn fields(&self) -> &InvoiceFields {
396                 match self {
397                         InvoiceContents::ForOffer { fields, .. } => fields,
398                         InvoiceContents::ForRefund { fields, .. } => fields,
399                 }
400         }
401
402         fn fields_mut(&mut self) -> &mut InvoiceFields {
403                 match self {
404                         InvoiceContents::ForOffer { fields, .. } => fields,
405                         InvoiceContents::ForRefund { fields, .. } => fields,
406                 }
407         }
408
409         fn as_tlv_stream(&self) -> PartialInvoiceTlvStreamRef {
410                 let (payer, offer, invoice_request) = match self {
411                         InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.as_tlv_stream(),
412                         InvoiceContents::ForRefund { refund, .. } => refund.as_tlv_stream(),
413                 };
414                 let invoice = self.fields().as_tlv_stream();
415
416                 (payer, offer, invoice_request, invoice)
417         }
418 }
419
420 impl InvoiceFields {
421         fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
422                 let features = {
423                         if self.features == Bolt12InvoiceFeatures::empty() { None }
424                         else { Some(&self.features) }
425                 };
426
427                 InvoiceTlvStreamRef {
428                         paths: Some(Iterable(self.payment_paths.iter().map(|(path, _)| path))),
429                         blindedpay: Some(Iterable(self.payment_paths.iter().map(|(_, payinfo)| payinfo))),
430                         created_at: Some(self.created_at.as_secs()),
431                         relative_expiry: self.relative_expiry.map(|duration| duration.as_secs() as u32),
432                         payment_hash: Some(&self.payment_hash),
433                         amount: Some(self.amount_msats),
434                         fallbacks: self.fallbacks.as_ref(),
435                         features,
436                         node_id: Some(&self.signing_pubkey),
437                 }
438         }
439 }
440
441 impl Writeable for Invoice {
442         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
443                 WithoutLength(&self.bytes).write(writer)
444         }
445 }
446
447 impl TryFrom<Vec<u8>> for Invoice {
448         type Error = ParseError;
449
450         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
451                 let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
452                 Invoice::try_from(parsed_invoice)
453         }
454 }
455
456 tlv_stream!(InvoiceTlvStream, InvoiceTlvStreamRef, 160..240, {
457         (160, paths: (Vec<BlindedPath>, WithoutLength, Iterable<'a, BlindedPathIter<'a>, BlindedPath>)),
458         (162, blindedpay: (Vec<BlindedPayInfo>, WithoutLength, Iterable<'a, BlindedPayInfoIter<'a>, BlindedPayInfo>)),
459         (164, created_at: (u64, HighZeroBytesDroppedBigSize)),
460         (166, relative_expiry: (u32, HighZeroBytesDroppedBigSize)),
461         (168, payment_hash: PaymentHash),
462         (170, amount: (u64, HighZeroBytesDroppedBigSize)),
463         (172, fallbacks: (Vec<FallbackAddress>, WithoutLength)),
464         (174, features: (Bolt12InvoiceFeatures, WithoutLength)),
465         (176, node_id: PublicKey),
466 });
467
468 type BlindedPathIter<'a> = core::iter::Map<
469         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
470         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
471 >;
472
473 type BlindedPayInfoIter<'a> = core::iter::Map<
474         core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
475         for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
476 >;
477
478 /// Information needed to route a payment across a [`BlindedPath`].
479 #[derive(Debug, PartialEq)]
480 pub struct BlindedPayInfo {
481         fee_base_msat: u32,
482         fee_proportional_millionths: u32,
483         cltv_expiry_delta: u16,
484         htlc_minimum_msat: u64,
485         htlc_maximum_msat: u64,
486         features: BlindedHopFeatures,
487 }
488
489 impl_writeable!(BlindedPayInfo, {
490         fee_base_msat,
491         fee_proportional_millionths,
492         cltv_expiry_delta,
493         htlc_minimum_msat,
494         htlc_maximum_msat,
495         features
496 });
497
498 /// Wire representation for an on-chain fallback address.
499 #[derive(Debug, PartialEq)]
500 pub(super) struct FallbackAddress {
501         version: u8,
502         program: Vec<u8>,
503 }
504
505 impl_writeable!(FallbackAddress, { version, program });
506
507 type FullInvoiceTlvStream =
508         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
509
510 impl SeekReadable for FullInvoiceTlvStream {
511         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
512                 let payer = SeekReadable::read(r)?;
513                 let offer = SeekReadable::read(r)?;
514                 let invoice_request = SeekReadable::read(r)?;
515                 let invoice = SeekReadable::read(r)?;
516                 let signature = SeekReadable::read(r)?;
517
518                 Ok((payer, offer, invoice_request, invoice, signature))
519         }
520 }
521
522 type PartialInvoiceTlvStream =
523         (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
524
525 type PartialInvoiceTlvStreamRef<'a> = (
526         PayerTlvStreamRef<'a>,
527         OfferTlvStreamRef<'a>,
528         InvoiceRequestTlvStreamRef<'a>,
529         InvoiceTlvStreamRef<'a>,
530 );
531
532 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
533         type Error = ParseError;
534
535         fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
536                 let ParsedMessage { bytes, tlv_stream } = invoice;
537                 let (
538                         payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
539                         SignatureTlvStream { signature },
540                 ) = tlv_stream;
541                 let contents = InvoiceContents::try_from(
542                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
543                 )?;
544
545                 let signature = match signature {
546                         None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
547                         Some(signature) => signature,
548                 };
549                 let pubkey = contents.fields().signing_pubkey;
550                 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
551
552                 Ok(Invoice { bytes, contents, signature })
553         }
554 }
555
556 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
557         type Error = SemanticError;
558
559         fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
560                 let (
561                         payer_tlv_stream,
562                         offer_tlv_stream,
563                         invoice_request_tlv_stream,
564                         InvoiceTlvStream {
565                                 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
566                                 features, node_id,
567                         },
568                 ) = tlv_stream;
569
570                 let payment_paths = match (paths, blindedpay) {
571                         (None, _) => return Err(SemanticError::MissingPaths),
572                         (_, None) => return Err(SemanticError::InvalidPayInfo),
573                         (Some(paths), _) if paths.is_empty() => return Err(SemanticError::MissingPaths),
574                         (Some(paths), Some(blindedpay)) if paths.len() != blindedpay.len() => {
575                                 return Err(SemanticError::InvalidPayInfo);
576                         },
577                         (Some(paths), Some(blindedpay)) => {
578                                 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
579                         },
580                 };
581
582                 let created_at = match created_at {
583                         None => return Err(SemanticError::MissingCreationTime),
584                         Some(timestamp) => Duration::from_secs(timestamp),
585                 };
586
587                 let relative_expiry = relative_expiry
588                         .map(Into::<u64>::into)
589                         .map(Duration::from_secs);
590
591                 let payment_hash = match payment_hash {
592                         None => return Err(SemanticError::MissingPaymentHash),
593                         Some(payment_hash) => payment_hash,
594                 };
595
596                 let amount_msats = match amount {
597                         None => return Err(SemanticError::MissingAmount),
598                         Some(amount) => amount,
599                 };
600
601                 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
602
603                 let signing_pubkey = match node_id {
604                         None => return Err(SemanticError::MissingSigningPubkey),
605                         Some(node_id) => node_id,
606                 };
607
608                 let fields = InvoiceFields {
609                         payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
610                         features, signing_pubkey,
611                 };
612
613                 match offer_tlv_stream.node_id {
614                         Some(expected_signing_pubkey) => {
615                                 if fields.signing_pubkey != expected_signing_pubkey {
616                                         return Err(SemanticError::InvalidSigningPubkey);
617                                 }
618
619                                 let invoice_request = InvoiceRequestContents::try_from(
620                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
621                                 )?;
622                                 Ok(InvoiceContents::ForOffer { invoice_request, fields })
623                         },
624                         None => {
625                                 let refund = RefundContents::try_from(
626                                         (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
627                                 )?;
628                                 Ok(InvoiceContents::ForRefund { refund, fields })
629                         },
630                 }
631         }
632 }