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