forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannelmanager.rs
3466 lines (3095 loc) · 152 KB
/
channelmanager.rs
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
use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::constants::genesis_block;
use bitcoin::network::constants::Network;
use bitcoin::network::serialize::BitcoinHash;
use bitcoin::util::hash::Sha256dHash;
use secp256k1::key::{SecretKey,PublicKey};
use secp256k1::{Secp256k1,Message};
use secp256k1::ecdh::SharedSecret;
use secp256k1;
use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
use chain::transaction::OutPoint;
use ln::channel::{Channel, ChannelKeys};
use ln::channelmonitor::ManyChannelMonitor;
use ln::router::{Route,RouteHop};
use ln::msgs;
use ln::msgs::{HandleError,ChannelMessageHandler,MsgEncodable,MsgDecodable};
use util::{byte_utils, events, internal_traits, rng};
use util::sha2::Sha256;
use util::chacha20poly1305rfc::ChaCha20;
use util::logger::Logger;
use util::errors::APIError;
use crypto;
use crypto::mac::{Mac,MacResult};
use crypto::hmac::Hmac;
use crypto::digest::Digest;
use crypto::symmetriccipher::SynchronousStreamCipher;
use std::{ptr, mem};
use std::collections::HashMap;
use std::collections::hash_map;
use std::sync::{Mutex,MutexGuard,Arc};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Instant,Duration};
/// We hold various information about HTLC relay in the HTLC objects in Channel itself:
///
/// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
/// forward the HTLC with information it will give back to us when it does so, or if it should Fail
/// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
///
/// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
/// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
/// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
/// the HTLC backwards along the relevant path).
/// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
/// our payment, which we can use to decode errors or inform the user that the payment was sent.
mod channel_held_info {
use ln::msgs;
use ln::router::Route;
use secp256k1::key::SecretKey;
use secp256k1::ecdh::SharedSecret;
/// Stores the info we will need to send when we want to forward an HTLC onwards
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
pub struct PendingForwardHTLCInfo {
pub(super) onion_packet: Option<msgs::OnionPacket>,
pub(super) incoming_shared_secret: SharedSecret,
pub(super) payment_hash: [u8; 32],
pub(super) short_channel_id: u64,
pub(super) amt_to_forward: u64,
pub(super) outgoing_cltv_value: u32,
}
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
pub enum HTLCFailureMsg {
Relay(msgs::UpdateFailHTLC),
Malformed(msgs::UpdateFailMalformedHTLC),
}
/// Stores whether we can't forward an HTLC or relevant forwarding info
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
pub enum PendingHTLCStatus {
Forward(PendingForwardHTLCInfo),
Fail(HTLCFailureMsg),
}
#[cfg(feature = "fuzztarget")]
impl PendingHTLCStatus {
pub fn dummy() -> Self {
let secp_ctx = ::secp256k1::Secp256k1::signing_only();
PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
onion_packet: None,
incoming_shared_secret: SharedSecret::new(&secp_ctx,
&::secp256k1::key::PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[1; 32]).unwrap()),
&SecretKey::from_slice(&secp_ctx, &[1; 32]).unwrap()),
payment_hash: [0; 32],
short_channel_id: 0,
amt_to_forward: 0,
outgoing_cltv_value: 0,
})
}
}
/// Tracks the inbound corresponding to an outbound HTLC
#[derive(Clone)]
pub struct HTLCPreviousHopData {
pub(super) short_channel_id: u64,
pub(super) htlc_id: u64,
pub(super) incoming_packet_shared_secret: SharedSecret,
}
/// Tracks the inbound corresponding to an outbound HTLC
#[derive(Clone)]
pub enum HTLCSource {
PreviousHopData(HTLCPreviousHopData),
OutboundRoute {
route: Route,
session_priv: SecretKey,
},
}
#[cfg(any(test, feature = "fuzztarget"))]
impl HTLCSource {
pub fn dummy() -> Self {
HTLCSource::OutboundRoute {
route: Route { hops: Vec::new() },
session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
}
}
}
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
pub enum HTLCFailReason {
ErrorPacket {
err: msgs::OnionErrorPacket,
},
Reason {
failure_code: u16,
data: Vec<u8>,
}
}
#[cfg(feature = "fuzztarget")]
impl HTLCFailReason {
pub fn dummy() -> Self {
HTLCFailReason::Reason {
failure_code: 0, data: Vec::new(),
}
}
}
}
#[cfg(feature = "fuzztarget")]
pub use self::channel_held_info::*;
#[cfg(not(feature = "fuzztarget"))]
pub(crate) use self::channel_held_info::*;
struct MsgHandleErrInternal {
err: msgs::HandleError,
needs_channel_force_close: bool,
}
impl MsgHandleErrInternal {
#[inline]
fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
Self {
err: HandleError {
err,
action: Some(msgs::ErrorAction::SendErrorMessage {
msg: msgs::ErrorMessage {
channel_id,
data: err.to_string()
},
}),
},
needs_channel_force_close: false,
}
}
#[inline]
fn send_err_msg_close_chan(err: &'static str, channel_id: [u8; 32]) -> Self {
Self {
err: HandleError {
err,
action: Some(msgs::ErrorAction::SendErrorMessage {
msg: msgs::ErrorMessage {
channel_id,
data: err.to_string()
},
}),
},
needs_channel_force_close: true,
}
}
#[inline]
fn from_maybe_close(err: msgs::HandleError) -> Self {
Self { err, needs_channel_force_close: true }
}
#[inline]
fn from_no_close(err: msgs::HandleError) -> Self {
Self { err, needs_channel_force_close: false }
}
}
/// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
/// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
/// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
/// probably increase this significantly.
const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
struct HTLCForwardInfo {
prev_short_channel_id: u64,
prev_htlc_id: u64,
forward_info: PendingForwardHTLCInfo,
}
struct ChannelHolder {
by_id: HashMap<[u8; 32], Channel>,
short_to_id: HashMap<u64, [u8; 32]>,
next_forward: Instant,
/// short channel id -> forward infos. Key of 0 means payments received
/// Note that while this is held in the same mutex as the channels themselves, no consistency
/// guarantees are made about there existing a channel with the short id here, nor the short
/// ids in the PendingForwardHTLCInfo!
forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
/// Note that while this is held in the same mutex as the channels themselves, no consistency
/// guarantees are made about the channels given here actually existing anymore by the time you
/// go to read them!
claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
}
struct MutChannelHolder<'a> {
by_id: &'a mut HashMap<[u8; 32], Channel>,
short_to_id: &'a mut HashMap<u64, [u8; 32]>,
next_forward: &'a mut Instant,
forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
}
impl ChannelHolder {
fn borrow_parts(&mut self) -> MutChannelHolder {
MutChannelHolder {
by_id: &mut self.by_id,
short_to_id: &mut self.short_to_id,
next_forward: &mut self.next_forward,
forward_htlcs: &mut self.forward_htlcs,
claimable_htlcs: &mut self.claimable_htlcs,
}
}
}
#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
/// Manager which keeps track of a number of channels and sends messages to the appropriate
/// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
/// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
/// to individual Channels.
pub struct ChannelManager {
genesis_hash: Sha256dHash,
fee_estimator: Arc<FeeEstimator>,
monitor: Arc<ManyChannelMonitor>,
chain_monitor: Arc<ChainWatchInterface>,
tx_broadcaster: Arc<BroadcasterInterface>,
announce_channels_publicly: bool,
fee_proportional_millionths: u32,
latest_block_height: AtomicUsize,
secp_ctx: Secp256k1<secp256k1::All>,
channel_state: Mutex<ChannelHolder>,
our_network_key: SecretKey,
pending_events: Mutex<Vec<events::Event>>,
logger: Arc<Logger>,
}
const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
macro_rules! secp_call {
( $res: expr, $err: expr ) => {
match $res {
Ok(key) => key,
Err(_) => return Err($err),
}
};
}
struct OnionKeys {
#[cfg(test)]
shared_secret: SharedSecret,
#[cfg(test)]
blinding_factor: [u8; 32],
ephemeral_pubkey: PublicKey,
rho: [u8; 32],
mu: [u8; 32],
}
pub struct ChannelDetails {
/// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
/// thereafter this is the txid of the funding transaction xor the funding transaction output).
/// Note that this means this value is *not* persistent - it can change once during the
/// lifetime of the channel.
pub channel_id: [u8; 32],
/// The position of the funding transaction in the chain. None if the funding transaction has
/// not yet been confirmed and the channel fully opened.
pub short_channel_id: Option<u64>,
pub remote_network_id: PublicKey,
pub channel_value_satoshis: u64,
/// The user_id passed in to create_channel, or 0 if the channel was inbound.
pub user_id: u64,
}
impl ChannelManager {
/// Constructs a new ChannelManager to hold several channels and route between them. This is
/// the main "logic hub" for all channel-related actions, and implements ChannelMessageHandler.
/// fee_proportional_millionths is an optional fee to charge any payments routed through us.
/// Non-proportional fees are fixed according to our risk using the provided fee estimator.
/// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
pub fn new(our_network_key: SecretKey, fee_proportional_millionths: u32, announce_channels_publicly: bool, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
let secp_ctx = Secp256k1::new();
let res = Arc::new(ChannelManager {
genesis_hash: genesis_block(network).header.bitcoin_hash(),
fee_estimator: feeest.clone(),
monitor: monitor.clone(),
chain_monitor,
tx_broadcaster,
announce_channels_publicly,
fee_proportional_millionths,
latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
secp_ctx,
channel_state: Mutex::new(ChannelHolder{
by_id: HashMap::new(),
short_to_id: HashMap::new(),
next_forward: Instant::now(),
forward_htlcs: HashMap::new(),
claimable_htlcs: HashMap::new(),
}),
our_network_key,
pending_events: Mutex::new(Vec::new()),
logger,
});
let weak_res = Arc::downgrade(&res);
res.chain_monitor.register_listener(weak_res);
Ok(res)
}
/// Creates a new outbound channel to the given remote node and with the given value.
/// user_id will be provided back as user_channel_id in FundingGenerationReady and
/// FundingBroadcastSafe events to allow tracking of which events correspond with which
/// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
/// may wish to avoid using 0 for user_id here.
/// If successful, will generate a SendOpenChannel event, so you should probably poll
/// PeerManager::process_events afterwards.
/// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
let chan_keys = if cfg!(feature = "fuzztarget") {
ChannelKeys {
funding_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
revocation_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
delayed_payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
htlc_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
channel_close_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
}
} else {
let mut key_seed = [0u8; 32];
rng::fill_bytes(&mut key_seed);
match ChannelKeys::new_from_seed(&key_seed) {
Ok(key) => key,
Err(_) => panic!("RNG is busted!")
}
};
let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator)?;
let mut channel_state = self.channel_state.lock().unwrap();
match channel_state.by_id.insert(channel.channel_id(), channel) {
Some(_) => panic!("RNG is bad???"),
None => {}
}
let mut events = self.pending_events.lock().unwrap();
events.push(events::Event::SendOpenChannel {
node_id: their_network_key,
msg: res,
});
Ok(())
}
/// Gets the list of open channels, in random order. See ChannelDetail field documentation for
/// more information.
pub fn list_channels(&self) -> Vec<ChannelDetails> {
let channel_state = self.channel_state.lock().unwrap();
let mut res = Vec::with_capacity(channel_state.by_id.len());
for (channel_id, channel) in channel_state.by_id.iter() {
res.push(ChannelDetails {
channel_id: (*channel_id).clone(),
short_channel_id: channel.get_short_channel_id(),
remote_network_id: channel.get_their_node_id(),
channel_value_satoshis: channel.get_value_satoshis(),
user_id: channel.get_user_id(),
});
}
res
}
/// Gets the list of usable channels, in random order. Useful as an argument to
/// Router::get_route to ensure non-announced channels are used.
pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
let channel_state = self.channel_state.lock().unwrap();
let mut res = Vec::with_capacity(channel_state.by_id.len());
for (channel_id, channel) in channel_state.by_id.iter() {
if channel.is_usable() {
res.push(ChannelDetails {
channel_id: (*channel_id).clone(),
short_channel_id: channel.get_short_channel_id(),
remote_network_id: channel.get_their_node_id(),
channel_value_satoshis: channel.get_value_satoshis(),
user_id: channel.get_user_id(),
});
}
}
res
}
/// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
/// will be accepted on the given channel, and after additional timeout/the closing of all
/// pending HTLCs, the channel will be closed on chain.
/// May generate a SendShutdown event on success, which should be relayed.
pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), HandleError> {
let (mut res, node_id, chan_option) = {
let mut channel_state_lock = self.channel_state.lock().unwrap();
let channel_state = channel_state_lock.borrow_parts();
match channel_state.by_id.entry(channel_id.clone()) {
hash_map::Entry::Occupied(mut chan_entry) => {
let res = chan_entry.get_mut().get_shutdown()?;
if chan_entry.get().is_shutdown() {
if let Some(short_id) = chan_entry.get().get_short_channel_id() {
channel_state.short_to_id.remove(&short_id);
}
(res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
} else { (res, chan_entry.get().get_their_node_id(), None) }
},
hash_map::Entry::Vacant(_) => return Err(HandleError{err: "No such channel", action: None})
}
};
for htlc_source in res.1.drain(..) {
// unknown_next_peer...I dunno who that is anymore....
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
}
let chan_update = if let Some(chan) = chan_option {
if let Ok(update) = self.get_channel_update(&chan) {
Some(update)
} else { None }
} else { None };
let mut events = self.pending_events.lock().unwrap();
if let Some(update) = chan_update {
events.push(events::Event::BroadcastChannelUpdate {
msg: update
});
}
events.push(events::Event::SendShutdown {
node_id,
msg: res.0
});
Ok(())
}
#[inline]
fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>)) {
let (local_txn, mut failed_htlcs) = shutdown_res;
for htlc_source in failed_htlcs.drain(..) {
// unknown_next_peer...I dunno who that is anymore....
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
}
for tx in local_txn {
self.tx_broadcaster.broadcast_transaction(&tx);
}
//TODO: We need to have a way where outbound HTLC claims can result in us claiming the
//now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
//TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
//may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
//timeouts are hit and our claims confirm).
//TODO: In any case, we need to make sure we remove any pending htlc tracking (via
//fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
}
/// Force closes a channel, immediately broadcasting the latest local commitment transaction to
/// the chain and rejecting new HTLCs on the given channel.
pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
let mut chan = {
let mut channel_state_lock = self.channel_state.lock().unwrap();
let channel_state = channel_state_lock.borrow_parts();
if let Some(chan) = channel_state.by_id.remove(channel_id) {
if let Some(short_id) = chan.get_short_channel_id() {
channel_state.short_to_id.remove(&short_id);
}
chan
} else {
return;
}
};
self.finish_force_close_channel(chan.force_shutdown());
let mut events = self.pending_events.lock().unwrap();
if let Ok(update) = self.get_channel_update(&chan) {
events.push(events::Event::BroadcastChannelUpdate {
msg: update
});
}
}
/// Force close all channels, immediately broadcasting the latest local commitment transaction
/// for each to the chain and rejecting new HTLCs on each.
pub fn force_close_all_channels(&self) {
for chan in self.list_channels() {
self.force_close_channel(&chan.channel_id);
}
}
#[inline]
fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
({
let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
hmac.input(&shared_secret[..]);
let mut res = [0; 32];
hmac.raw_result(&mut res);
res
},
{
let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
hmac.input(&shared_secret[..]);
let mut res = [0; 32];
hmac.raw_result(&mut res);
res
})
}
#[inline]
fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
hmac.input(&shared_secret[..]);
let mut res = [0; 32];
hmac.raw_result(&mut res);
res
}
#[inline]
fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
hmac.input(&shared_secret[..]);
let mut res = [0; 32];
hmac.raw_result(&mut res);
res
}
// can only fail if an intermediary hop has an invalid public key or session_priv is invalid
#[inline]
fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
let mut blinded_priv = session_priv.clone();
let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
for hop in route.hops.iter() {
let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
let mut sha = Sha256::new();
sha.input(&blinded_pub.serialize()[..]);
sha.input(&shared_secret[..]);
let mut blinding_factor = [0u8; 32];
sha.result(&mut blinding_factor);
let ephemeral_pubkey = blinded_pub;
blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
}
Ok(())
}
// can only fail if an intermediary hop has an invalid public key or session_priv is invalid
fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
let mut res = Vec::with_capacity(route.hops.len());
Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
res.push(OnionKeys {
#[cfg(test)]
shared_secret,
#[cfg(test)]
blinding_factor: _blinding_factor,
ephemeral_pubkey,
rho,
mu,
});
})?;
Ok(res)
}
/// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), HandleError> {
let mut cur_value_msat = 0u64;
let mut cur_cltv = starting_htlc_offset;
let mut last_short_channel_id = 0;
let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
unsafe { res.set_len(route.hops.len()); }
for (idx, hop) in route.hops.iter().enumerate().rev() {
// 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 + starting_htlc_offset } else { cur_cltv };
res[idx] = msgs::OnionHopData {
realm: 0,
data: msgs::OnionRealm0HopData {
short_channel_id: last_short_channel_id,
amt_to_forward: value_msat,
outgoing_cltv_value: cltv,
},
hmac: [0; 32],
};
cur_value_msat += hop.fee_msat;
if cur_value_msat >= 21000000 * 100000000 * 1000 {
return Err(HandleError{err: "Channel fees overflowed?!", action: None});
}
cur_cltv += hop.cltv_expiry_delta as u32;
if cur_cltv >= 500000000 {
return Err(HandleError{err: "Channel CLTV overflowed?!", action: None});
}
last_short_channel_id = hop.short_channel_id;
}
Ok((res, cur_value_msat, cur_cltv))
}
#[inline]
fn shift_arr_right(arr: &mut [u8; 20*65]) {
unsafe {
ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
}
for i in 0..65 {
arr[i] = 0;
}
}
#[inline]
fn xor_bufs(dst: &mut[u8], src: &[u8]) {
assert_eq!(dst.len(), src.len());
for i in 0..dst.len() {
dst[i] ^= src[i];
}
}
const ZERO:[u8; 21*65] = [0; 21*65];
fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> Result<msgs::OnionPacket, HandleError> {
let mut buf = Vec::with_capacity(21*65);
buf.resize(21*65, 0);
let filler = {
let iters = payloads.len() - 1;
let end_len = iters * 65;
let mut res = Vec::with_capacity(end_len);
res.resize(end_len, 0);
for (i, keys) in onion_keys.iter().enumerate() {
if i == payloads.len() - 1 { continue; }
let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
}
res
};
let mut packet_data = [0; 20*65];
let mut hmac_res = [0; 32];
for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
ChannelManager::shift_arr_right(&mut packet_data);
payload.hmac = hmac_res;
packet_data[0..65].copy_from_slice(&payload.encode()[..]);
let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
chacha.process(&packet_data, &mut buf[0..20*65]);
packet_data[..].copy_from_slice(&buf[0..20*65]);
if i == 0 {
packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
}
let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
hmac.input(&packet_data);
hmac.input(&associated_data[..]);
hmac.raw_result(&mut hmac_res);
}
Ok(msgs::OnionPacket{
version: 0,
public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
hop_data: packet_data,
hmac: hmac_res,
})
}
/// Encrypts a failure packet. raw_packet can either be a
/// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
let mut packet_crypted = Vec::with_capacity(raw_packet.len());
packet_crypted.resize(raw_packet.len(), 0);
let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
chacha.process(&raw_packet, &mut packet_crypted[..]);
msgs::OnionErrorPacket {
data: packet_crypted,
}
}
fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
assert!(failure_data.len() <= 256 - 2);
let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
let failuremsg = {
let mut res = Vec::with_capacity(2 + failure_data.len());
res.push(((failure_type >> 8) & 0xff) as u8);
res.push(((failure_type >> 0) & 0xff) as u8);
res.extend_from_slice(&failure_data[..]);
res
};
let pad = {
let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
res.resize(256 - 2 - failure_data.len(), 0);
res
};
let mut packet = msgs::DecodedOnionErrorPacket {
hmac: [0; 32],
failuremsg: failuremsg,
pad: pad,
};
let mut hmac = Hmac::new(Sha256::new(), &um);
hmac.input(&packet.encode()[32..]);
hmac.raw_result(&mut packet.hmac);
packet
}
#[inline]
fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
}
fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
macro_rules! get_onion_hash {
() => {
{
let mut sha = Sha256::new();
sha.input(&msg.onion_routing_packet.hop_data);
let mut onion_hash = [0; 32];
sha.result(&mut onion_hash);
onion_hash
}
}
}
if let Err(_) = msg.onion_routing_packet.public_key {
log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
channel_id: msg.channel_id,
htlc_id: msg.htlc_id,
sha256_of_onion: get_onion_hash!(),
failure_code: 0x8000 | 0x4000 | 6,
})), self.channel_state.lock().unwrap());
}
let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
let mut channel_state = None;
macro_rules! return_err {
($msg: expr, $err_code: expr, $data: expr) => {
{
log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
if channel_state.is_none() {
channel_state = Some(self.channel_state.lock().unwrap());
}
return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
channel_id: msg.channel_id,
htlc_id: msg.htlc_id,
reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
})), channel_state.unwrap());
}
}
}
if msg.onion_routing_packet.version != 0 {
//TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
//sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
//the hash doesn't really serve any purpuse - in the case of hashing all data, the
//receiving node would have to brute force to figure out which version was put in the
//packet by the node that send us the message, in the case of hashing the hop_data, the
//node knows the HMAC matched, so they already know what is there...
return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
}
let mut hmac = Hmac::new(Sha256::new(), &mu);
hmac.input(&msg.onion_routing_packet.hop_data);
hmac.input(&msg.payment_hash);
if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
}
let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
let next_hop_data = {
let mut decoded = [0; 65];
chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
match msgs::OnionHopData::decode(&decoded[..]) {
Err(err) => {
let error_code = match err {
msgs::DecodeError::UnknownRealmByte => 0x4000 | 1,
_ => 0x2000 | 2, // Should never happen
};
return_err!("Unable to decode our hop data", error_code, &[0;0]);
},
Ok(msg) => msg
}
};
//TODO: Check that msg.cltv_expiry is within acceptable bounds!
let pending_forward_info = if next_hop_data.hmac == [0; 32] {
// OUR PAYMENT!
if next_hop_data.data.amt_to_forward != msg.amount_msat {
return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
}
if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
}
// Note that we could obviously respond immediately with an update_fulfill_htlc
// message, however that would leak that we are the recipient of this payment, so
// instead we stay symmetric with the forwarding case, only responding (after a
// delay) once they've send us a commitment_signed!
PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
onion_packet: None,
payment_hash: msg.payment_hash.clone(),
short_channel_id: 0,
incoming_shared_secret: shared_secret.clone(),
amt_to_forward: next_hop_data.data.amt_to_forward,
outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
})
} else {
let mut new_packet_data = [0; 20*65];
chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
let blinding_factor = {
let mut sha = Sha256::new();
sha.input(&new_pubkey.serialize()[..]);
sha.input(&shared_secret[..]);
let mut res = [0u8; 32];
sha.result(&mut res);
match SecretKey::from_slice(&self.secp_ctx, &res) {
Err(_) => {
return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
},
Ok(key) => key
}
};
if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
}
let outgoing_packet = msgs::OnionPacket {
version: 0,
public_key: Ok(new_pubkey),
hop_data: new_packet_data,
hmac: next_hop_data.hmac.clone(),
};
PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
onion_packet: Some(outgoing_packet),
payment_hash: msg.payment_hash.clone(),
short_channel_id: next_hop_data.data.short_channel_id,
incoming_shared_secret: shared_secret.clone(),
amt_to_forward: next_hop_data.data.amt_to_forward,
outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
})
};
channel_state = Some(self.channel_state.lock().unwrap());
if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
let forwarding_id = match id_option {
None => {
return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
},
Some(id) => id.clone(),
};
if let Some((err, code, chan_update)) = {
let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
if !chan.is_live() {
Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, self.get_channel_update(chan).unwrap()))
} else {
let fee = amt_to_forward.checked_mul(self.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward {
Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, self.get_channel_update(chan).unwrap()))
} else {
if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 {
Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, self.get_channel_update(chan).unwrap()))
} else {
None
}
}
}
} {
return_err!(err, code, &chan_update.encode_with_len()[..]);
}
}
}
(pending_forward_info, channel_state.unwrap())
}
/// only fails if the channel does not yet have an assigned short_id
fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
let short_channel_id = match chan.get_short_channel_id() {
None => return Err(HandleError{err: "Channel not yet established", action: None}),
Some(id) => id,
};
let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
let unsigned = msgs::UnsignedChannelUpdate {
chain_hash: self.genesis_hash,
short_channel_id: short_channel_id,
timestamp: chan.get_channel_update_count(),
flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
cltv_expiry_delta: CLTV_EXPIRY_DELTA,
htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
fee_proportional_millionths: self.fee_proportional_millionths,
excess_data: Vec::new(),
};
let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key); //TODO Can we unwrap here?
Ok(msgs::ChannelUpdate {
signature: sig,
contents: unsigned
})
}
/// Sends a payment along a given route.
/// Value parameters are provided via the last hop in route, see documentation for RouteHop
/// fields for more info.
/// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
/// payment), we don't do anything to stop you! We always try to ensure that if the provided
/// next hop knows the preimage to payment_hash they can claim an additional amount as
/// specified in the last hop in the route! Thus, you should probably do your own
/// payment_preimage tracking (which you should already be doing as they represent "proof of
/// payment") and prevent double-sends yourself.
/// See-also docs on Channel::send_htlc_and_commit.
/// May generate a SendHTLCs event on success, which should be relayed.
pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), HandleError> {
if route.hops.len() < 1 || route.hops.len() > 20 {
return Err(HandleError{err: "Route didn't go anywhere/had bogus size", action: None});
}
let our_node_id = self.get_our_node_id();
for (idx, hop) in route.hops.iter().enumerate() {
if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
return Err(HandleError{err: "Route went through us but wasn't a simple rebalance loop to us", action: None});
}
}
let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
let mut session_key = [0; 32];
rng::fill_bytes(&mut session_key);
session_key
}).expect("RNG is bad!");
let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
//TODO: This should return something other than HandleError, that's really intended for
//p2p-returns only.
let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
HandleError{err: "Pubkey along hop was maliciously selected", action: Some(msgs::ErrorAction::IgnoreError)});
let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash)?;