-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathmessenger.rs
More file actions
2546 lines (2374 loc) · 89.6 KB
/
Copy pathmessenger.rs
File metadata and controls
2546 lines (2374 loc) · 89.6 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.
//! LDK sends, receives, and forwards onion messages via this [`OnionMessenger`], which lives here,
//! as well as various types, traits, and utilities that it uses.
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
use super::async_payments::{AsyncPaymentsMessage, AsyncPaymentsMessageHandler};
use super::dns_resolution::{DNSResolverMessage, DNSResolverMessageHandler};
use super::offers::{OffersMessage, OffersMessageHandler};
use super::packet::OnionMessageContents;
use super::packet::ParsedOnionMessageContents;
use super::packet::{
ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, BIG_PACKET_HOP_DATA_LEN,
SMALL_PACKET_HOP_DATA_LEN,
};
use crate::blinded_path::message::{
AsyncPaymentsContext, BlindedMessagePath, DNSResolverContext, ForwardTlvs, MessageContext,
MessageForwardNode, NextMessageHop, OffersContext, ReceiveTlvs,
};
use crate::blinded_path::utils;
use crate::blinded_path::{IntroductionNode, NodeIdLookUp};
use crate::events::{Event, EventHandler, EventsProvider, ReplayEvent};
use crate::ln::msgs::{
self, BaseMessageHandler, MessageSendEvent, OnionMessage, OnionMessageHandler, SocketAddress,
};
use crate::ln::onion_utils;
use crate::routing::gossip::{NetworkGraph, NodeId, ReadOnlyNetworkGraph};
use crate::sign::{EntropySource, NodeSigner, ReceiveAuthKey, Recipient};
use crate::types::features::{InitFeatures, NodeFeatures};
use crate::util::async_poll::{MultiResultFuturePoller, ResultFuture};
use crate::util::logger::{Logger, WithContext};
use crate::util::ser::Writeable;
use crate::util::wakers::{Future, Notifier};
use crate::io;
use crate::prelude::*;
use crate::sync::Mutex;
use core::fmt;
use core::ops::Deref;
use core::sync::atomic::{AtomicBool, Ordering};
#[cfg(not(c_bindings))]
use {
crate::ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager},
crate::ln::peer_handler::IgnoringMessageHandler,
crate::sign::KeysManager,
crate::sync::Arc,
};
pub(super) const MAX_TIMER_TICKS: usize = 2;
/// A trivial trait which describes any [`OnionMessenger`].
///
/// This is not exported to bindings users as general cover traits aren't useful in other
/// languages.
pub trait AOnionMessenger {
/// A type implementing [`EntropySource`]
type EntropySource: EntropySource;
/// A type implementing [`NodeSigner`]
type NodeSigner: NodeSigner;
/// A type implementing [`Logger`]
type Logger: Logger;
/// A type implementing [`NodeIdLookUp`]
type NL: NodeIdLookUp;
/// A type implementing [`MessageRouter`]
type MessageRouter: MessageRouter;
/// A type implementing [`OffersMessageHandler`]
type OMH: OffersMessageHandler;
/// A type implementing [`AsyncPaymentsMessageHandler`]
type APH: AsyncPaymentsMessageHandler;
/// A type implementing [`DNSResolverMessageHandler`]
type DRH: DNSResolverMessageHandler;
/// A type implementing [`CustomOnionMessageHandler`]
type CMH: CustomOnionMessageHandler;
/// Returns a reference to the actual [`OnionMessenger`] object.
fn get_om(
&self,
) -> &OnionMessenger<
Self::EntropySource,
Self::NodeSigner,
Self::Logger,
Self::NL,
Self::MessageRouter,
Self::OMH,
Self::APH,
Self::DRH,
Self::CMH,
>;
}
impl<
ES: EntropySource,
NS: NodeSigner,
L: Logger,
NL: NodeIdLookUp,
MR: MessageRouter,
OMH: OffersMessageHandler,
APH: AsyncPaymentsMessageHandler,
DRH: DNSResolverMessageHandler,
CMH: CustomOnionMessageHandler,
> AOnionMessenger for OnionMessenger<ES, NS, L, NL, MR, OMH, APH, DRH, CMH>
{
type EntropySource = ES;
type NodeSigner = NS;
type Logger = L;
type NL = NL;
type MessageRouter = MR;
type OMH = OMH;
type APH = APH;
type DRH = DRH;
type CMH = CMH;
fn get_om(&self) -> &OnionMessenger<ES, NS, L, NL, MR, OMH, APH, DRH, CMH> {
self
}
}
/// A sender, receiver and forwarder of [`OnionMessage`]s.
///
/// # Handling Messages
///
/// `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
/// messages to peers or delegating to the appropriate handler for the message type. Currently, the
/// available handlers are:
/// * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
/// * [`CustomOnionMessageHandler`], for handling user-defined message types
///
/// # Sending Messages
///
/// [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
/// a message, the matched handler may return a response message which `OnionMessenger` will send
/// on its behalf.
///
/// # Example
///
/// ```
/// # extern crate bitcoin;
/// # use bitcoin::hashes::_export::_core::time::Duration;
/// # use bitcoin::hex::FromHex;
/// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
/// # use lightning::blinded_path::EmptyNodeIdLookUp;
/// # use lightning::blinded_path::message::{BlindedMessagePath, MessageForwardNode, MessageContext};
/// # use lightning::sign::{EntropySource, KeysManager};
/// # use lightning::ln::peer_handler::IgnoringMessageHandler;
/// # use lightning::onion_message::messenger::{Destination, MessageRouter, MessageSendInstructions, OnionMessagePath, OnionMessenger};
/// # use lightning::onion_message::packet::OnionMessageContents;
/// # use lightning::sign::{NodeSigner, ReceiveAuthKey};
/// # use lightning::util::logger::{Logger, Record};
/// # use lightning::util::ser::{Writeable, Writer};
/// # use lightning::io;
/// # use std::sync::Arc;
/// # struct FakeLogger;
/// # impl Logger for FakeLogger {
/// # fn log(&self, record: Record) { println!("{:?}" , record); }
/// # }
/// # struct FakeMessageRouter {}
/// # impl MessageRouter for FakeMessageRouter {
/// # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
/// # let secp_ctx = Secp256k1::new();
/// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
/// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
/// # let hop_node_id2 = hop_node_id1;
/// # Ok(OnionMessagePath {
/// # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
/// # destination,
/// # first_node_addresses: Vec::new(),
/// # })
/// # }
/// # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
/// # &self, _recipient: PublicKey, _local_node_receive_key: ReceiveAuthKey,
/// # _context: MessageContext, _peers: Vec<MessageForwardNode>, _secp_ctx: &Secp256k1<T>
/// # ) -> Result<Vec<BlindedMessagePath>, ()> {
/// # unreachable!()
/// # }
/// # }
/// # let seed = [42u8; 32];
/// # let time = Duration::from_secs(123456);
/// # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos(), true);
/// # let logger = Arc::new(FakeLogger {});
/// # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
/// # let secp_ctx = Secp256k1::new();
/// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
/// # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
/// # let destination_node_id = hop_node_id1;
/// # let node_id_lookup = EmptyNodeIdLookUp {};
/// # let message_router = Arc::new(FakeMessageRouter {});
/// # let custom_message_handler = IgnoringMessageHandler {};
/// # let offers_message_handler = IgnoringMessageHandler {};
/// # let async_payments_message_handler = IgnoringMessageHandler {};
/// # let dns_resolution_message_handler = IgnoringMessageHandler {};
/// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
/// // ChannelManager.
/// let onion_messenger = OnionMessenger::new(
/// &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
/// &offers_message_handler, &async_payments_message_handler, &dns_resolution_message_handler,
/// &custom_message_handler,
/// );
///
/// # #[derive(Debug)]
/// # struct YourCustomMessage {}
/// impl Writeable for YourCustomMessage {
/// fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
/// # Ok(())
/// // Write your custom onion message to `w`
/// }
/// }
/// impl OnionMessageContents for YourCustomMessage {
/// fn tlv_type(&self) -> u64 {
/// # let your_custom_message_type = 42;
/// your_custom_message_type
/// }
/// fn msg_type(&self) -> &'static str { "YourCustomMessageType" }
/// }
/// // Send a custom onion message to a node id.
/// let destination = Destination::Node(destination_node_id);
/// let instructions = MessageSendInstructions::WithoutReplyPath { destination };
/// # let message = YourCustomMessage {};
/// onion_messenger.send_onion_message(message, instructions);
///
/// // Create a blinded path to yourself, for someone to send an onion message to.
/// # let your_node_id = hop_node_id1;
/// let hops = [
/// MessageForwardNode { node_id: hop_node_id3, short_channel_id: None },
/// MessageForwardNode { node_id: hop_node_id4, short_channel_id: None },
/// ];
/// let context = MessageContext::Custom(Vec::new());
/// let receive_key = keys_manager.get_receive_auth_key();
/// let blinded_path = BlindedMessagePath::new(&hops, your_node_id, receive_key, context, false, &keys_manager, &secp_ctx);
///
/// // Send a custom onion message to a blinded path.
/// let destination = Destination::BlindedPath(blinded_path);
/// let instructions = MessageSendInstructions::WithoutReplyPath { destination };
/// # let message = YourCustomMessage {};
/// onion_messenger.send_onion_message(message, instructions);
/// ```
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
pub struct OnionMessenger<
ES: EntropySource,
NS: NodeSigner,
L: Logger,
NL: NodeIdLookUp,
MR: MessageRouter,
OMH: OffersMessageHandler,
APH: AsyncPaymentsMessageHandler,
DRH: DNSResolverMessageHandler,
CMH: CustomOnionMessageHandler,
> {
entropy_source: ES,
#[cfg(test)]
pub(super) node_signer: NS,
#[cfg(not(test))]
node_signer: NS,
logger: L,
message_recipients: Mutex<HashMap<PublicKey, OnionMessageRecipient>>,
secp_ctx: Secp256k1<secp256k1::All>,
node_id_lookup: NL,
message_router: MR,
offers_handler: OMH,
#[allow(unused)]
async_payments_handler: APH,
dns_resolver_handler: DRH,
custom_handler: CMH,
intercept_messages_for_offline_peers: bool,
intercept_for_unknown_scids: bool,
pending_intercepted_msgs_events: Mutex<Vec<Event>>,
pending_peer_connected_events: Mutex<Vec<Event>>,
pending_events_processor: AtomicBool,
/// A [`Notifier`] used to wake up the background processor in case we have any [`Event`]s for
/// it to give to users.
event_notifier: Notifier,
}
/// [`OnionMessage`]s buffered to be sent.
enum OnionMessageRecipient {
/// Messages for a node connected as a peer.
ConnectedPeer(VecDeque<OnionMessage>),
/// Messages for a node that is not yet connected, which are dropped after [`MAX_TIMER_TICKS`]
/// and tracked here.
PendingConnection(VecDeque<OnionMessage>, Option<Vec<SocketAddress>>, usize),
}
impl OnionMessageRecipient {
fn pending_connection(addresses: Vec<SocketAddress>) -> Self {
Self::PendingConnection(VecDeque::new(), Some(addresses), 0)
}
fn pending_messages(&self) -> &VecDeque<OnionMessage> {
match self {
OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
}
}
fn enqueue_message(&mut self, message: OnionMessage) {
let pending_messages = match self {
OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
};
pending_messages.push_back(message);
}
fn dequeue_message(&mut self) -> Option<OnionMessage> {
let pending_messages = match self {
OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
OnionMessageRecipient::PendingConnection(pending_messages, _, _) => {
debug_assert!(false);
pending_messages
},
};
pending_messages.pop_front()
}
#[cfg(test)]
fn release_pending_messages(&mut self) -> VecDeque<OnionMessage> {
let pending_messages = match self {
OnionMessageRecipient::ConnectedPeer(pending_messages) => pending_messages,
OnionMessageRecipient::PendingConnection(pending_messages, _, _) => pending_messages,
};
core::mem::take(pending_messages)
}
fn mark_connected(&mut self) {
if let OnionMessageRecipient::PendingConnection(pending_messages, _, _) = self {
let mut new_pending_messages = VecDeque::new();
core::mem::swap(pending_messages, &mut new_pending_messages);
*self = OnionMessageRecipient::ConnectedPeer(new_pending_messages);
}
}
fn is_connected(&self) -> bool {
match self {
OnionMessageRecipient::ConnectedPeer(..) => true,
OnionMessageRecipient::PendingConnection(..) => false,
}
}
}
/// The `Responder` struct creates an appropriate [`ResponseInstruction`] for responding to a
/// message.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Responder {
/// The path along which a response can be sent.
reply_path: BlindedMessagePath,
}
impl_ser_tlv_based!(Responder, {
(0, reply_path, required),
});
impl Responder {
/// Creates a new [`Responder`] instance with the provided reply path.
pub(super) fn new(reply_path: BlindedMessagePath) -> Self {
Responder { reply_path }
}
/// Creates a [`ResponseInstruction`] for responding without including a reply path.
///
/// Use when the recipient doesn't need to send back a reply to us.
pub fn respond(self) -> ResponseInstruction {
ResponseInstruction {
destination: Destination::BlindedPath(self.reply_path),
context: None,
}
}
/// Creates a [`ResponseInstruction`] for responding including a reply path.
///
/// Use when the recipient needs to send back a reply to us.
pub fn respond_with_reply_path(self, context: MessageContext) -> ResponseInstruction {
ResponseInstruction {
destination: Destination::BlindedPath(self.reply_path),
context: Some(context),
}
}
/// Converts a [`Responder`] into its inner [`BlindedMessagePath`].
pub(crate) fn into_blinded_path(self) -> BlindedMessagePath {
self.reply_path
}
}
/// Instructions for how and where to send the response to an onion message.
#[derive(Clone)]
pub struct ResponseInstruction {
/// The destination in a response is always a [`Destination::BlindedPath`] but using a
/// [`Destination`] rather than an explicit [`BlindedMessagePath`] simplifies the logic in
/// [`OnionMessenger::send_onion_message_internal`] somewhat.
destination: Destination,
context: Option<MessageContext>,
}
impl ResponseInstruction {
/// Converts this [`ResponseInstruction`] into a [`MessageSendInstructions`] so that it can be
/// used to send the response via a normal message sending method.
pub fn into_instructions(self) -> MessageSendInstructions {
MessageSendInstructions::ForReply { instructions: self }
}
}
/// Instructions for how and where to send a message.
#[derive(Clone)]
pub enum MessageSendInstructions {
/// Indicates that a message should be sent including the provided reply path for the recipient
/// to respond.
WithSpecifiedReplyPath {
/// The destination where we need to send our message.
destination: Destination,
/// The reply path which should be included in the message.
reply_path: BlindedMessagePath,
},
/// Indicates that a message should be sent including a reply path for the recipient to
/// respond.
WithReplyPath {
/// The destination where we need to send our message.
destination: Destination,
/// The context to include in the reply path we'll give the recipient so they can respond
/// to us.
context: MessageContext,
},
/// Indicates that a message should be sent without including a reply path, preventing the
/// recipient from responding.
WithoutReplyPath {
/// The destination where we need to send our message.
destination: Destination,
},
/// Indicates that a message is being sent as a reply to a received message.
ForReply {
/// The instructions provided by the [`Responder`].
instructions: ResponseInstruction,
},
/// Indicates that this onion message did not originate from our node and is being forwarded
/// through us from another node on the network to the destination.
///
/// We separate out this case because forwarded onion messages are treated differently from
/// outbound onion messages initiated by our node. Outbounds are buffered internally, whereas, for
/// DoS protection, forwards should never be buffered internally and instead will either be
/// dropped or generate an [`Event::OnionMessageIntercepted`] if the next-hop node is
/// disconnected.
ForwardedMessage {
/// The destination where we need to send the forwarded onion message.
destination: Destination,
/// The reply path which should be included in the message, that terminates at the original
/// sender of this forwarded message.
reply_path: Option<BlindedMessagePath>,
},
}
/// A trait defining behavior for routing an [`OnionMessage`].
pub trait MessageRouter {
/// Returns a route for sending an [`OnionMessage`] to the given [`Destination`].
fn find_path(
&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination,
) -> Result<OnionMessagePath, ()>;
/// Creates [`BlindedMessagePath`]s to the `recipient` node. The nodes in `peers` are assumed to
/// be direct peers with the `recipient`.
///
/// While payments will fail if most of `context` is modified, modifying
/// [`OffersContext::InvoiceRequest::payment_metadata`] prior to blinded path construction is
/// allowed.
///
fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey,
context: MessageContext, peers: Vec<MessageForwardNode>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()>;
}
impl<T: MessageRouter + ?Sized, R: Deref<Target = T>> MessageRouter for R {
fn find_path(
&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination,
) -> Result<OnionMessagePath, ()> {
self.deref().find_path(sender, peers, destination)
}
fn create_blinded_paths<S: secp256k1::Signing + secp256k1::Verification>(
&self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey,
context: MessageContext, peers: Vec<MessageForwardNode>, secp_ctx: &Secp256k1<S>,
) -> Result<Vec<BlindedMessagePath>, ()> {
self.deref().create_blinded_paths(
recipient,
local_node_receive_key,
context,
peers,
secp_ctx,
)
}
}
/// A [`MessageRouter`] that can only route to a directly connected [`Destination`].
///
/// [`DefaultMessageRouter`] tries to construct compact or private [`BlindedMessagePath`]s based on
/// the [`MessageContext`] given to [`MessageRouter::create_blinded_paths`]. That is, if the
/// provided context implies the path may be used in a BOLT 12 object which might appear in a QR
/// code, it reduces the amount of padding and dummy hops and prefers building compact paths when
/// short channel IDs (SCIDs) are available for intermediate peers.
///
/// # Compact Blinded Paths
///
/// Compact blinded paths use short channel IDs (SCIDs) instead of pubkeys, resulting in smaller
/// serialization. This is particularly useful when encoding data into space-constrained formats
/// such as QR codes. The SCID is communicated via a [`MessageForwardNode`], but may be `None`
/// to allow for graceful degradation.
///
/// **Note:**
/// If any SCID in the blinded path becomes invalid, the entire compact blinded path may fail to route.
/// For the immediate hop, this can happen if the corresponding channel is closed.
/// For other intermediate hops, it can happen if the channel is closed or modified (e.g., due to splicing).
///
/// # Privacy
///
/// Creating [`BlindedMessagePath`]s may affect privacy since, if a suitable path cannot be found,
/// it will create a one-hop path using the recipient as the introduction node if it is an announced
/// node. Otherwise, there is no way to find a path to the introduction node in order to send a
/// message, and thus an `Err` is returned. The impact of this may be somewhat muted when
/// additional dummy hops are added to the blinded path, but this protection is not complete.
pub struct DefaultMessageRouter<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource> {
network_graph: G,
entropy_source: ES,
}
// Target total length (in hops) for blinded paths used outside of QR codes.
//
// We add dummy hops until the path reaches this length (including the recipient).
pub(crate) const DUMMY_HOPS_PATH_LENGTH: usize = 4;
// Target total length (in hops) for blinded paths included in objects which may appear in a QR
// code.
//
// We add dummy hops until the path reaches this length (including the recipient).
pub(crate) const QR_CODED_DUMMY_HOPS_PATH_LENGTH: usize = 2;
impl<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource>
DefaultMessageRouter<G, L, ES>
{
/// Creates a [`DefaultMessageRouter`] using the given [`NetworkGraph`].
pub fn new(network_graph: G, entropy_source: ES) -> Self {
Self { network_graph, entropy_source }
}
pub(crate) fn create_blinded_paths_from_iter<
I: ExactSizeIterator<Item = MessageForwardNode> + Clone,
T: secp256k1::Signing + secp256k1::Verification,
>(
network_graph: &G, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey,
context: MessageContext, peers: I, entropy_source: &ES, secp_ctx: &Secp256k1<T>,
never_compact_path: bool,
) -> Result<Vec<BlindedMessagePath>, ()> {
// Limit the number of blinded paths that are computed.
const MAX_PATHS: usize = 3;
let network_graph = network_graph.deref().read_only();
let is_recipient_announced =
network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
let (size_constrained, path_len_incl_dummys) = match &context {
MessageContext::Offers(OffersContext::InvoiceRequest { .. })
| MessageContext::Offers(OffersContext::OutboundPaymentForRefund { .. }) => {
// When including blinded paths within BOLT 12 objects that appear in QR codes, we
// sadly need to be conservative about size, especially if the QR code ultimately
// also includes an on-chain address.
(true, QR_CODED_DUMMY_HOPS_PATH_LENGTH)
},
MessageContext::Offers(OffersContext::StaticInvoiceRequested { .. }) => {
// Async Payments aggressively embeds the entire `InvoiceRequest` in the payment
// onion. In a future version it should likely move to embedding only the
// `InvoiceRequest`-specific fields instead, but until then we have to be
// incredibly strict in the size of the blinded path we include in a static payment
// `Offer`.
(true, 0)
},
_ => {
// If there's no need to be small, add additional dummy hops and never use
// SCID-based next-hops as they carry additional expiry risk.
(false, DUMMY_HOPS_PATH_LENGTH)
},
};
let compact_paths = !never_compact_path && size_constrained;
let build_path = |intermediate_hops: &[MessageForwardNode]| {
// Calculate the dummy hops given the total hop count target (including the recipient).
let dummy_hops_count = path_len_incl_dummys.saturating_sub(intermediate_hops.len() + 1);
BlindedMessagePath::new_with_dummy_hops(
intermediate_hops,
recipient,
dummy_hops_count,
local_node_receive_key,
context.clone(),
size_constrained,
&entropy_source,
secp_ctx,
)
};
let has_one_peer = peers.len() == 1;
let mut paths = if !is_recipient_announced {
let mut peer_info = peers
.map(|peer| MessageForwardNode {
short_channel_id: if compact_paths { peer.short_channel_id } else { None },
..peer
})
.filter_map(|peer| {
network_graph
.node(&NodeId::from_pubkey(&peer.node_id))
.map(|info| (peer, info.is_tor_only(), info.channels.len()))
// Allow messages directly with the only peer
.or_else(|| has_one_peer.then(|| (peer, false, 0)))
})
.collect::<Vec<_>>();
// Prefer using non-Tor nodes with the most channels as the introduction node.
peer_info.sort_unstable_by(
|(_, a_tor_only, a_channels), (_, b_tor_only, b_channels)| {
a_tor_only.cmp(b_tor_only).then(a_channels.cmp(b_channels).reverse())
},
);
// Try to create paths from peer info, fall back to direct path if needed
peer_info
.into_iter()
.map(|(peer, _, _)| build_path(&[peer]))
.take(MAX_PATHS)
.collect::<Vec<_>>()
} else {
vec![]
};
if paths.is_empty() {
if is_recipient_announced {
paths = vec![build_path(&[])];
} else {
return Err(());
}
}
if compact_paths {
for path in &mut paths {
path.use_compact_introduction_node(&network_graph);
}
}
Ok(paths)
}
pub(crate) fn find_path(
network_graph: &G, sender: PublicKey, peers: Vec<PublicKey>, mut destination: Destination,
) -> Result<OnionMessagePath, ()> {
let network_graph = network_graph.deref().read_only();
destination.resolve(&network_graph);
let first_node = match destination.first_node() {
Some(first_node) => first_node,
None => return Err(()),
};
if peers.contains(&first_node) || sender == first_node {
Ok(OnionMessagePath {
intermediate_nodes: vec![],
destination,
first_node_addresses: vec![],
})
} else {
let node_details = network_graph
.node(&NodeId::from_pubkey(&first_node))
.and_then(|node_info| node_info.announcement_info.as_ref())
.map(|announcement_info| {
(announcement_info.features(), announcement_info.addresses())
});
match node_details {
Some((features, addresses))
if features.supports_onion_messages() && addresses.len() > 0 =>
{
Ok(OnionMessagePath {
intermediate_nodes: vec![],
destination,
first_node_addresses: addresses.to_vec(),
})
},
None => {
// If the destination is an unannounced node, they may be a known peer that is offline and
// can be woken by the sender.
Ok(OnionMessagePath {
intermediate_nodes: vec![],
destination,
first_node_addresses: vec![],
})
},
_ => Err(()),
}
}
}
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource> MessageRouter
for DefaultMessageRouter<G, L, ES>
{
fn find_path(
&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination,
) -> Result<OnionMessagePath, ()> {
Self::find_path(&self.network_graph, sender, peers, destination)
}
fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey,
context: MessageContext, peers: Vec<MessageForwardNode>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()> {
Self::create_blinded_paths_from_iter(
&self.network_graph,
recipient,
local_node_receive_key,
context,
peers.into_iter(),
&self.entropy_source,
secp_ctx,
false,
)
}
}
/// This message router is similar to [`DefaultMessageRouter`], but it always creates
/// non-compact blinded paths, using the peer's [`NodeId`]. It uses the same heuristics as
/// [`DefaultMessageRouter`] for deciding when to add additional dummy hops to the generated blinded
/// paths.
///
/// This may be useful in cases where you want a long-lived blinded path and anticipate channel(s)
/// may close, but connections to specific peers will remain stable.
///
/// This message router can only route to a directly connected [`Destination`].
///
/// # Privacy
///
/// Creating [`BlindedMessagePath`]s may affect privacy since, if a suitable path cannot be found,
/// it will create a one-hop path using the recipient as the introduction node if it is an announced
/// node. Otherwise, there is no way to find a path to the introduction node in order to send a
/// message, and thus an `Err` is returned. The impact of this may be somewhat muted when
/// additional dummy hops are added to the blinded path, but this protection is not complete.
pub struct NodeIdMessageRouter<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource> {
network_graph: G,
entropy_source: ES,
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource>
NodeIdMessageRouter<G, L, ES>
{
/// Creates a [`NodeIdMessageRouter`] using the given [`NetworkGraph`].
pub fn new(network_graph: G, entropy_source: ES) -> Self {
Self { network_graph, entropy_source }
}
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Logger, ES: EntropySource> MessageRouter
for NodeIdMessageRouter<G, L, ES>
{
fn find_path(
&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination,
) -> Result<OnionMessagePath, ()> {
DefaultMessageRouter::<G, L, ES>::find_path(&self.network_graph, sender, peers, destination)
}
fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, recipient: PublicKey, local_node_receive_key: ReceiveAuthKey,
context: MessageContext, mut peers: Vec<MessageForwardNode>, secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()> {
for peer in peers.iter_mut() {
peer.short_channel_id = None;
}
DefaultMessageRouter::create_blinded_paths_from_iter(
&self.network_graph,
recipient,
local_node_receive_key,
context,
peers.into_iter(),
&self.entropy_source,
secp_ctx,
true,
)
}
}
/// A special [`MessageRouter`] that performs no routing and does not create blinded paths.
/// Its purpose is to enable the creation of [`Offer`]s and [`Refund`]s without blinded paths,
/// where the user's `node_id` is used directly as the [`Destination`].
///
/// # Note
/// [`NullMessageRouter`] **must not** be used as the type parameter for [`ChannelManager`],
/// since [`ChannelManager`] requires a functioning [`MessageRouter`] to create blinded paths,
/// which are necessary for constructing reply paths in onion message communication.
/// However, [`NullMessageRouter`] *can* still be passed as an argument to [`ChannelManager`]
/// methods that accepts a [`MessageRouter`], such as [`ChannelManager::create_offer_builder_using_router`],
/// when blinded paths are not needed.
///
/// [`Offer`]: crate::offers::offer::Offer
/// [`Refund`]: crate::offers::refund::Refund
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
/// [`ChannelManager::create_offer_builder_using_router`]: crate::ln::channelmanager::ChannelManager::create_offer_builder_using_router
pub struct NullMessageRouter {}
impl MessageRouter for NullMessageRouter {
fn find_path(
&self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination,
) -> Result<OnionMessagePath, ()> {
Err(())
}
fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, _recipient: PublicKey, _local_node_receive_key: ReceiveAuthKey,
_context: MessageContext, _peers: Vec<MessageForwardNode>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()> {
Ok(vec![])
}
}
/// A path for sending an [`OnionMessage`].
#[derive(Clone)]
pub struct OnionMessagePath {
/// Nodes on the path between the sender and the destination.
pub intermediate_nodes: Vec<PublicKey>,
/// The recipient of the message.
pub destination: Destination,
/// Addresses that may be used to connect to [`OnionMessagePath::first_node`].
///
/// Only needs to be filled in if a connection to the node is required and it is not a known peer.
/// [`OnionMessenger`] may use this to initiate such a connection.
pub first_node_addresses: Vec<SocketAddress>,
}
impl OnionMessagePath {
/// Returns the first node in the path.
pub fn first_node(&self) -> Option<PublicKey> {
self.intermediate_nodes.first().copied().or_else(|| self.destination.first_node())
}
}
/// The destination of an onion message.
#[derive(Clone, Hash, Debug, PartialEq, Eq)]
pub enum Destination {
/// We're sending this onion message to a node.
Node(PublicKey),
/// We're sending this onion message to a blinded path.
BlindedPath(BlindedMessagePath),
}
impl Destination {
/// Attempts to resolve the [`IntroductionNode::DirectedShortChannelId`] of a
/// [`Destination::BlindedPath`] to a [`IntroductionNode::NodeId`], if applicable, using the
/// provided [`ReadOnlyNetworkGraph`].
pub fn resolve(&mut self, network_graph: &ReadOnlyNetworkGraph) {
if let Destination::BlindedPath(path) = self {
if let IntroductionNode::DirectedShortChannelId(..) = path.introduction_node() {
if let Some(pubkey) = path
.public_introduction_node_id(network_graph)
.and_then(|node_id| node_id.as_pubkey().ok())
{
*path.introduction_node_mut() = IntroductionNode::NodeId(pubkey);
}
}
}
}
pub(super) fn num_hops(&self) -> usize {
match self {
Destination::Node(_) => 1,
Destination::BlindedPath(path) => path.blinded_hops().len(),
}
}
fn first_node(&self) -> Option<PublicKey> {
match self {
Destination::Node(node_id) => Some(*node_id),
Destination::BlindedPath(path) => match path.introduction_node() {
IntroductionNode::NodeId(pubkey) => Some(*pubkey),
IntroductionNode::DirectedShortChannelId(..) => None,
},
}
}
}
/// Result of successfully [sending an onion message].
///
/// [sending an onion message]: OnionMessenger::send_onion_message
#[derive(Clone, Hash, Debug, PartialEq, Eq)]
pub enum SendSuccess {
/// The message was buffered and will be sent once it is processed by
/// [`OnionMessageHandler::next_onion_message_for_peer`].
Buffered,
/// The message was buffered and will be sent once the node is connected as a peer and it is
/// processed by [`OnionMessageHandler::next_onion_message_for_peer`].
BufferedAwaitingConnection(PublicKey),
}
/// Errors that may occur when [sending an onion message].
///
/// [sending an onion message]: OnionMessenger::send_onion_message
#[derive(Clone, Hash, Debug, PartialEq, Eq)]
pub enum SendError {
/// Errored computing onion message packet keys.
Secp256k1(secp256k1::Error),
/// Because implementations such as Eclair will drop onion messages where the message packet
/// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
TooBigPacket,
/// The provided [`Destination`] was an invalid [`BlindedMessagePath`] due to not having any
/// blinded hops.
TooFewBlindedHops,
/// The first hop is not a peer and doesn't have a known [`SocketAddress`].
InvalidFirstHop(PublicKey),
/// Indicates that a path could not be found by the [`MessageRouter`].
///
/// This occurs when either:
/// - No path from the sender to the destination was found to send the onion message
/// - No reply path to the sender could be created when responding to an onion message
PathNotFound,
/// Onion message contents must have a TLV type >= 64.
InvalidMessage,
/// Our next-hop peer's buffer was full or our total outbound buffer was full.
BufferFull,
/// Failed to retrieve our node id from the provided [`NodeSigner`].
///
/// [`NodeSigner`]: crate::sign::NodeSigner
GetNodeIdFailed,
/// The provided [`Destination`] has a blinded path with an unresolved introduction node. An
/// attempt to resolve it in the [`MessageRouter`] when finding an [`OnionMessagePath`] likely
/// failed.
UnresolvedIntroductionNode,
/// We attempted to send to a blinded path where we are the introduction node, and failed to
/// advance the blinded path to make the second hop the new introduction node. Either
/// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
/// new blinding point, or we were attempting to send to ourselves.
BlindedPathAdvanceFailed,
}
/// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
/// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
/// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
/// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
/// message types.
///
/// See [`OnionMessenger`] for example usage.
///
/// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
/// [`CustomMessage`]: Self::CustomMessage
pub trait CustomOnionMessageHandler {
/// The message known to the handler. To support multiple message types, you may want to make this
/// an enum with a variant for each supported message.
type CustomMessage: OnionMessageContents;
/// Called with the custom message that was received, returning a response to send, if any.
///
/// If the provided `context` is `Some`, then the message was sent to a blinded path that we
/// created and was authenticated as such by the [`OnionMessenger`].
///
/// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
fn handle_custom_message(
&self, message: Self::CustomMessage, context: Option<Vec<u8>>, responder: Option<Responder>,
) -> Option<(Self::CustomMessage, ResponseInstruction)>;
/// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
/// message type is unknown.
fn read_custom_message<R: io::Read>(
&self, message_type: u64, buffer: &mut R,
) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
/// Releases any [`Self::CustomMessage`]s that need to be sent.
///
/// Typically, this is used for messages initiating a message flow rather than in response to
/// another message. The latter should use the return value of [`Self::handle_custom_message`].
fn release_pending_custom_messages(
&self,
) -> Vec<(Self::CustomMessage, MessageSendInstructions)>;
}
impl<T: CustomOnionMessageHandler + ?Sized, C: Deref<Target = T>> CustomOnionMessageHandler for C {
type CustomMessage = T::CustomMessage;
fn handle_custom_message(
&self, message: Self::CustomMessage, context: Option<Vec<u8>>, responder: Option<Responder>,
) -> Option<(Self::CustomMessage, ResponseInstruction)> {
self.deref().handle_custom_message(message, context, responder)
}
fn read_custom_message<R: io::Read>(
&self, message_type: u64, buffer: &mut R,
) -> Result<Option<Self::CustomMessage>, msgs::DecodeError> {