forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow.rs
More file actions
1782 lines (1597 loc) · 66.7 KB
/
flow.rs
File metadata and controls
1782 lines (1597 loc) · 66.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Provides data structures and functions for creating and managing Offers messages,
//! facilitating communication, and handling BOLT12 messages and payments.
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
use bitcoin::block::Header;
use bitcoin::constants::ChainHash;
use bitcoin::secp256k1::{self, PublicKey, Secp256k1};
use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, MessageContext, MessageForwardNode, OffersContext,
};
use crate::blinded_path::payment::{
AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext,
PaymentConstraints, PaymentContext, ReceiveTlvs,
};
use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
#[allow(unused_imports)]
use crate::prelude::*;
use crate::chain::BestBlock;
use crate::ln::channel_state::ChannelDetails;
use crate::ln::channelmanager::{InterceptId, PaymentId, CLTV_FAR_FAR_AWAY};
use crate::ln::inbound_payment;
use crate::offers::async_receive_offer_cache::AsyncReceiveOfferCache;
use crate::offers::invoice::{
Bolt12Invoice, DerivedSigningPubkey, ExplicitSigningPubkey, InvoiceBuilder,
DEFAULT_RELATIVE_EXPIRY,
};
use crate::offers::invoice_request::{
InvoiceRequest, InvoiceRequestBuilder, InvoiceRequestVerifiedFromOffer, VerifiedInvoiceRequest,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{Amount, DerivedMetadata, Offer, OfferBuilder};
use crate::offers::parse::Bolt12SemanticError;
use crate::offers::refund::{Refund, RefundBuilder};
use crate::offers::static_invoice::{StaticInvoice, StaticInvoiceBuilder};
use crate::onion_message::async_payments::{
AsyncPaymentsMessage, HeldHtlcAvailable, OfferPaths, OfferPathsRequest, ServeStaticInvoice,
StaticInvoicePersisted,
};
use crate::onion_message::messenger::{
Destination, MessageRouter, MessageSendInstructions, Responder, DUMMY_HOPS_PATH_LENGTH,
};
use crate::onion_message::offers::OffersMessage;
use crate::onion_message::packet::OnionMessageContents;
use crate::routing::router::Router;
use crate::sign::{EntropySource, ReceiveAuthKey};
use crate::sync::{Mutex, RwLock};
use crate::types::payment::{PaymentHash, PaymentSecret};
use crate::util::logger::Logger;
use crate::util::ser::Writeable;
#[cfg(feature = "dnssec")]
use {
crate::blinded_path::message::DNSResolverContext,
crate::onion_message::dns_resolution::{DNSResolverMessage, DNSSECQuery, OMNameResolver},
};
/// A BOLT12 offers code and flow utility provider, which facilitates
/// BOLT12 builder generation and onion message handling.
///
/// [`OffersMessageFlow`] is parameterized by a [`MessageRouter`], which is responsible
/// for finding message paths when initiating and retrying onion messages.
pub struct OffersMessageFlow<MR: MessageRouter, L: Logger> {
chain_hash: ChainHash,
best_block: RwLock<BestBlock>,
our_network_pubkey: PublicKey,
highest_seen_timestamp: AtomicUsize,
inbound_payment_key: inbound_payment::ExpandedKey,
receive_auth_key: ReceiveAuthKey,
secp_ctx: Secp256k1<secp256k1::All>,
message_router: MR,
#[cfg(not(any(test, feature = "_test_utils")))]
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
#[cfg(any(test, feature = "_test_utils"))]
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
pending_async_payments_messages: Mutex<Vec<(AsyncPaymentsMessage, MessageSendInstructions)>>,
async_receive_offer_cache: Mutex<AsyncReceiveOfferCache>,
#[cfg(feature = "dnssec")]
pub(crate) hrn_resolver: OMNameResolver,
#[cfg(feature = "dnssec")]
pending_dns_onion_messages: Mutex<Vec<(DNSResolverMessage, MessageSendInstructions)>>,
logger: L,
}
impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// Creates a new [`OffersMessageFlow`]
pub fn new(
chain_hash: ChainHash, best_block: BestBlock, our_network_pubkey: PublicKey,
current_timestamp: u32, inbound_payment_key: inbound_payment::ExpandedKey,
receive_auth_key: ReceiveAuthKey, secp_ctx: Secp256k1<secp256k1::All>, message_router: MR,
logger: L,
) -> Self {
Self {
chain_hash,
best_block: RwLock::new(best_block),
our_network_pubkey,
highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
inbound_payment_key,
receive_auth_key,
secp_ctx,
message_router,
pending_offers_messages: Mutex::new(Vec::new()),
pending_async_payments_messages: Mutex::new(Vec::new()),
#[cfg(feature = "dnssec")]
hrn_resolver: OMNameResolver::new(current_timestamp, best_block.height),
#[cfg(feature = "dnssec")]
pending_dns_onion_messages: Mutex::new(Vec::new()),
async_receive_offer_cache: Mutex::new(AsyncReceiveOfferCache::new()),
logger,
}
}
/// If we are an async recipient, on startup we'll interactively build offers and static invoices
/// with an always-online node that will serve static invoices on our behalf. Once the offer is
/// built and the static invoice is confirmed as persisted by the server, the underlying
/// [`AsyncReceiveOfferCache`] should be persisted using
/// [`Self::writeable_async_receive_offer_cache`] so we remember the offers we've built.
pub fn with_async_payments_offers_cache(
mut self, async_receive_offer_cache: AsyncReceiveOfferCache,
) -> Self {
self.async_receive_offer_cache = Mutex::new(async_receive_offer_cache);
self
}
/// Sets the [`BlindedMessagePath`]s that we will use as an async recipient to interactively build
/// [`Offer`]s with a static invoice server, so the server can serve [`StaticInvoice`]s to payers
/// on our behalf when we're offline.
///
/// This method will also send out messages initiating async offer creation to the static invoice
/// server, if any peers are connected.
///
/// This method only needs to be called once when the server first takes on the recipient as a
/// client, or when the paths change, e.g. if the paths are set to expire at a particular time.
pub fn set_paths_to_static_invoice_server(
&self, paths_to_static_invoice_server: Vec<BlindedMessagePath>,
peers: Vec<MessageForwardNode>,
) -> Result<(), ()> {
let mut cache = self.async_receive_offer_cache.lock().unwrap();
cache.set_paths_to_static_invoice_server(paths_to_static_invoice_server.clone())?;
core::mem::drop(cache);
// We'll only fail here if no peers are connected yet for us to create reply paths to outbound
// offer_paths_requests, so ignore the error.
let _ = self.check_refresh_async_offers(peers, false);
Ok(())
}
/// Gets the node_id held by this [`OffersMessageFlow`]`
fn get_our_node_id(&self) -> PublicKey {
self.our_network_pubkey
}
fn get_receive_auth_key(&self) -> ReceiveAuthKey {
self.receive_auth_key
}
fn duration_since_epoch(&self) -> Duration {
#[cfg(any(not(feature = "std"), fuzzing))]
let now = Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64);
#[cfg(all(feature = "std", not(fuzzing)))]
let now = std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
now
}
/// Notifies the [`OffersMessageFlow`] that a new block has been observed.
///
/// This allows the flow to keep in sync with the latest block timestamp,
/// which may be used for time-sensitive operations.
///
/// Must be called whenever a new chain tip becomes available. May be skipped
/// for intermediary blocks.
pub fn best_block_updated(&self, header: &Header, _height: u32) {
let timestamp = &self.highest_seen_timestamp;
let block_time = header.time as usize;
loop {
// Update timestamp to be the max of its current value and the block
// timestamp. This should keep us close to the current time without relying on
// having an explicit local time source.
// Just in case we end up in a race, we loop until we either successfully
// update timestamp or decide we don't need to.
let old_serial = timestamp.load(Ordering::Acquire);
if old_serial >= block_time {
break;
}
if timestamp
.compare_exchange(old_serial, block_time, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
break;
}
}
#[cfg(feature = "dnssec")]
{
let updated_time = timestamp.load(Ordering::Acquire) as u32;
self.hrn_resolver.new_best_block(_height, updated_time);
}
}
}
/// The maximum size of a received [`StaticInvoice`] before we'll fail verification in
/// [`OffersMessageFlow::verify_serve_static_invoice_message].
pub const MAX_STATIC_INVOICE_SIZE_BYTES: usize = 5 * 1024;
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
/// along different paths.
/// Sending multiple requests increases the chances of successful delivery in case some
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
/// even if multiple invoices are received.
const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
#[cfg(test)]
pub(crate) const TEST_OFFERS_MESSAGE_REQUEST_LIMIT: usize = OFFERS_MESSAGE_REQUEST_LIMIT;
/// The default relative expiry for reply paths where a quick response is expected and the reply
/// path is single-use.
const TEMP_REPLY_PATH_RELATIVE_EXPIRY: Duration = Duration::from_secs(2 * 60 * 60);
#[cfg(test)]
pub(crate) const TEST_TEMP_REPLY_PATH_RELATIVE_EXPIRY: Duration = TEMP_REPLY_PATH_RELATIVE_EXPIRY;
// Default to async receive offers and the paths used to update them lasting one year.
const DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY: Duration = Duration::from_secs(365 * 24 * 60 * 60);
#[cfg(test)]
pub(crate) const TEST_DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY: Duration =
DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY;
impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`BlindedMessagePath`]s for an async recipient to communicate with this node and interactively
/// build [`Offer`]s and [`StaticInvoice`]s for receiving async payments.
///
/// If `relative_expiry` is unset, the [`BlindedMessagePath`]s will never expire.
///
/// Returns the paths that the recipient should be configured with via
/// [`Self::set_paths_to_static_invoice_server`].
///
/// Errors if blinded path creation fails or the provided `recipient_id` is larger than 1KiB.
pub fn blinded_paths_for_async_recipient(
&self, recipient_id: Vec<u8>, relative_expiry: Option<Duration>,
peers: Vec<MessageForwardNode>,
) -> Result<Vec<BlindedMessagePath>, ()> {
if recipient_id.len() > 1024 {
log_trace!(self.logger, "Async recipient ID exceeds 1024 bytes");
return Err(());
}
let path_absolute_expiry =
relative_expiry.map(|exp| exp.saturating_add(self.duration_since_epoch()));
let context = MessageContext::AsyncPayments(AsyncPaymentsContext::OfferPathsRequest {
recipient_id,
path_absolute_expiry,
});
self.create_blinded_paths(peers, context)
}
fn blinded_paths_for_phantom_offer(
&self, per_node_peers: Vec<(PublicKey, Vec<MessageForwardNode>)>, path_count_limit: usize,
context: MessageContext,
) -> Result<Vec<BlindedMessagePath>, ()> {
let receive_key = ReceiveAuthKey(self.inbound_payment_key.phantom_node_blinded_path_key);
let secp_ctx = &self.secp_ctx;
let mut per_node_paths: Vec<_> = per_node_peers
.into_iter()
.filter_map(|(recipient, peers)| {
self.message_router
.create_blinded_paths(recipient, receive_key, context.clone(), peers, secp_ctx)
.ok()
})
.collect();
let mut res = Vec::new();
while res.len() < path_count_limit && !per_node_paths.is_empty() {
for node_paths in per_node_paths.iter_mut() {
if let Some(path) = node_paths.pop() {
res.push(path);
}
}
per_node_paths.retain(|node_paths| !node_paths.is_empty());
}
if res.is_empty() {
Err(())
} else {
Ok(res)
}
}
/// Creates a collection of blinded paths by delegating to
/// [`MessageRouter::create_blinded_paths`].
///
/// Errors if the `MessageRouter` errors.
fn create_blinded_paths(
&self, peers: Vec<MessageForwardNode>, context: MessageContext,
) -> Result<Vec<BlindedMessagePath>, ()> {
let recipient = self.get_our_node_id();
let receive_key = self.get_receive_auth_key();
let secp_ctx = &self.secp_ctx;
self.message_router
.create_blinded_paths(recipient, receive_key, context, peers, secp_ctx)
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
}
/// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
/// [`Router::create_blinded_payment_paths`].
fn create_blinded_payment_paths<R: Router>(
&self, router: &R, usable_channels: Vec<ChannelDetails>, amount_msats: Option<u64>,
payment_secret: PaymentSecret, payment_context: PaymentContext,
relative_expiry_seconds: u32,
) -> Result<Vec<BlindedPaymentPath>, ()> {
let secp_ctx = &self.secp_ctx;
let receive_auth_key = self.receive_auth_key;
let payee_node_id = self.get_our_node_id();
// Assume shorter than usual block times to avoid spuriously failing payments too early.
const SECONDS_PER_BLOCK: u32 = 9 * 60;
let relative_expiry_blocks = relative_expiry_seconds / SECONDS_PER_BLOCK;
let max_cltv_expiry = core::cmp::max(relative_expiry_blocks, CLTV_FAR_FAR_AWAY)
.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS)
.saturating_add(self.best_block.read().unwrap().height);
let payee_tlvs = ReceiveTlvs {
payment_secret,
payment_constraints: PaymentConstraints { max_cltv_expiry, htlc_minimum_msat: 1 },
payment_context,
};
router.create_blinded_payment_paths(
payee_node_id,
receive_auth_key,
usable_channels,
payee_tlvs,
amount_msats,
secp_ctx,
)
}
#[cfg(test)]
/// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
/// [`Router::create_blinded_payment_paths`].
pub(crate) fn test_create_blinded_payment_paths<R: Router>(
&self, router: &R, usable_channels: Vec<ChannelDetails>, amount_msats: Option<u64>,
payment_secret: PaymentSecret, payment_context: PaymentContext,
relative_expiry_seconds: u32,
) -> Result<Vec<BlindedPaymentPath>, ()> {
self.create_blinded_payment_paths(
router,
usable_channels,
amount_msats,
payment_secret,
payment_context,
relative_expiry_seconds,
)
}
}
fn enqueue_onion_message_with_reply_paths<T: OnionMessageContents + Clone>(
message: T, message_paths: &[BlindedMessagePath], reply_paths: Vec<BlindedMessagePath>,
queue: &mut Vec<(T, MessageSendInstructions)>,
) {
reply_paths
.iter()
.flat_map(|reply_path| message_paths.iter().map(move |path| (path, reply_path)))
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
.for_each(|(path, reply_path)| {
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
destination: Destination::BlindedPath(path.clone()),
reply_path: reply_path.clone(),
};
queue.push((message.clone(), instructions));
});
}
/// Instructions for how to respond to an `InvoiceRequest`.
pub enum InvreqResponseInstructions {
/// We are the recipient of this payment, and a [`Bolt12Invoice`] should be sent in response to
/// the invoice request since it is now verified.
SendInvoice(InvoiceRequestVerifiedFromOffer),
/// We are a static invoice server and should respond to this invoice request by retrieving the
/// [`StaticInvoice`] corresponding to the `recipient_id` and `invoice_slot` and calling
/// [`OffersMessageFlow::enqueue_static_invoice`].
///
/// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice
SendStaticInvoice {
/// An identifier for the async recipient for whom we are serving [`StaticInvoice`]s.
///
/// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice
recipient_id: Vec<u8>,
/// The slot number for the specific invoice being requested by the payer.
invoice_slot: u16,
/// The invoice request that should be forwarded to the async recipient in case the
/// recipient is online to respond. Should be forwarded by calling
/// [`OffersMessageFlow::enqueue_invoice_request_to_forward`].
invoice_request: InvoiceRequest,
},
}
/// Parameters for the reply path to a [`HeldHtlcAvailable`] onion message.
pub enum HeldHtlcReplyPath {
/// The reply path to the [`HeldHtlcAvailable`] message should terminate at our node.
ToUs {
/// The id of the payment.
payment_id: PaymentId,
/// The peers to use when creating this reply path.
peers: Vec<MessageForwardNode>,
},
/// The reply path to the [`HeldHtlcAvailable`] message should terminate at our next-hop channel
/// counterparty, as they are holding our HTLC until they receive the corresponding
/// [`ReleaseHeldHtlc`] message.
///
/// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc
ToCounterparty {
/// The blinded path provided to us by our counterparty.
path: BlindedMessagePath,
},
}
impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// Verifies an [`InvoiceRequest`] using the provided [`OffersContext`] or the [`InvoiceRequest::metadata`].
///
/// - If an [`OffersContext::InvoiceRequest`] with a `nonce` is provided, verification is performed using recipient context data.
/// - If no context is provided but the [`InvoiceRequest`] contains [`Offer`] metadata, verification is performed using that metadata.
/// - If neither is available, verification fails.
///
/// # Errors
///
/// Returns an error if:
/// - Both [`OffersContext`] and [`InvoiceRequest`] metadata are absent or invalid.
/// - The verification process (via recipient context data or metadata) fails.
pub fn verify_invoice_request(
&self, invoice_request: InvoiceRequest, context: Option<OffersContext>,
) -> Result<InvreqResponseInstructions, ()> {
let secp_ctx = &self.secp_ctx;
let expanded_key = &self.inbound_payment_key;
let nonce = match context {
None if invoice_request.metadata().is_some() => None,
Some(OffersContext::InvoiceRequest { nonce }) => Some(nonce),
Some(OffersContext::StaticInvoiceRequested {
recipient_id,
invoice_slot,
path_absolute_expiry,
}) => {
if path_absolute_expiry < self.duration_since_epoch() {
log_trace!(self.logger, "Static invoice request has expired");
return Err(());
}
return Ok(InvreqResponseInstructions::SendStaticInvoice {
recipient_id,
invoice_slot,
invoice_request,
});
},
_ => return Err(()),
};
let invoice_request = match nonce {
Some(nonce) => {
invoice_request.verify_using_recipient_data(nonce, expanded_key, secp_ctx)
},
None => invoice_request.verify_using_metadata(expanded_key, secp_ctx),
}?;
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}
/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
) -> Result<PaymentId, ()> {
let secp_ctx = &self.secp_ctx;
let expanded_key = &self.inbound_payment_key;
match context {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
} else {
Err(())
}
},
_ => Err(()),
}
}
/// Verifies the provided [`AsyncPaymentsContext`] for an inbound [`HeldHtlcAvailable`] message.
///
/// Because blinded path contexts are verified as a part of onion message processing, this only
/// validates that the context is not yet expired based on `path_absolute_expiry`.
///
/// # Errors
///
/// Returns `Err(())` if:
/// - The inbound payment context has expired.
pub fn verify_inbound_async_payment_context(
&self, context: AsyncPaymentsContext,
) -> Result<(), ()> {
match context {
AsyncPaymentsContext::InboundPayment { path_absolute_expiry } => {
if self.duration_since_epoch() > path_absolute_expiry {
return Err(());
}
Ok(())
},
_ => Err(()),
}
}
fn create_offer_builder_intern<ES: EntropySource, PF, I>(
&self, entropy_source: ES, make_paths: PF,
) -> Result<(OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Nonce), Bolt12SemanticError>
where
PF: FnOnce(
PublicKey,
MessageContext,
&secp256k1::Secp256k1<secp256k1::All>,
) -> Result<I, Bolt12SemanticError>,
I: IntoIterator<Item = BlindedMessagePath>,
{
let node_id = self.get_our_node_id();
let expanded_key = &self.inbound_payment_key;
let entropy = entropy_source;
let secp_ctx = &self.secp_ctx;
let nonce = Nonce::from_entropy_source(entropy);
let context = MessageContext::Offers(OffersContext::InvoiceRequest { nonce });
let mut builder =
OfferBuilder::deriving_signing_pubkey(node_id, expanded_key, nonce, secp_ctx)
.chain_hash(self.chain_hash);
for path in make_paths(node_id, context, secp_ctx)? {
builder = builder.path(path)
}
Ok((builder.into(), nonce))
}
/// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
/// [`OffersMessageFlow`], and any corresponding [`InvoiceRequest`] can be verified using
/// [`Self::verify_invoice_request`].
///
/// # Privacy
///
/// Uses [`MessageRouter`] provided at construction to construct a [`BlindedMessagePath`] for
/// the offer. See the documentation of the selected [`MessageRouter`] for details on how it
/// selects blinded paths including privacy implications and reliability tradeoffs.
///
/// Also uses a derived signing pubkey in the offer for recipient privacy.
///
/// # Limitations
///
/// If [`DefaultMessageRouter`] is used to parameterize the [`OffersMessageFlow`], a direct
/// connection to the introduction node in the responding [`InvoiceRequest`]'s reply path is
/// required. See the [`DefaultMessageRouter`] documentation for more details.
///
/// # Errors
///
/// Returns an error if the parameterized [`Router`] is unable to create a blinded path for the offer.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
///
/// [`DefaultMessageRouter`]: crate::onion_message::messenger::DefaultMessageRouter
pub fn create_offer_builder<ES: EntropySource>(
&self, entropy_source: ES, peers: Vec<MessageForwardNode>,
) -> Result<OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Bolt12SemanticError> {
self.create_offer_builder_intern(&entropy_source, |_, context, _| {
self.create_blinded_paths(peers, context)
.map(|paths| paths.into_iter().take(1))
.map_err(|_| Bolt12SemanticError::MissingPaths)
})
.map(|(builder, _)| builder)
}
/// Same as [`Self::create_offer_builder`], but allows specifying a custom [`MessageRouter`]
/// instead of using the one provided via the [`OffersMessageFlow`] parameterization.
///
/// This gives users full control over how the [`BlindedMessagePath`] is constructed,
/// including the option to omit it entirely.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
///
/// See [`Self::create_offer_builder`] for more details on usage.
pub fn create_offer_builder_using_router<ME: MessageRouter, ES: EntropySource>(
&self, router: ME, entropy_source: ES, peers: Vec<MessageForwardNode>,
) -> Result<OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Bolt12SemanticError> {
let receive_key = self.get_receive_auth_key();
self.create_offer_builder_intern(&entropy_source, |node_id, context, secp_ctx| {
router
.create_blinded_paths(node_id, receive_key, context, peers, secp_ctx)
.map(|paths| paths.into_iter().take(1))
.map_err(|_| Bolt12SemanticError::MissingPaths)
})
.map(|(builder, _)| builder)
}
/// Create an offer for receiving async payments as an often-offline recipient.
///
/// Because we may be offline when the payer attempts to request an invoice, you MUST:
/// 1. Provide at least 1 [`BlindedMessagePath`] terminating at an always-online node that will
/// serve the [`StaticInvoice`] created from this offer on our behalf.
/// 2. Use [`Self::create_static_invoice_builder`] to create a [`StaticInvoice`] from this
/// [`Offer`] plus the returned [`Nonce`], and provide the static invoice to the
/// aforementioned always-online node.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub fn create_async_receive_offer_builder<ES: EntropySource>(
&self, entropy_source: ES, message_paths_to_always_online_node: Vec<BlindedMessagePath>,
) -> Result<(OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Nonce), Bolt12SemanticError> {
self.create_offer_builder_intern(&entropy_source, |_, _, _| {
Ok(message_paths_to_always_online_node)
})
}
/// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by any
/// [`OffersMessageFlow`] using the same [`ExpandedKey`] (provided in the constructor as
/// `inbound_payment_key`), and any corresponding [`InvoiceRequest`] can be verified using
/// [`Self::verify_invoice_request`].
///
/// See [`Self::create_offer_builder`] for more details on privacy and limitations.
///
/// [`ExpandedKey`]: inbound_payment::ExpandedKey
pub fn create_phantom_offer_builder<ES: EntropySource>(
&self, entropy_source: ES, per_node_peers: Vec<(PublicKey, Vec<MessageForwardNode>)>,
path_count_limit: usize,
) -> Result<OfferBuilder<'_, DerivedMetadata, secp256k1::All>, Bolt12SemanticError> {
self.create_offer_builder_intern(entropy_source, |_, context, _| {
self.blinded_paths_for_phantom_offer(per_node_peers, path_count_limit, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)
})
.map(|(builder, _)| builder)
}
fn create_refund_builder_intern<ES: EntropySource, PF, I>(
&self, entropy_source: ES, make_paths: PF, amount_msats: u64, absolute_expiry: Duration,
payment_id: PaymentId,
) -> Result<RefundBuilder<'_, secp256k1::All>, Bolt12SemanticError>
where
PF: FnOnce(
PublicKey,
MessageContext,
&secp256k1::Secp256k1<secp256k1::All>,
) -> Result<I, Bolt12SemanticError>,
I: IntoIterator<Item = BlindedMessagePath>,
{
let node_id = self.get_our_node_id();
let expanded_key = &self.inbound_payment_key;
let entropy = &entropy_source;
let secp_ctx = &self.secp_ctx;
let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
node_id,
expanded_key,
nonce,
secp_ctx,
amount_msats,
payment_id,
)?
.chain_hash(self.chain_hash)
.absolute_expiry(absolute_expiry);
for path in make_paths(node_id, context, secp_ctx)? {
builder = builder.path(path);
}
Ok(builder.into())
}
/// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
/// [`OffersMessageFlow`], and any corresponding [`Bolt12Invoice`] received for the refund
/// can be verified using [`Self::verify_bolt12_invoice`].
///
/// # Privacy
///
/// Uses [`MessageRouter`] provided at construction to construct a [`BlindedMessagePath`] for
/// the refund. See the documentation of the selected [`MessageRouter`] for details on how it
/// selects blinded paths including privacy implications and reliability tradeoffs.
///
/// The builder will have the provided expiration set. Any changes to the expiration on the
/// returned builder will not be honored by [`OffersMessageFlow`]. For non-`std`, the highest seen
/// block time minus two hours is used for the current time when determining if the refund has
/// expired.
///
/// The refund can be revoked by the user prior to receiving the invoice.
/// If abandoned, or if an invoice is not received before expiration, the payment will fail
/// with an [`Event::PaymentFailed`].
///
/// If `max_total_routing_fee_msat` is not specified, the default from
/// [`RouteParameters::from_payment_params_and_value`] is applied.
///
/// Also uses a derived payer id in the refund for payer privacy.
///
/// # Errors
///
/// Returns an error if:
/// - A duplicate `payment_id` is provided, given the caveats in the aforementioned link.
/// - `amount_msats` is invalid, or
/// - The parameterized [`Router`] is unable to create a blinded path for the refund.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
///
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
/// [`RouteParameters::from_payment_params_and_value`]: crate::routing::router::RouteParameters::from_payment_params_and_value
pub fn create_refund_builder<ES: EntropySource>(
&self, entropy_source: ES, amount_msats: u64, absolute_expiry: Duration,
payment_id: PaymentId, peers: Vec<MessageForwardNode>,
) -> Result<RefundBuilder<'_, secp256k1::All>, Bolt12SemanticError> {
self.create_refund_builder_intern(
&entropy_source,
|_, context, _| {
self.create_blinded_paths(peers, context)
.map(|paths| paths.into_iter().take(1))
.map_err(|_| Bolt12SemanticError::MissingPaths)
},
amount_msats,
absolute_expiry,
payment_id,
)
}
/// Same as [`Self::create_refund_builder`] but allows specifying a custom [`MessageRouter`]
/// instead of using the one provided via the [`OffersMessageFlow`] parameterization.
///
/// This gives users full control over how the [`BlindedMessagePath`] is constructed,
/// including the option to omit it entirely.
///
/// See [`Self::create_refund_builder`] for more details on usage.
///
/// # Errors
///
/// In addition to the errors documented in [`Self::create_refund_builder`], this method will
/// return an error if the provided [`MessageRouter`] fails to construct a valid
/// [`BlindedMessagePath`] for the refund.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
///
/// [`Refund`]: crate::offers::refund::Refund
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
/// [`RouteParameters::from_payment_params_and_value`]: crate::routing::router::RouteParameters::from_payment_params_and_value
pub fn create_refund_builder_using_router<ES: EntropySource, ME: MessageRouter>(
&self, router: ME, entropy_source: ES, amount_msats: u64, absolute_expiry: Duration,
payment_id: PaymentId, peers: Vec<MessageForwardNode>,
) -> Result<RefundBuilder<'_, secp256k1::All>, Bolt12SemanticError> {
let receive_key = self.get_receive_auth_key();
self.create_refund_builder_intern(
&entropy_source,
|node_id, context, secp_ctx| {
router
.create_blinded_paths(node_id, receive_key, context, peers, secp_ctx)
.map(|paths| paths.into_iter().take(1))
.map_err(|_| Bolt12SemanticError::MissingPaths)
},
amount_msats,
absolute_expiry,
payment_id,
)
}
/// Creates an [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized
/// by the [`OffersMessageFlow`], and any corresponding [`Bolt12Invoice`] received in response
/// can be verified using [`Self::verify_bolt12_invoice`].
///
/// # Nonce
/// The nonce is used to create a unique [`InvoiceRequest::payer_metadata`] for the invoice request.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub fn create_invoice_request_builder<'a>(
&'a self, offer: &'a Offer, nonce: Nonce, payment_id: PaymentId,
) -> Result<InvoiceRequestBuilder<'a, 'a, secp256k1::All>, Bolt12SemanticError> {
let expanded_key = &self.inbound_payment_key;
let secp_ctx = &self.secp_ctx;
let builder: InvoiceRequestBuilder<secp256k1::All> =
offer.request_invoice(expanded_key, nonce, secp_ctx, payment_id)?.into();
let builder = builder.chain_hash(self.chain_hash)?;
Ok(builder)
}
/// Creates a [`StaticInvoiceBuilder`] from the corresponding [`Offer`] and [`Nonce`] that were
/// created via [`Self::create_async_receive_offer_builder`].
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub fn create_static_invoice_builder<'a, R: Router>(
&self, router: &R, offer: &'a Offer, offer_nonce: Nonce, payment_secret: PaymentSecret,
relative_expiry_secs: u32, usable_channels: Vec<ChannelDetails>,
peers: Vec<MessageForwardNode>,
) -> Result<StaticInvoiceBuilder<'a>, Bolt12SemanticError> {
let expanded_key = &self.inbound_payment_key;
let secp_ctx = &self.secp_ctx;
let payment_context =
PaymentContext::AsyncBolt12Offer(AsyncBolt12OfferContext { offer_nonce });
let amount_msat = offer.amount().and_then(|amount| match amount {
Amount::Bitcoin { amount_msats } => Some(amount_msats),
Amount::Currency { .. } => None,
});
let created_at = self.duration_since_epoch();
let payment_paths = self
.create_blinded_payment_paths(
router,
usable_channels,
amount_msat,
payment_secret,
payment_context,
relative_expiry_secs,
)
.map_err(|()| Bolt12SemanticError::MissingPaths)?;
let path_absolute_expiry = Duration::from_secs(inbound_payment::calculate_absolute_expiry(
created_at.as_secs(),
relative_expiry_secs,
));
let context = MessageContext::AsyncPayments(AsyncPaymentsContext::InboundPayment {
path_absolute_expiry,
});
let async_receive_message_paths = self
.create_blinded_paths(peers, context)
.map_err(|()| Bolt12SemanticError::MissingPaths)?;
StaticInvoiceBuilder::for_offer_using_derived_keys(
offer,
payment_paths,
async_receive_message_paths,
created_at,
expanded_key,
offer_nonce,
secp_ctx,
)
.map(|inv| inv.allow_mpp().relative_expiry(relative_expiry_secs))
}
/// Creates an [`InvoiceBuilder`] using the provided [`Refund`].
///
/// This method is used when a node wishes to construct an [`InvoiceBuilder`]
/// in response to a [`Refund`] request as part of a BOLT 12 flow.
///
/// Returns an `InvoiceBuilder` configured with:
/// - Blinded payment paths created using the parameterized [`Router`], with the provided
/// `payment_secret` included in the path payloads.
/// - The given `payment_hash` and `payment_secret`, enabling secure claim verification.
///
/// Returns an error if the refund targets a different chain or if no valid
/// blinded path can be constructed.
///
/// This is not exported to bindings users as builder patterns don't map outside of move semantics.
pub fn create_invoice_builder_from_refund<'a, ES: EntropySource, R: Router, F>(
&'a self, router: &R, entropy_source: ES, refund: &'a Refund,
usable_channels: Vec<ChannelDetails>, get_payment_info: F,
) -> Result<InvoiceBuilder<'a, DerivedSigningPubkey>, Bolt12SemanticError>
where
F: Fn(u64, u32) -> Result<(PaymentHash, PaymentSecret), Bolt12SemanticError>,
{
if refund.chain() != self.chain_hash {
return Err(Bolt12SemanticError::UnsupportedChain);
}
let expanded_key = &self.inbound_payment_key;
let entropy = &entropy_source;
let amount_msats = refund.amount_msats();
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
let (payment_hash, payment_secret) = get_payment_info(amount_msats, relative_expiry)?;
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
let payment_paths = self
.create_blinded_payment_paths(
router,
usable_channels,
Some(amount_msats),
payment_secret,
payment_context,
relative_expiry,
)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
#[cfg(all(feature = "std", not(fuzzing)))]
let builder = refund.respond_using_derived_keys(
payment_paths,
payment_hash,
expanded_key,
entropy,
)?;
#[cfg(any(not(feature = "std"), fuzzing))]
let created_at = Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64);
#[cfg(any(not(feature = "std"), fuzzing))]
let builder = refund.respond_using_derived_keys_no_std(
payment_paths,
payment_hash,
created_at,
expanded_key,
entropy,
)?;
Ok(builder.into())
}
/// Creates an [`InvoiceBuilder<DerivedSigningPubkey>`] for the
/// provided [`VerifiedInvoiceRequest<DerivedSigningPubkey>`].
///
/// Returns the invoice builder along with a [`MessageContext`] that can
/// later be used to respond to the counterparty.
///
/// Use this method when you want to inspect or modify the [`InvoiceBuilder`]
/// before signing and generating the final [`Bolt12Invoice`].
///
/// # Errors
///
/// Returns a [`Bolt12SemanticError`] if:
/// - Valid blinded payment paths could not be generated for the [`Bolt12Invoice`].
/// - The [`InvoiceBuilder`] could not be created from the [`InvoiceRequest`].
pub fn create_invoice_builder_from_invoice_request_with_keys<'a, R: Router, F>(
&self, router: &R, invoice_request: &'a VerifiedInvoiceRequest<DerivedSigningPubkey>,
usable_channels: Vec<ChannelDetails>, get_payment_info: F,
) -> Result<(InvoiceBuilder<'a, DerivedSigningPubkey>, MessageContext), Bolt12SemanticError>
where
F: Fn(u64, u32) -> Result<(PaymentHash, PaymentSecret), Bolt12SemanticError>,
{
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
let amount_msats =
InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(&invoice_request.inner)?;
let (payment_hash, payment_secret) = get_payment_info(amount_msats, relative_expiry)?;
let context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
offer_id: invoice_request.offer_id,
invoice_request: invoice_request.fields(),
});
let payment_paths = self