forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonion_utils.rs
More file actions
4006 lines (3602 loc) · 171 KB
/
onion_utils.rs
File metadata and controls
4006 lines (3602 loc) · 171 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.
use super::msgs::OnionErrorPacket;
use crate::blinded_path::BlindedHop;
use crate::crypto::chacha20::ChaCha20;
use crate::crypto::streams::ChaChaReader;
use crate::events::HTLCHandlingFailureReason;
use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
use crate::ln::channelmanager::{HTLCSource, RecipientOnionFields};
use crate::ln::msgs::{self, DecodeError};
use crate::offers::invoice_request::InvoiceRequest;
use crate::routing::gossip::NetworkUpdate;
use crate::routing::router::{BlindedTail, Path, RouteHop, RouteParameters, TrampolineHop};
use crate::sign::{NodeSigner, Recipient};
use crate::types::features::{ChannelFeatures, NodeFeatures};
use crate::types::payment::{PaymentHash, PaymentPreimage};
use crate::util::errors::APIError;
use crate::util::logger::Logger;
use crate::util::ser::{
LengthCalculatingWriter, Readable, ReadableArgs, VecWriter, Writeable, Writer,
};
use bitcoin::hashes::cmp::fixed_time_eq;
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::secp256k1;
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use crate::io::{Cursor, Read};
use core::ops::Deref;
#[allow(unused_imports)]
use crate::prelude::*;
const DEFAULT_MIN_FAILURE_PACKET_LEN: usize = 256;
/// The unit size of the hold time. This is used to reduce the hold time resolution to improve privacy.
pub(crate) const HOLD_TIME_UNIT_MILLIS: u128 = 100;
pub(crate) struct OnionKeys {
#[cfg(test)]
pub(crate) shared_secret: SharedSecret,
#[cfg(test)]
pub(crate) blinding_factor: [u8; 32],
pub(crate) ephemeral_pubkey: PublicKey,
pub(crate) rho: [u8; 32],
pub(crate) mu: [u8; 32],
}
#[inline]
pub(crate) fn gen_rho_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
assert_eq!(shared_secret.len(), 32);
let mut hmac = HmacEngine::<Sha256>::new(b"rho");
hmac.input(&shared_secret);
Hmac::from_engine(hmac).to_byte_array()
}
#[inline]
pub(crate) fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
assert_eq!(shared_secret.len(), 32);
let mut engine_rho = HmacEngine::<Sha256>::new(b"rho");
engine_rho.input(&shared_secret);
let hmac_rho = Hmac::from_engine(engine_rho).to_byte_array();
let mut engine_mu = HmacEngine::<Sha256>::new(b"mu");
engine_mu.input(&shared_secret);
let hmac_mu = Hmac::from_engine(engine_mu).to_byte_array();
(hmac_rho, hmac_mu)
}
#[inline]
pub(super) fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
assert_eq!(shared_secret.len(), 32);
let mut hmac = HmacEngine::<Sha256>::new(b"um");
hmac.input(&shared_secret);
Hmac::from_engine(hmac).to_byte_array()
}
#[inline]
pub(super) fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
assert_eq!(shared_secret.len(), 32);
let mut hmac = HmacEngine::<Sha256>::new(b"ammag");
hmac.input(&shared_secret);
Hmac::from_engine(hmac).to_byte_array()
}
#[inline]
pub(super) fn gen_ammagext_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
assert_eq!(shared_secret.len(), 32);
let mut hmac = HmacEngine::<Sha256>::new(b"ammagext");
hmac.input(&shared_secret);
Hmac::from_engine(hmac).to_byte_array()
}
#[cfg(test)]
#[inline]
pub(super) fn gen_pad_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
assert_eq!(shared_secret.len(), 32);
let mut hmac = HmacEngine::<Sha256>::new(b"pad");
hmac.input(&shared_secret);
Hmac::from_engine(hmac).to_byte_array()
}
/// Calculates a pubkey for the next hop, such as the next hop's packet pubkey or blinding point.
pub(crate) fn next_hop_pubkey<T: secp256k1::Verification>(
secp_ctx: &Secp256k1<T>, curr_pubkey: PublicKey, shared_secret: &[u8],
) -> Result<PublicKey, secp256k1::Error> {
let blinding_factor = {
let mut sha = Sha256::engine();
sha.input(&curr_pubkey.serialize()[..]);
sha.input(shared_secret);
Sha256::from_engine(sha).to_byte_array()
};
curr_pubkey.mul_tweak(secp_ctx, &Scalar::from_be_bytes(blinding_factor).unwrap())
}
trait HopInfo {
fn node_pubkey(&self) -> &PublicKey;
}
trait PathHop {
type HopId;
fn hop_id(&self) -> Self::HopId;
fn fee_msat(&self) -> u64;
fn cltv_expiry_delta(&self) -> u32;
}
impl HopInfo for RouteHop {
fn node_pubkey(&self) -> &PublicKey {
&self.pubkey
}
}
impl<'a> PathHop for &'a RouteHop {
type HopId = u64; // scid
fn hop_id(&self) -> Self::HopId {
self.short_channel_id
}
fn fee_msat(&self) -> u64 {
self.fee_msat
}
fn cltv_expiry_delta(&self) -> u32 {
self.cltv_expiry_delta
}
}
impl HopInfo for TrampolineHop {
fn node_pubkey(&self) -> &PublicKey {
&self.pubkey
}
}
impl<'a> PathHop for &'a TrampolineHop {
type HopId = PublicKey;
fn hop_id(&self) -> Self::HopId {
self.pubkey
}
fn fee_msat(&self) -> u64 {
self.fee_msat
}
fn cltv_expiry_delta(&self) -> u32 {
self.cltv_expiry_delta
}
}
trait OnionPayload<'a, 'b> {
type PathHopForId: PathHop + 'b;
type ReceiveType: OnionPayload<'a, 'b>;
fn new_forward(
hop_id: <<Self as OnionPayload<'a, 'b>>::PathHopForId as PathHop>::HopId,
amt_to_forward: u64, outgoing_cltv_value: u32,
) -> Self;
fn new_receive(
recipient_onion: &'a RecipientOnionFields, keysend_preimage: Option<PaymentPreimage>,
sender_intended_htlc_amt_msat: u64, total_msat: u64, cltv_expiry_height: u32,
) -> Result<Self::ReceiveType, APIError>;
fn new_blinded_forward(
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
) -> Self;
fn new_blinded_receive(
sender_intended_htlc_amt_msat: u64, total_msat: u64, cltv_expiry_height: u32,
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&'a InvoiceRequest>,
custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
) -> Self;
fn new_trampoline_entry(
total_msat: u64, amt_to_forward: u64, outgoing_cltv_value: u32,
recipient_onion: &'a RecipientOnionFields, packet: msgs::TrampolineOnionPacket,
) -> Result<Self::ReceiveType, APIError>;
}
impl<'a, 'b> OnionPayload<'a, 'b> for msgs::OutboundOnionPayload<'a> {
type PathHopForId = &'b RouteHop;
type ReceiveType = msgs::OutboundOnionPayload<'a>;
fn new_forward(short_channel_id: u64, amt_to_forward: u64, outgoing_cltv_value: u32) -> Self {
Self::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value }
}
fn new_receive(
recipient_onion: &'a RecipientOnionFields, keysend_preimage: Option<PaymentPreimage>,
sender_intended_htlc_amt_msat: u64, total_msat: u64, cltv_expiry_height: u32,
) -> Result<Self::ReceiveType, APIError> {
Ok(Self::Receive {
payment_data: recipient_onion
.payment_secret
.map(|payment_secret| msgs::FinalOnionHopData { payment_secret, total_msat }),
payment_metadata: recipient_onion.payment_metadata.as_ref(),
keysend_preimage,
custom_tlvs: &recipient_onion.custom_tlvs,
sender_intended_htlc_amt_msat,
cltv_expiry_height,
})
}
fn new_blinded_forward(
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
) -> Self {
Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point }
}
fn new_blinded_receive(
sender_intended_htlc_amt_msat: u64, total_msat: u64, cltv_expiry_height: u32,
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&'a InvoiceRequest>,
custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
) -> Self {
Self::BlindedReceive {
sender_intended_htlc_amt_msat,
total_msat,
cltv_expiry_height,
encrypted_tlvs,
intro_node_blinding_point,
keysend_preimage,
invoice_request,
custom_tlvs,
}
}
fn new_trampoline_entry(
total_msat: u64, amt_to_forward: u64, outgoing_cltv_value: u32,
recipient_onion: &'a RecipientOnionFields, packet: msgs::TrampolineOnionPacket,
) -> Result<Self, APIError> {
Ok(Self::TrampolineEntrypoint {
amt_to_forward,
outgoing_cltv_value,
multipath_trampoline_data: recipient_onion
.payment_secret
.map(|payment_secret| msgs::FinalOnionHopData { payment_secret, total_msat }),
trampoline_packet: packet,
})
}
}
impl<'a, 'b> OnionPayload<'a, 'b> for msgs::OutboundTrampolinePayload<'a> {
type PathHopForId = &'b TrampolineHop;
type ReceiveType = msgs::OutboundTrampolinePayload<'a>;
fn new_forward(
outgoing_node_id: PublicKey, amt_to_forward: u64, outgoing_cltv_value: u32,
) -> Self {
Self::Forward { outgoing_node_id, amt_to_forward, outgoing_cltv_value }
}
fn new_receive(
_recipient_onion: &'a RecipientOnionFields, _keysend_preimage: Option<PaymentPreimage>,
_sender_intended_htlc_amt_msat: u64, _total_msat: u64, _cltv_expiry_height: u32,
) -> Result<Self::ReceiveType, APIError> {
Err(APIError::InvalidRoute {
err: "Unblinded receiving is not supported for Trampoline!".to_string(),
})
}
fn new_blinded_forward(
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
) -> Self {
Self::BlindedForward { encrypted_tlvs, intro_node_blinding_point }
}
fn new_blinded_receive(
sender_intended_htlc_amt_msat: u64, total_msat: u64, cltv_expiry_height: u32,
encrypted_tlvs: &'a Vec<u8>, intro_node_blinding_point: Option<PublicKey>,
keysend_preimage: Option<PaymentPreimage>, _invoice_request: Option<&'a InvoiceRequest>,
custom_tlvs: &'a Vec<(u64, Vec<u8>)>,
) -> Self {
Self::BlindedReceive {
sender_intended_htlc_amt_msat,
total_msat,
cltv_expiry_height,
encrypted_tlvs,
intro_node_blinding_point,
keysend_preimage,
custom_tlvs,
}
}
fn new_trampoline_entry(
_total_msat: u64, _amt_to_forward: u64, _outgoing_cltv_value: u32,
_recipient_onion: &'a RecipientOnionFields, _packet: msgs::TrampolineOnionPacket,
) -> Result<Self::ReceiveType, APIError> {
Err(APIError::InvalidRoute {
err: "Trampoline onions cannot contain Trampoline entrypoints!".to_string(),
})
}
}
fn construct_onion_keys_generic<'a, T, H>(
secp_ctx: &'a Secp256k1<T>, hops: &'a [H], blinded_tail: Option<&'a BlindedTail>,
session_priv: &SecretKey,
) -> impl Iterator<Item = (SharedSecret, [u8; 32], PublicKey, Option<&'a H>, usize)> + 'a
where
T: secp256k1::Signing,
H: HopInfo,
{
let mut blinded_priv = session_priv.clone();
let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
let unblinded_hops = hops.iter().map(|h| (h.node_pubkey(), Some(h)));
let blinded_pubkeys = blinded_tail
.map(|t| t.hops.iter())
.unwrap_or([].iter())
.skip(1) // Skip the intro node because it's included in the unblinded hops
.map(|h| (&h.blinded_node_id, None));
unblinded_hops.chain(blinded_pubkeys).enumerate().map(move |(idx, (pubkey, route_hop_opt))| {
let shared_secret = SharedSecret::new(pubkey, &blinded_priv);
let mut sha = Sha256::engine();
sha.input(&blinded_pub.serialize()[..]);
sha.input(shared_secret.as_ref());
let blinding_factor = Sha256::from_engine(sha).to_byte_array();
let ephemeral_pubkey = blinded_pub;
blinded_priv = blinded_priv
.mul_tweak(&Scalar::from_be_bytes(blinding_factor).expect("You broke SHA-256"))
.expect("Blinding are never invalid as we picked the starting private key randomly");
blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
(shared_secret, blinding_factor, ephemeral_pubkey, route_hop_opt, idx)
})
}
// can only fail if an intermediary hop has an invalid public key or session_priv is invalid
pub(super) fn construct_onion_keys<T: secp256k1::Signing>(
secp_ctx: &Secp256k1<T>, path: &Path, session_priv: &SecretKey,
) -> Vec<OnionKeys> {
let mut res = Vec::with_capacity(path.hops.len());
let blinded_tail = path.blinded_tail.as_ref().and_then(|t| {
if !t.trampoline_hops.is_empty() {
return None;
}
Some(t)
});
let iter = construct_onion_keys_generic(secp_ctx, &path.hops, blinded_tail, session_priv);
for (shared_secret, _blinding_factor, ephemeral_pubkey, _, _) in iter {
let (rho, mu) = gen_rho_mu_from_shared_secret(shared_secret.as_ref());
res.push(OnionKeys {
#[cfg(test)]
shared_secret,
#[cfg(test)]
blinding_factor: _blinding_factor,
ephemeral_pubkey,
rho,
mu,
});
}
res
}
// can only fail if an intermediary hop has an invalid public key or session_priv is invalid
pub(super) fn construct_trampoline_onion_keys<T: secp256k1::Signing>(
secp_ctx: &Secp256k1<T>, blinded_tail: &BlindedTail, session_priv: &SecretKey,
) -> Vec<OnionKeys> {
let mut res = Vec::with_capacity(blinded_tail.trampoline_hops.len());
let hops = &blinded_tail.trampoline_hops;
let iter = construct_onion_keys_generic(secp_ctx, &hops, Some(blinded_tail), session_priv);
for (shared_secret, _blinding_factor, ephemeral_pubkey, _, _) in iter {
let (rho, mu) = gen_rho_mu_from_shared_secret(shared_secret.as_ref());
res.push(OnionKeys {
#[cfg(test)]
shared_secret,
#[cfg(test)]
blinding_factor: _blinding_factor,
ephemeral_pubkey,
rho,
mu,
});
}
res
}
pub(super) fn build_trampoline_onion_payloads<'a>(
blinded_tail: &'a BlindedTail, total_msat: u64, recipient_onion: &'a RecipientOnionFields,
starting_htlc_offset: u32, keysend_preimage: &Option<PaymentPreimage>,
) -> Result<(Vec<msgs::OutboundTrampolinePayload<'a>>, u64, u32), APIError> {
let mut res: Vec<msgs::OutboundTrampolinePayload> =
Vec::with_capacity(blinded_tail.trampoline_hops.len() + blinded_tail.hops.len());
let blinded_tail_with_hop_iter = BlindedTailDetails::DirectEntry {
hops: blinded_tail.hops.iter(),
blinding_point: blinded_tail.blinding_point,
final_value_msat: blinded_tail.final_value_msat,
excess_final_cltv_expiry_delta: blinded_tail.excess_final_cltv_expiry_delta,
};
let (value_msat, cltv) = build_onion_payloads_callback(
blinded_tail.trampoline_hops.iter(),
Some(blinded_tail_with_hop_iter),
total_msat,
recipient_onion,
starting_htlc_offset,
keysend_preimage,
None,
|action, payload| match action {
PayloadCallbackAction::PushBack => res.push(payload),
PayloadCallbackAction::PushFront => res.insert(0, payload),
},
)?;
Ok((res, value_msat, cltv))
}
/// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
pub(super) fn build_onion_payloads<'a>(
path: &'a Path, total_msat: u64, recipient_onion: &'a RecipientOnionFields,
starting_htlc_offset: u32, keysend_preimage: &Option<PaymentPreimage>,
invoice_request: Option<&'a InvoiceRequest>,
trampoline_packet: Option<msgs::TrampolineOnionPacket>,
) -> Result<(Vec<msgs::OutboundOnionPayload<'a>>, u64, u32), APIError> {
let mut res: Vec<msgs::OutboundOnionPayload> = Vec::with_capacity(
path.hops.len() + path.blinded_tail.as_ref().map_or(0, |t| t.hops.len()),
);
// When Trampoline hops are present, they are presumed to follow the non-Trampoline hops, which
// means that the blinded path needs not be appended to the regular hops, and is only included
// among the Trampoline onion payloads.
let blinded_tail_with_hop_iter = path.blinded_tail.as_ref().map(|bt| {
if let Some(trampoline_packet) = trampoline_packet {
return BlindedTailDetails::TrampolineEntry {
trampoline_packet,
final_value_msat: bt.final_value_msat,
};
}
BlindedTailDetails::DirectEntry {
hops: bt.hops.iter(),
blinding_point: bt.blinding_point,
final_value_msat: bt.final_value_msat,
excess_final_cltv_expiry_delta: bt.excess_final_cltv_expiry_delta,
}
});
let (value_msat, cltv) = build_onion_payloads_callback(
path.hops.iter(),
blinded_tail_with_hop_iter,
total_msat,
recipient_onion,
starting_htlc_offset,
keysend_preimage,
invoice_request,
|action, payload| match action {
PayloadCallbackAction::PushBack => res.push(payload),
PayloadCallbackAction::PushFront => res.insert(0, payload),
},
)?;
Ok((res, value_msat, cltv))
}
enum BlindedTailDetails<'a, I: Iterator<Item = &'a BlindedHop>> {
DirectEntry {
hops: I,
blinding_point: PublicKey,
final_value_msat: u64,
excess_final_cltv_expiry_delta: u32,
},
TrampolineEntry {
trampoline_packet: msgs::TrampolineOnionPacket,
final_value_msat: u64,
},
}
enum PayloadCallbackAction {
PushBack,
PushFront,
}
fn build_onion_payloads_callback<'a, 'b, H, B, F, OP>(
hops: H, mut blinded_tail: Option<BlindedTailDetails<'a, B>>, total_msat: u64,
recipient_onion: &'a RecipientOnionFields, starting_htlc_offset: u32,
keysend_preimage: &Option<PaymentPreimage>, invoice_request: Option<&'a InvoiceRequest>,
mut callback: F,
) -> Result<(u64, u32), APIError>
where
H: DoubleEndedIterator<Item = OP::PathHopForId>,
B: ExactSizeIterator<Item = &'a BlindedHop>,
F: FnMut(PayloadCallbackAction, OP),
OP: OnionPayload<'a, 'b, ReceiveType = OP>,
{
let mut cur_value_msat = 0u64;
let mut cur_cltv = starting_htlc_offset;
let mut last_hop_id = None;
for (idx, hop) in hops.rev().enumerate() {
// First hop gets special values so that it can check, on receipt, that everything is
// exactly as it should be (and the next hop isn't trying to probe to find out if we're
// the intended recipient).
let value_msat = if cur_value_msat == 0 { hop.fee_msat() } else { cur_value_msat };
let cltv = if cur_cltv == starting_htlc_offset {
hop.cltv_expiry_delta().saturating_add(starting_htlc_offset)
} else {
cur_cltv
};
if idx == 0 {
match blinded_tail.take() {
Some(BlindedTailDetails::DirectEntry {
blinding_point,
hops,
final_value_msat,
excess_final_cltv_expiry_delta,
..
}) => {
let mut blinding_point = Some(blinding_point);
let hops_len = hops.len();
for (i, blinded_hop) in hops.enumerate() {
if i == hops_len - 1 {
cur_value_msat += final_value_msat;
callback(
PayloadCallbackAction::PushBack,
OP::new_blinded_receive(
final_value_msat,
total_msat,
cur_cltv + excess_final_cltv_expiry_delta,
&blinded_hop.encrypted_payload,
blinding_point.take(),
*keysend_preimage,
invoice_request,
&recipient_onion.custom_tlvs,
),
);
} else {
callback(
PayloadCallbackAction::PushBack,
OP::new_blinded_forward(
&blinded_hop.encrypted_payload,
blinding_point.take(),
),
);
}
}
},
Some(BlindedTailDetails::TrampolineEntry {
trampoline_packet,
final_value_msat,
}) => {
cur_value_msat += final_value_msat;
callback(
PayloadCallbackAction::PushBack,
OP::new_trampoline_entry(
total_msat,
final_value_msat + hop.fee_msat(),
cur_cltv,
&recipient_onion,
trampoline_packet,
)?,
);
},
None => {
callback(
PayloadCallbackAction::PushBack,
OP::new_receive(
&recipient_onion,
*keysend_preimage,
value_msat,
total_msat,
cltv,
)?,
);
},
}
} else {
let payload = OP::new_forward(
last_hop_id.ok_or(APIError::InvalidRoute {
err: "Next hop ID must be known for non-final hops".to_string(),
})?,
value_msat,
cltv,
);
callback(PayloadCallbackAction::PushFront, payload);
}
cur_value_msat += hop.fee_msat();
if cur_value_msat >= 21000000 * 100000000 * 1000 {
return Err(APIError::InvalidRoute { err: "Channel fees overflowed?".to_owned() });
}
cur_cltv = cur_cltv.saturating_add(hop.cltv_expiry_delta() as u32);
if cur_cltv >= 500000000 {
return Err(APIError::InvalidRoute { err: "Channel CLTV overflowed?".to_owned() });
}
last_hop_id = Some(hop.hop_id());
}
Ok((cur_value_msat, cur_cltv))
}
pub(crate) const MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY: u64 = 100_000_000;
pub(crate) fn set_max_path_length(
route_params: &mut RouteParameters, recipient_onion: &RecipientOnionFields,
keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
best_block_height: u32,
) -> Result<(), ()> {
const PAYLOAD_HMAC_LEN: usize = 32;
let unblinded_intermed_payload_len = msgs::OutboundOnionPayload::Forward {
short_channel_id: 42,
amt_to_forward: TOTAL_BITCOIN_SUPPLY_SATOSHIS,
outgoing_cltv_value: route_params.payment_params.max_total_cltv_expiry_delta,
}
.serialized_length()
.saturating_add(PAYLOAD_HMAC_LEN);
const OVERPAY_ESTIMATE_MULTIPLER: u64 = 3;
let final_value_msat_with_overpay_buffer = route_params
.final_value_msat
.saturating_mul(OVERPAY_ESTIMATE_MULTIPLER)
.clamp(MIN_FINAL_VALUE_ESTIMATE_WITH_OVERPAY, 0x1000_0000);
let blinded_tail_opt = route_params
.payment_params
.payee
.blinded_route_hints()
.iter()
.max_by_key(|path| path.inner_blinded_path().serialized_length())
.map(|largest_path| BlindedTailDetails::DirectEntry {
hops: largest_path.blinded_hops().iter(),
blinding_point: largest_path.blinding_point(),
final_value_msat: final_value_msat_with_overpay_buffer,
excess_final_cltv_expiry_delta: 0,
});
let cltv_expiry_delta =
core::cmp::min(route_params.payment_params.max_total_cltv_expiry_delta, 0x1000_0000);
let unblinded_route_hop = RouteHop {
pubkey: PublicKey::from_slice(&[2; 33]).unwrap(),
node_features: NodeFeatures::empty(),
short_channel_id: 42,
channel_features: ChannelFeatures::empty(),
fee_msat: final_value_msat_with_overpay_buffer,
cltv_expiry_delta,
maybe_announced_channel: false,
};
let mut num_reserved_bytes: usize = 0;
let build_payloads_res = build_onion_payloads_callback(
core::iter::once(&unblinded_route_hop),
blinded_tail_opt,
final_value_msat_with_overpay_buffer,
&recipient_onion,
best_block_height,
&keysend_preimage,
invoice_request,
|_, payload: msgs::OutboundOnionPayload| {
num_reserved_bytes = num_reserved_bytes
.saturating_add(payload.serialized_length())
.saturating_add(PAYLOAD_HMAC_LEN);
},
);
debug_assert!(build_payloads_res.is_ok());
let max_path_length = 1300usize
.checked_sub(num_reserved_bytes)
.map(|p| p / unblinded_intermed_payload_len)
.and_then(|l| u8::try_from(l.saturating_add(1)).ok())
.ok_or(())?;
route_params.payment_params.max_path_length =
core::cmp::min(max_path_length, route_params.payment_params.max_path_length);
Ok(())
}
/// Length of the onion data packet. Before TLV-based onions this was 20 65-byte hops, though now
/// the hops can be of variable length.
pub(crate) const ONION_DATA_LEN: usize = 20 * 65;
#[inline]
fn shift_slice_right(arr: &mut [u8], amt: usize) {
for i in (amt..arr.len()).rev() {
arr[i] = arr[i - amt];
}
for i in 0..amt {
arr[i] = 0;
}
}
pub(super) fn construct_onion_packet(
payloads: Vec<msgs::OutboundOnionPayload>, onion_keys: Vec<OnionKeys>, prng_seed: [u8; 32],
associated_data: &PaymentHash,
) -> Result<msgs::OnionPacket, ()> {
let mut packet_data = [0; ONION_DATA_LEN];
let mut chacha = ChaCha20::new(&prng_seed, &[0; 8]);
chacha.process(&[0; ONION_DATA_LEN], &mut packet_data);
debug_assert_eq!(payloads.len(), onion_keys.len(), "Payloads and keys must have equal lengths");
let packet = FixedSizeOnionPacket(packet_data);
construct_onion_packet_with_init_noise::<_, _>(
payloads,
onion_keys,
packet,
Some(associated_data),
)
}
pub(super) fn construct_trampoline_onion_packet(
payloads: Vec<msgs::OutboundTrampolinePayload>, onion_keys: Vec<OnionKeys>,
prng_seed: [u8; 32], associated_data: &PaymentHash, length: Option<u16>,
) -> Result<msgs::TrampolineOnionPacket, ()> {
let minimum_packet_length = payloads.iter().map(|p| p.serialized_length() + 32).sum();
debug_assert!(
minimum_packet_length < ONION_DATA_LEN,
"Trampoline onion packet must be smaller than outer onion"
);
if minimum_packet_length >= ONION_DATA_LEN {
return Err(());
}
let packet_length = length.map(|l| usize::from(l)).unwrap_or(minimum_packet_length);
debug_assert!(
packet_length >= minimum_packet_length,
"Packet length cannot be smaller than the payloads require."
);
if packet_length < minimum_packet_length {
return Err(());
}
let mut packet_data = vec![0u8; packet_length];
let mut chacha = ChaCha20::new(&prng_seed, &[0; 8]);
chacha.process_in_place(&mut packet_data);
construct_onion_packet_with_init_noise::<_, _>(
payloads,
onion_keys,
packet_data,
Some(associated_data),
)
}
#[cfg(test)]
/// Used in testing to write bogus `BogusOnionHopData` as well as `RawOnionHopData`, which is
/// otherwise not representable in `msgs::OnionHopData`.
pub(super) fn construct_onion_packet_with_writable_hopdata<HD: Writeable>(
payloads: Vec<HD>, onion_keys: Vec<OnionKeys>, prng_seed: [u8; 32],
associated_data: &PaymentHash,
) -> Result<msgs::OnionPacket, ()> {
let mut packet_data = [0; ONION_DATA_LEN];
let mut chacha = ChaCha20::new(&prng_seed, &[0; 8]);
chacha.process(&[0; ONION_DATA_LEN], &mut packet_data);
let packet = FixedSizeOnionPacket(packet_data);
construct_onion_packet_with_init_noise::<_, _>(
payloads,
onion_keys,
packet,
Some(associated_data),
)
}
/// Since onion message packets and onion payment packets have different lengths but are otherwise
/// identical, we use this trait to allow `construct_onion_packet_with_init_noise` to return either
/// type.
pub(crate) trait Packet {
type Data: AsMut<[u8]>;
fn new(pubkey: PublicKey, hop_data: Self::Data, hmac: [u8; 32]) -> Self;
}
// Needed for rustc versions older than 1.47 to avoid E0277: "arrays only have std trait
// implementations for lengths 0..=32".
pub(crate) struct FixedSizeOnionPacket(pub(crate) [u8; ONION_DATA_LEN]);
impl AsMut<[u8]> for FixedSizeOnionPacket {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
pub(crate) fn payloads_serialized_length<HD: Writeable>(payloads: &Vec<HD>) -> usize {
payloads.iter().map(|p| p.serialized_length() + 32 /* HMAC */).sum()
}
pub(crate) fn construct_onion_message_packet<HD: Writeable, P: Packet<Data = Vec<u8>>>(
payloads: Vec<HD>, onion_keys: Vec<OnionKeys>, prng_seed: [u8; 32], packet_data_len: usize,
) -> Result<P, ()> {
let mut packet_data = vec![0; packet_data_len];
let mut chacha = ChaCha20::new(&prng_seed, &[0; 8]);
chacha.process_in_place(&mut packet_data);
construct_onion_packet_with_init_noise::<_, _>(payloads, onion_keys, packet_data, None)
}
fn construct_onion_packet_with_init_noise<HD: Writeable, P: Packet>(
mut payloads: Vec<HD>, onion_keys: Vec<OnionKeys>, mut packet_data: P::Data,
associated_data: Option<&PaymentHash>,
) -> Result<P, ()> {
let filler = {
let packet_data = packet_data.as_mut();
const ONION_HOP_DATA_LEN: usize = 65; // We may decrease this eventually after TLV is common
let mut res = Vec::with_capacity(ONION_HOP_DATA_LEN * (payloads.len() - 1));
let mut pos = 0;
for (i, (payload, keys)) in payloads.iter().zip(onion_keys.iter()).enumerate() {
let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
// TODO: Batch this.
for _ in 0..(packet_data.len() - pos) {
let mut dummy = [0; 1];
chacha.process_in_place(&mut dummy); // We don't have a seek function :(
}
let mut payload_len = LengthCalculatingWriter(0);
payload.write(&mut payload_len).expect("Failed to calculate length");
pos += payload_len.0 + 32;
if pos > packet_data.len() {
return Err(());
}
if i == payloads.len() - 1 {
break;
}
res.resize(pos, 0u8);
chacha.process_in_place(&mut res);
}
res
};
let mut hmac_res = [0; 32];
for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
let mut payload_len = LengthCalculatingWriter(0);
payload.write(&mut payload_len).expect("Failed to calculate length");
let packet_data = packet_data.as_mut();
shift_slice_right(packet_data, payload_len.0 + 32);
packet_data[0..payload_len.0].copy_from_slice(&payload.encode()[..]);
packet_data[payload_len.0..(payload_len.0 + 32)].copy_from_slice(&hmac_res);
let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
chacha.process_in_place(packet_data);
if i == 0 {
let stop_index = packet_data.len();
let start_index = stop_index.checked_sub(filler.len()).ok_or(())?;
packet_data[start_index..stop_index].copy_from_slice(&filler[..]);
}
let mut hmac = HmacEngine::<Sha256>::new(&keys.mu);
hmac.input(packet_data);
if let Some(associated_data) = associated_data {
hmac.input(&associated_data.0[..]);
}
hmac_res = Hmac::from_engine(hmac).to_byte_array();
}
Ok(P::new(onion_keys.first().unwrap().ephemeral_pubkey, packet_data, hmac_res))
}
/// Encrypts/decrypts a failure packet.
fn crypt_failure_packet(shared_secret: &[u8], packet: &mut OnionErrorPacket) {
let ammag = gen_ammag_from_shared_secret(&shared_secret);
let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
chacha.process_in_place(&mut packet.data);
if let Some(ref mut attribution_data) = packet.attribution_data {
attribution_data.crypt(shared_secret);
}
}
#[cfg(test)]
pub(super) fn test_crypt_failure_packet(shared_secret: &[u8], packet: &mut OnionErrorPacket) {
crypt_failure_packet(shared_secret, packet)
}
fn build_unencrypted_failure_packet(
shared_secret: &[u8], failure_reason: LocalHTLCFailureReason, failure_data: &[u8],
hold_time: u32, min_packet_len: usize,
) -> OnionErrorPacket {
assert_eq!(shared_secret.len(), 32);
assert!(failure_data.len() <= 64531);
// Failure len is 2 bytes type plus the data.
let failure_len = 2 + failure_data.len();
// The remaining length is the padding.
let pad_len = min_packet_len.saturating_sub(failure_len);
// Total len is a 32 bytes HMAC, 2 bytes failure len, failure, 2 bytes pad len and pad.
let total_len = 32 + 2 + failure_len + 2 + pad_len;
let mut writer = VecWriter(Vec::with_capacity(total_len));
// Reserve space for the HMAC.
writer.0.extend_from_slice(&[0; 32]);
// Write failure len, type and data.
(failure_len as u16).write(&mut writer).unwrap();
failure_reason.failure_code().write(&mut writer).unwrap();
writer.0.extend_from_slice(&failure_data[..]);
// Write pad len and resize to match padding.
(pad_len as u16).write(&mut writer).unwrap();
writer.0.resize(total_len, 0);
// Calculate and store HMAC.
let um = gen_um_from_shared_secret(&shared_secret);
let mut hmac = HmacEngine::<Sha256>::new(&um);
hmac.input(&writer.0[32..]);
let hmac = Hmac::from_engine(hmac).to_byte_array();
writer.0[..32].copy_from_slice(&hmac);
// Prepare attribution data.
let mut packet = OnionErrorPacket { data: writer.0, attribution_data: None };
update_attribution_data(&mut packet, shared_secret, hold_time);
packet
}
fn update_attribution_data(
onion_error_packet: &mut OnionErrorPacket, shared_secret: &[u8], hold_time: u32,
) {
// If there's no attribution data yet, we still add our hold times and HMACs to potentially give the sender
// attribution data for the partial path. In order for this to work, all upstream nodes need to support attributable
// failures.
let attribution_data =
onion_error_packet.attribution_data.get_or_insert(AttributionData::new());
attribution_data.update(&onion_error_packet.data, shared_secret, hold_time);
}
pub(super) fn build_failure_packet(
shared_secret: &[u8], failure_reason: LocalHTLCFailureReason, failure_data: &[u8],
hold_time: u32,
) -> OnionErrorPacket {
let mut onion_error_packet = build_unencrypted_failure_packet(
shared_secret,
failure_reason,
failure_data,
hold_time,
DEFAULT_MIN_FAILURE_PACKET_LEN,
);
crypt_failure_packet(shared_secret, &mut onion_error_packet);
onion_error_packet
}
mod fuzzy_onion_utils {
use super::*;
pub struct DecodedOnionFailure {
pub(crate) network_update: Option<NetworkUpdate>,
pub(crate) short_channel_id: Option<u64>,
pub(crate) payment_failed_permanently: bool,
pub(crate) failed_within_blinded_path: bool,
#[allow(dead_code)]
pub(crate) hold_times: Vec<u32>,
#[cfg(any(test, feature = "_test_utils"))]
pub(crate) onion_error_code: Option<LocalHTLCFailureReason>,
#[cfg(any(test, feature = "_test_utils"))]
pub(crate) onion_error_data: Option<Vec<u8>>,
#[cfg(test)]
pub(crate) attribution_failed_channel: Option<u64>,
}
}
#[cfg(fuzzing)]
pub use self::fuzzy_onion_utils::*;
#[cfg(not(fuzzing))]
pub(crate) use self::fuzzy_onion_utils::*;
pub fn process_onion_failure<T: secp256k1::Signing, L: Deref>(
secp_ctx: &Secp256k1<T>, logger: &L, htlc_source: &HTLCSource,
encrypted_packet: OnionErrorPacket,
) -> DecodedOnionFailure
where
L::Target: Logger,
{
let (path, session_priv) = match htlc_source {
HTLCSource::OutboundRoute { ref path, ref session_priv, .. } => (path, session_priv),
_ => unreachable!(),
};
process_onion_failure_inner(secp_ctx, logger, path, &session_priv, None, encrypted_packet)