1 // This file is Copyright its original authors, visible in version control
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
10 //! Data structures and encoding for `invoice` messages.
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.
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.
20 //! extern crate bitcoin;
21 //! extern crate lightning;
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;
30 //! # use lightning::ln::PaymentHash;
31 //! # use lightning::offers::invoice::BlindedPayInfo;
32 //! # use lightning::onion_message::BlindedPath;
34 //! # fn create_payment_paths() -> Vec<(BlindedPath, BlindedPayInfo)> { unimplemented!() }
35 //! # fn create_payment_hash() -> PaymentHash { unimplemented!() }
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();
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)
51 //! .fallback_v0_p2wpkh(&wpubkey_hash)
53 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
54 //! .expect("failed verifying signature")
55 //! .write(&mut buffer)
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();
69 //! // Invoice for the "offer for money" flow.
71 //! .parse::<Refund>()?
72 //! .respond_with(payment_paths, payment_hash, pubkey)?
73 //! .relative_expiry(3600)
75 //! .fallback_v0_p2wpkh(&wpubkey_hash)
77 //! .sign::<_, Infallible>(|digest| Ok(secp_ctx.sign_schnorr_no_aux_rand(digest, &keys)))
78 //! .expect("failed verifying signature")
79 //! .write(&mut buffer)
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;
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};
109 use crate::prelude::*;
111 #[cfg(feature = "std")]
112 use std::time::SystemTime;
114 const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(7200);
116 const SIGNATURE_TAG: &'static str = concat!("lightning", "invoice", "signature");
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.
122 /// See [module-level documentation] for usage.
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,
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)
143 Some(Amount::Currency { .. }) => return Err(SemanticError::UnsupportedCurrency),
144 None => return Err(SemanticError::MissingAmount),
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(),
157 Self::new(&invoice_request.bytes, contents)
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,
173 Self::new(&refund.bytes, contents)
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);
181 Ok(Self { invreq_bytes, invoice: contents })
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`].
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);
194 /// Adds a P2WSH address to [`Invoice::fallbacks`].
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()[..]),
203 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
207 /// Adds a P2WPKH address to [`Invoice::fallbacks`].
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()[..]),
216 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
220 /// Adds a P2TR address to [`Invoice::fallbacks`].
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()[..]),
229 self.invoice.fields_mut().fallbacks.get_or_insert_with(Vec::new).push(address);
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();
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);
248 let InvoiceBuilder { invreq_bytes, invoice } = self;
249 Ok(UnsignedInvoice { invreq_bytes, invoice })
253 /// A semantically valid [`Invoice`] that hasn't been signed.
254 pub struct UnsignedInvoice<'a> {
255 invreq_bytes: &'a Vec<u8>,
256 invoice: InvoiceContents,
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>>
263 F: FnOnce(&Message) -> Result<Signature, E>
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
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);
272 let mut bytes = Vec::new();
273 unsigned_tlv_stream.write(&mut bytes).unwrap();
275 let pubkey = self.invoice.fields().signing_pubkey;
276 let signature = merkle::sign_message(sign, SIGNATURE_TAG, &bytes, pubkey)?;
278 // Append the signature TLV record to the bytes.
279 let signature_tlv_stream = SignatureTlvStreamRef {
280 signature: Some(&signature),
282 signature_tlv_stream.write(&mut bytes).unwrap();
286 contents: self.invoice,
292 /// An `Invoice` is a payment request, typically corresponding to an [`Offer`] or a [`Refund`].
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.
297 /// [`Offer`]: crate::offers::offer::Offer
298 /// [`Refund`]: crate::offers::refund::Refund
299 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
302 contents: InvoiceContents,
303 signature: Signature,
306 /// The contents of an [`Invoice`] for responding to either an [`Offer`] or a [`Refund`].
308 /// [`Offer`]: crate::offers::offer::Offer
309 /// [`Refund`]: crate::offers::refund::Refund
310 enum InvoiceContents {
311 /// Contents for an [`Invoice`] corresponding to an [`Offer`].
313 /// [`Offer`]: crate::offers::offer::Offer
315 invoice_request: InvoiceRequestContents,
316 fields: InvoiceFields,
318 /// Contents for an [`Invoice`] corresponding to a [`Refund`].
320 /// [`Refund`]: crate::offers::refund::Refund
322 refund: RefundContents,
323 fields: InvoiceFields,
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,
334 fallbacks: Option<Vec<FallbackAddress>>,
335 features: Bolt12InvoiceFeatures,
336 signing_pubkey: PublicKey,
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[..]
347 /// Duration since the Unix epoch when the invoice was created.
348 pub fn created_at(&self) -> Duration {
349 self.contents.fields().created_at
352 /// Duration since [`Invoice::created_at`] when the invoice has expired and therefore should no
354 pub fn relative_expiry(&self) -> Duration {
355 self.contents.fields().relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
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,
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
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
381 /// Fallback addresses for paying the invoice on-chain, in order of most-preferred to
383 pub fn fallbacks(&self) -> Vec<Address> {
384 let network = match self.network() {
385 None => return Vec::new(),
386 Some(network) => network,
389 let to_valid_address = |address: &FallbackAddress| {
390 let version = match WitnessVersion::try_from(address.version) {
391 Ok(version) => version,
392 Err(_) => return None,
395 let program = &address.program;
396 if program.len() < 2 || program.len() > 40 {
400 let address = Address {
401 payload: Payload::WitnessProgram {
403 program: address.program.clone(),
408 if !address.is_standard() && version == WitnessVersion::V0 {
415 self.contents.fields().fallbacks
417 .map(|fallbacks| fallbacks.iter().filter_map(to_valid_address).collect())
418 .unwrap_or_else(Vec::new)
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)
436 /// Features pertaining to paying an invoice.
437 pub fn features(&self) -> &Bolt12InvoiceFeatures {
438 &self.contents.fields().features
441 /// The public key used to sign invoices.
442 pub fn signing_pubkey(&self) -> PublicKey {
443 self.contents.fields().signing_pubkey
446 /// Signature of the invoice using [`Invoice::signing_pubkey`].
447 pub fn signature(&self) -> Signature {
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 {
457 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.offer.is_expired(),
458 InvoiceContents::ForRefund { refund, .. } => refund.is_expired(),
462 fn chain(&self) -> ChainHash {
464 InvoiceContents::ForOffer { invoice_request, .. } => invoice_request.chain(),
465 InvoiceContents::ForRefund { refund, .. } => refund.chain(),
469 fn fields(&self) -> &InvoiceFields {
471 InvoiceContents::ForOffer { fields, .. } => fields,
472 InvoiceContents::ForRefund { fields, .. } => fields,
476 fn fields_mut(&mut self) -> &mut InvoiceFields {
478 InvoiceContents::ForOffer { fields, .. } => fields,
479 InvoiceContents::ForRefund { fields, .. } => fields,
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(),
488 let invoice = self.fields().as_tlv_stream();
490 (payer, offer, invoice_request, invoice)
495 fn as_tlv_stream(&self) -> InvoiceTlvStreamRef {
497 if self.features == Bolt12InvoiceFeatures::empty() { None }
498 else { Some(&self.features) }
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(),
510 node_id: Some(&self.signing_pubkey),
515 impl Writeable for Invoice {
516 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
517 WithoutLength(&self.bytes).write(writer)
521 impl TryFrom<Vec<u8>> for Invoice {
522 type Error = ParseError;
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)
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),
542 type BlindedPathIter<'a> = core::iter::Map<
543 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
544 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPath,
547 type BlindedPayInfoIter<'a> = core::iter::Map<
548 core::slice::Iter<'a, (BlindedPath, BlindedPayInfo)>,
549 for<'r> fn(&'r (BlindedPath, BlindedPayInfo)) -> &'r BlindedPayInfo,
552 /// Information needed to route a payment across a [`BlindedPath`].
553 #[derive(Debug, PartialEq)]
554 pub struct BlindedPayInfo {
556 fee_proportional_millionths: u32,
557 cltv_expiry_delta: u16,
558 htlc_minimum_msat: u64,
559 htlc_maximum_msat: u64,
560 features: BlindedHopFeatures,
563 impl_writeable!(BlindedPayInfo, {
565 fee_proportional_millionths,
572 /// Wire representation for an on-chain fallback address.
573 #[derive(Debug, PartialEq)]
574 pub(super) struct FallbackAddress {
579 impl_writeable!(FallbackAddress, { version, program });
581 type FullInvoiceTlvStream =
582 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream, SignatureTlvStream);
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)?;
592 Ok((payer, offer, invoice_request, invoice, signature))
596 type PartialInvoiceTlvStream =
597 (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream, InvoiceTlvStream);
599 type PartialInvoiceTlvStreamRef<'a> = (
600 PayerTlvStreamRef<'a>,
601 OfferTlvStreamRef<'a>,
602 InvoiceRequestTlvStreamRef<'a>,
603 InvoiceTlvStreamRef<'a>,
606 impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for Invoice {
607 type Error = ParseError;
609 fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
610 let ParsedMessage { bytes, tlv_stream } = invoice;
612 payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream,
613 SignatureTlvStream { signature },
615 let contents = InvoiceContents::try_from(
616 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream, invoice_tlv_stream)
619 let signature = match signature {
620 None => return Err(ParseError::InvalidSemantics(SemanticError::MissingSignature)),
621 Some(signature) => signature,
623 let pubkey = contents.fields().signing_pubkey;
624 merkle::verify_signature(&signature, SIGNATURE_TAG, &bytes, pubkey)?;
626 Ok(Invoice { bytes, contents, signature })
630 impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
631 type Error = SemanticError;
633 fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
637 invoice_request_tlv_stream,
639 paths, blindedpay, created_at, relative_expiry, payment_hash, amount, fallbacks,
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);
651 (Some(paths), Some(blindedpay)) => {
652 paths.into_iter().zip(blindedpay.into_iter()).collect::<Vec<_>>()
656 let created_at = match created_at {
657 None => return Err(SemanticError::MissingCreationTime),
658 Some(timestamp) => Duration::from_secs(timestamp),
661 let relative_expiry = relative_expiry
662 .map(Into::<u64>::into)
663 .map(Duration::from_secs);
665 let payment_hash = match payment_hash {
666 None => return Err(SemanticError::MissingPaymentHash),
667 Some(payment_hash) => payment_hash,
670 let amount_msats = match amount {
671 None => return Err(SemanticError::MissingAmount),
672 Some(amount) => amount,
675 let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
677 let signing_pubkey = match node_id {
678 None => return Err(SemanticError::MissingSigningPubkey),
679 Some(node_id) => node_id,
682 let fields = InvoiceFields {
683 payment_paths, created_at, relative_expiry, payment_hash, amount_msats, fallbacks,
684 features, signing_pubkey,
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);
693 let invoice_request = InvoiceRequestContents::try_from(
694 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
696 Ok(InvoiceContents::ForOffer { invoice_request, fields })
699 let refund = RefundContents::try_from(
700 (payer_tlv_stream, offer_tlv_stream, invoice_request_tlv_stream)
702 Ok(InvoiceContents::ForRefund { refund, fields })