12
12
use crate :: blinded_path:: BlindedPath ;
13
13
use crate :: io;
14
14
use crate :: ln:: features:: { Bolt12InvoiceFeatures , OfferFeatures } ;
15
+ use crate :: ln:: inbound_payment:: ExpandedKey ;
15
16
use crate :: ln:: msgs:: DecodeError ;
16
17
use crate :: offers:: invoice:: {
17
18
check_invoice_signing_pubkey, construct_payment_paths, filter_fallbacks, BlindedPathIter ,
18
19
BlindedPayInfo , BlindedPayInfoIter , FallbackAddress , InvoiceTlvStream , InvoiceTlvStreamRef ,
19
20
} ;
20
- use crate :: offers:: invoice_macros:: invoice_accessors_common;
21
- use crate :: offers:: merkle:: { self , SignatureTlvStream , TaggedHash } ;
22
- use crate :: offers:: offer:: { Amount , OfferContents , OfferTlvStream , Quantity } ;
21
+ use crate :: offers:: invoice_macros:: { invoice_accessors_common, invoice_builder_methods_common} ;
22
+ use crate :: offers:: merkle:: {
23
+ self , SignError , SignFn , SignatureTlvStream , SignatureTlvStreamRef , TaggedHash ,
24
+ } ;
25
+ use crate :: offers:: offer:: {
26
+ Amount , Offer , OfferContents , OfferTlvStream , OfferTlvStreamRef , Quantity ,
27
+ } ;
23
28
use crate :: offers:: parse:: { Bolt12ParseError , Bolt12SemanticError , ParsedMessage } ;
24
29
use crate :: util:: ser:: {
25
30
HighZeroBytesDroppedBigSize , Iterable , SeekReadable , WithoutLength , Writeable , Writer ,
@@ -28,7 +33,7 @@ use crate::util::string::PrintableString;
28
33
use bitcoin:: address:: Address ;
29
34
use bitcoin:: blockdata:: constants:: ChainHash ;
30
35
use bitcoin:: secp256k1:: schnorr:: Signature ;
31
- use bitcoin:: secp256k1:: PublicKey ;
36
+ use bitcoin:: secp256k1:: { self , Keypair , PublicKey , Secp256k1 } ;
32
37
use core:: time:: Duration ;
33
38
34
39
#[ cfg( feature = "std" ) ]
@@ -75,6 +80,93 @@ struct InvoiceContents {
75
80
message_paths : Vec < BlindedPath > ,
76
81
}
77
82
83
+ /// Builds a [`StaticInvoice`] from an [`Offer`].
84
+ ///
85
+ /// [`Offer`]: crate::offers::offer::Offer
86
+ /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
87
+ // TODO: add module-level docs and link here
88
+ pub struct StaticInvoiceBuilder < ' a > {
89
+ offer_bytes : & ' a Vec < u8 > ,
90
+ invoice : InvoiceContents ,
91
+ keys : Keypair ,
92
+ }
93
+
94
+ impl < ' a > StaticInvoiceBuilder < ' a > {
95
+ /// Initialize a [`StaticInvoiceBuilder`] from the given [`Offer`].
96
+ ///
97
+ /// Unless [`StaticInvoiceBuilder::relative_expiry`] is set, the invoice will expire 24 hours
98
+ /// after `created_at`.
99
+ pub fn for_offer_using_derived_keys < T : secp256k1:: Signing > (
100
+ offer : & ' a Offer , payment_paths : Vec < ( BlindedPayInfo , BlindedPath ) > ,
101
+ message_paths : Vec < BlindedPath > , created_at : Duration , expanded_key : & ExpandedKey ,
102
+ secp_ctx : & Secp256k1 < T > ,
103
+ ) -> Result < Self , Bolt12SemanticError > {
104
+ if offer. chains ( ) . len ( ) > 1 {
105
+ return Err ( Bolt12SemanticError :: UnexpectedChain ) ;
106
+ }
107
+
108
+ if payment_paths. is_empty ( ) || message_paths. is_empty ( ) || offer. paths ( ) . is_empty ( ) {
109
+ return Err ( Bolt12SemanticError :: MissingPaths ) ;
110
+ }
111
+
112
+ let offer_signing_pubkey =
113
+ offer. signing_pubkey ( ) . ok_or ( Bolt12SemanticError :: MissingSigningPubkey ) ?;
114
+
115
+ let keys = offer
116
+ . verify ( & expanded_key, & secp_ctx)
117
+ . map_err ( |( ) | Bolt12SemanticError :: InvalidMetadata ) ?
118
+ . 1
119
+ . ok_or ( Bolt12SemanticError :: MissingSigningPubkey ) ?;
120
+
121
+ let signing_pubkey = keys. public_key ( ) ;
122
+ if signing_pubkey != offer_signing_pubkey {
123
+ return Err ( Bolt12SemanticError :: InvalidSigningPubkey ) ;
124
+ }
125
+
126
+ let invoice =
127
+ InvoiceContents :: new ( offer, payment_paths, message_paths, created_at, signing_pubkey) ;
128
+
129
+ Ok ( Self { offer_bytes : & offer. bytes , invoice, keys } )
130
+ }
131
+
132
+ /// Builds a signed [`StaticInvoice`] after checking for valid semantics.
133
+ pub fn build_and_sign < T : secp256k1:: Signing > (
134
+ self , secp_ctx : & Secp256k1 < T > ,
135
+ ) -> Result < StaticInvoice , Bolt12SemanticError > {
136
+ #[ cfg( feature = "std" ) ]
137
+ {
138
+ if self . invoice . is_offer_expired ( ) {
139
+ return Err ( Bolt12SemanticError :: AlreadyExpired ) ;
140
+ }
141
+ }
142
+
143
+ #[ cfg( not( feature = "std" ) ) ]
144
+ {
145
+ if self . invoice . is_offer_expired_no_std ( self . invoice . created_at ( ) ) {
146
+ return Err ( Bolt12SemanticError :: AlreadyExpired ) ;
147
+ }
148
+ }
149
+
150
+ let Self { offer_bytes, invoice, keys } = self ;
151
+ let unsigned_invoice = UnsignedStaticInvoice :: new ( & offer_bytes, invoice) ;
152
+ let invoice = unsigned_invoice
153
+ . sign ( |message : & UnsignedStaticInvoice | {
154
+ Ok ( secp_ctx. sign_schnorr_no_aux_rand ( message. tagged_hash . as_digest ( ) , & keys) )
155
+ } )
156
+ . unwrap ( ) ;
157
+ Ok ( invoice)
158
+ }
159
+
160
+ invoice_builder_methods_common ! ( self , Self , self . invoice, Self , self , S , StaticInvoice , mut ) ;
161
+ }
162
+
163
+ /// A semantically valid [`StaticInvoice`] that hasn't been signed.
164
+ pub struct UnsignedStaticInvoice {
165
+ bytes : Vec < u8 > ,
166
+ contents : InvoiceContents ,
167
+ tagged_hash : TaggedHash ,
168
+ }
169
+
78
170
macro_rules! invoice_accessors { ( $self: ident, $contents: expr) => {
79
171
/// The chain that must be used when paying the invoice. [`StaticInvoice`]s currently can only be
80
172
/// created from offers that support a single chain.
@@ -150,6 +242,68 @@ macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
150
242
}
151
243
} }
152
244
245
+ impl UnsignedStaticInvoice {
246
+ fn new ( offer_bytes : & Vec < u8 > , contents : InvoiceContents ) -> Self {
247
+ let ( _, invoice_tlv_stream) = contents. as_tlv_stream ( ) ;
248
+ let offer_bytes = WithoutLength ( offer_bytes) ;
249
+ let unsigned_tlv_stream = ( offer_bytes, invoice_tlv_stream) ;
250
+
251
+ let mut bytes = Vec :: new ( ) ;
252
+ unsigned_tlv_stream. write ( & mut bytes) . unwrap ( ) ;
253
+
254
+ let tagged_hash = TaggedHash :: from_valid_tlv_stream_bytes ( SIGNATURE_TAG , & bytes) ;
255
+
256
+ Self { contents, tagged_hash, bytes }
257
+ }
258
+
259
+ /// Signs the [`TaggedHash`] of the invoice using the given function.
260
+ ///
261
+ /// Note: The hash computation may have included unknown, odd TLV records.
262
+ pub fn sign < F : SignStaticInvoiceFn > ( mut self , sign : F ) -> Result < StaticInvoice , SignError > {
263
+ let pubkey = self . contents . signing_pubkey ;
264
+ let signature = merkle:: sign_message ( sign, & self , pubkey) ?;
265
+
266
+ // Append the signature TLV record to the bytes.
267
+ let signature_tlv_stream = SignatureTlvStreamRef { signature : Some ( & signature) } ;
268
+ signature_tlv_stream. write ( & mut self . bytes ) . unwrap ( ) ;
269
+
270
+ Ok ( StaticInvoice { bytes : self . bytes , contents : self . contents , signature } )
271
+ }
272
+
273
+ invoice_accessors_common ! ( self , self . contents, StaticInvoice ) ;
274
+ invoice_accessors ! ( self , self . contents) ;
275
+ }
276
+
277
+ impl AsRef < TaggedHash > for UnsignedStaticInvoice {
278
+ fn as_ref ( & self ) -> & TaggedHash {
279
+ & self . tagged_hash
280
+ }
281
+ }
282
+
283
+ /// A function for signing an [`UnsignedStaticInvoice`].
284
+ pub trait SignStaticInvoiceFn {
285
+ /// Signs a [`TaggedHash`] computed over the merkle root of `message`'s TLV stream.
286
+ fn sign_invoice ( & self , message : & UnsignedStaticInvoice ) -> Result < Signature , ( ) > ;
287
+ }
288
+
289
+ impl < F > SignStaticInvoiceFn for F
290
+ where
291
+ F : Fn ( & UnsignedStaticInvoice ) -> Result < Signature , ( ) > ,
292
+ {
293
+ fn sign_invoice ( & self , message : & UnsignedStaticInvoice ) -> Result < Signature , ( ) > {
294
+ self ( message)
295
+ }
296
+ }
297
+
298
+ impl < F > SignFn < UnsignedStaticInvoice > for F
299
+ where
300
+ F : SignStaticInvoiceFn ,
301
+ {
302
+ fn sign ( & self , message : & UnsignedStaticInvoice ) -> Result < Signature , ( ) > {
303
+ self . sign_invoice ( message)
304
+ }
305
+ }
306
+
153
307
impl StaticInvoice {
154
308
invoice_accessors_common ! ( self , self . contents, StaticInvoice ) ;
155
309
invoice_accessors ! ( self , self . contents) ;
@@ -161,6 +315,57 @@ impl StaticInvoice {
161
315
}
162
316
163
317
impl InvoiceContents {
318
+ #[ cfg( feature = "std" ) ]
319
+ fn is_offer_expired ( & self ) -> bool {
320
+ self . offer . is_expired ( )
321
+ }
322
+
323
+ #[ cfg( not( feature = "std" ) ) ]
324
+ fn is_offer_expired_no_std ( & self , duration_since_epoch : Duration ) -> bool {
325
+ self . offer . is_expired_no_std ( duration_since_epoch)
326
+ }
327
+
328
+ fn new (
329
+ offer : & Offer , payment_paths : Vec < ( BlindedPayInfo , BlindedPath ) > ,
330
+ message_paths : Vec < BlindedPath > , created_at : Duration , signing_pubkey : PublicKey ,
331
+ ) -> Self {
332
+ Self {
333
+ offer : offer. contents . clone ( ) ,
334
+ payment_paths,
335
+ message_paths,
336
+ created_at,
337
+ relative_expiry : None ,
338
+ fallbacks : None ,
339
+ features : Bolt12InvoiceFeatures :: empty ( ) ,
340
+ signing_pubkey,
341
+ }
342
+ }
343
+
344
+ fn as_tlv_stream ( & self ) -> PartialInvoiceTlvStreamRef {
345
+ let features = {
346
+ if self . features == Bolt12InvoiceFeatures :: empty ( ) {
347
+ None
348
+ } else {
349
+ Some ( & self . features )
350
+ }
351
+ } ;
352
+
353
+ let invoice = InvoiceTlvStreamRef {
354
+ paths : Some ( Iterable ( self . payment_paths . iter ( ) . map ( |( _, path) | path) ) ) ,
355
+ message_paths : Some ( self . message_paths . as_ref ( ) ) ,
356
+ blindedpay : Some ( Iterable ( self . payment_paths . iter ( ) . map ( |( payinfo, _) | payinfo) ) ) ,
357
+ created_at : Some ( self . created_at . as_secs ( ) ) ,
358
+ relative_expiry : self . relative_expiry . map ( |duration| duration. as_secs ( ) as u32 ) ,
359
+ fallbacks : self . fallbacks . as_ref ( ) ,
360
+ features,
361
+ node_id : Some ( & self . signing_pubkey ) ,
362
+ amount : None ,
363
+ payment_hash : None ,
364
+ } ;
365
+
366
+ ( self . offer . as_tlv_stream ( ) , invoice)
367
+ }
368
+
164
369
fn chain ( & self ) -> ChainHash {
165
370
debug_assert_eq ! ( self . offer. chains( ) . len( ) , 1 ) ;
166
371
self . offer . chains ( ) . first ( ) . cloned ( ) . unwrap_or_else ( || self . offer . implied_chain ( ) )
@@ -265,6 +470,8 @@ impl SeekReadable for FullInvoiceTlvStream {
265
470
266
471
type PartialInvoiceTlvStream = ( OfferTlvStream , InvoiceTlvStream ) ;
267
472
473
+ type PartialInvoiceTlvStreamRef < ' a > = ( OfferTlvStreamRef < ' a > , InvoiceTlvStreamRef < ' a > ) ;
474
+
268
475
impl TryFrom < ParsedMessage < FullInvoiceTlvStream > > for StaticInvoice {
269
476
type Error = Bolt12ParseError ;
270
477
0 commit comments