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