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