Merge pull request #20 from TheBlueMatt/master
[rust-lightning] / src / ln / channelmanager.rs
1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::constants::genesis_block;
4 use bitcoin::network::constants::Network;
5 use bitcoin::network::serialize::BitcoinHash;
6 use bitcoin::util::hash::Sha256dHash;
7 use bitcoin::util::uint::Uint256;
8
9 use secp256k1::key::{SecretKey,PublicKey};
10 use secp256k1::{Secp256k1,Message};
11 use secp256k1::ecdh::SharedSecret;
12 use secp256k1;
13
14 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
15 use ln::channel::Channel;
16 use ln::channelmonitor::ManyChannelMonitor;
17 use ln::router::Route;
18 use ln::msgs;
19 use ln::msgs::{HandleError,ChannelMessageHandler,MsgEncodable,MsgDecodable};
20 use util::{byte_utils, events, internal_traits, rng};
21 use util::sha2::Sha256;
22
23 use crypto::mac::{Mac,MacResult};
24 use crypto::hmac::Hmac;
25 use crypto::digest::Digest;
26 use crypto::symmetriccipher::SynchronousStreamCipher;
27 use crypto::chacha20::ChaCha20;
28
29 use std::sync::{Mutex,MutexGuard,Arc};
30 use std::collections::HashMap;
31 use std::collections::hash_map;
32 use std::{ptr, mem};
33 use std::time::{Instant,Duration};
34
35 mod channel_held_info {
36         use ln::msgs;
37
38         /// Stores the info we will need to send when we want to forward an HTLC onwards
39         pub struct PendingForwardHTLCInfo {
40                 pub(super) onion_packet: Option<msgs::OnionPacket>,
41                 pub(super) payment_hash: [u8; 32],
42                 pub(super) short_channel_id: u64,
43                 pub(super) prev_short_channel_id: u64,
44                 pub(super) amt_to_forward: u64,
45                 pub(super) outgoing_cltv_value: u32,
46         }
47
48         #[cfg(feature = "fuzztarget")]
49         impl PendingForwardHTLCInfo {
50                 pub fn dummy() -> Self {
51                         Self {
52                                 onion_packet: None,
53                                 payment_hash: [0; 32],
54                                 short_channel_id: 0,
55                                 prev_short_channel_id: 0,
56                                 amt_to_forward: 0,
57                                 outgoing_cltv_value: 0,
58                         }
59                 }
60         }
61
62         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
63         pub enum HTLCFailReason {
64                 ErrorPacket {
65                         err: msgs::OnionErrorPacket,
66                 },
67                 Reason {
68                         failure_code: u16,
69                         data: Vec<u8>,
70                 }
71         }
72
73         #[cfg(feature = "fuzztarget")]
74         impl HTLCFailReason {
75                 pub fn dummy() -> Self {
76                         HTLCFailReason::Reason {
77                                 failure_code: 0, data: Vec::new(),
78                         }
79                 }
80         }
81 }
82 #[cfg(feature = "fuzztarget")]
83 pub use self::channel_held_info::*;
84 #[cfg(not(feature = "fuzztarget"))]
85 pub(crate) use self::channel_held_info::*;
86
87 enum PendingOutboundHTLC {
88         IntermediaryHopData {
89                 source_short_channel_id: u64,
90                 incoming_packet_shared_secret: SharedSecret,
91         },
92         OutboundRoute {
93                 route: Route,
94         },
95         /// Used for channel rebalancing
96         CycledRoute {
97                 source_short_channel_id: u64,
98                 incoming_packet_shared_secret: SharedSecret,
99                 route: Route,
100         }
101 }
102
103 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
104 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
105 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
106 /// probably increase this significantly.
107 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
108
109 struct ChannelHolder {
110         by_id: HashMap<Uint256, Channel>,
111         short_to_id: HashMap<u64, Uint256>,
112         next_forward: Instant,
113         /// short channel id -> forward infos. Key of 0 means payments received
114         forward_htlcs: HashMap<u64, Vec<PendingForwardHTLCInfo>>,
115         claimable_htlcs: HashMap<[u8; 32], PendingOutboundHTLC>,
116 }
117 struct MutChannelHolder<'a> {
118         by_id: &'a mut HashMap<Uint256, Channel>,
119         short_to_id: &'a mut HashMap<u64, Uint256>,
120         next_forward: &'a mut Instant,
121         /// short channel id -> forward infos. Key of 0 means payments received
122         forward_htlcs: &'a mut HashMap<u64, Vec<PendingForwardHTLCInfo>>,
123         claimable_htlcs: &'a mut HashMap<[u8; 32], PendingOutboundHTLC>,
124 }
125 impl ChannelHolder {
126         fn borrow_parts(&mut self) -> MutChannelHolder {
127                 MutChannelHolder {
128                         by_id: &mut self.by_id,
129                         short_to_id: &mut self.short_to_id,
130                         next_forward: &mut self.next_forward,
131                         /// short channel id -> forward infos. Key of 0 means payments received
132                         forward_htlcs: &mut self.forward_htlcs,
133                         claimable_htlcs: &mut self.claimable_htlcs,
134                 }
135         }
136 }
137
138 /// Manager which keeps track of a number of channels and sends messages to the appropriate
139 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
140 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
141 /// to individual Channels.
142 pub struct ChannelManager {
143         genesis_hash: Sha256dHash,
144         fee_estimator: Arc<FeeEstimator>,
145         monitor: Arc<ManyChannelMonitor>,
146         chain_monitor: Arc<ChainWatchInterface>,
147         tx_broadcaster: Arc<BroadcasterInterface>,
148
149         announce_channels_publicly: bool,
150         fee_proportional_millionths: u32,
151         secp_ctx: Secp256k1,
152
153         channel_state: Mutex<ChannelHolder>,
154         our_network_key: SecretKey,
155
156         pending_events: Mutex<Vec<events::Event>>,
157 }
158
159 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
160
161 macro_rules! secp_call {
162         ( $res : expr ) => {
163                 match $res {
164                         Ok(key) => key,
165                         //TODO: Make the err a parameter!
166                         Err(_) => return Err(HandleError{err: "Key error", msg: None})
167                 }
168         };
169 }
170
171 struct OnionKeys {
172         #[cfg(test)]
173         shared_secret: SharedSecret,
174         #[cfg(test)]
175         blinding_factor: [u8; 32],
176         ephemeral_pubkey: PublicKey,
177         rho: [u8; 32],
178         mu: [u8; 32],
179 }
180
181 pub struct ChannelDetails {
182         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
183         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
184         /// Note that this means this value is *not* persistent - it can change once during the
185         /// lifetime of the channel.
186         pub channel_id: Uint256,
187         /// The position of the funding transaction in the chain. None if the funding transaction has
188         /// not yet been confirmed and the channel fully opened.
189         pub short_channel_id: Option<u64>,
190         pub remote_network_id: PublicKey,
191         pub channel_value_satoshis: u64,
192         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
193         pub user_id: u64,
194 }
195
196 impl ChannelManager {
197         /// Constructs a new ChannelManager to hold several channels and route between them. This is
198         /// the main "logic hub" for all channel-related actions, and implements ChannelMessageHandler.
199         /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
200         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
201         /// panics if channel_value_satoshis is >= (1 << 24)!
202         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>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
203                 let secp_ctx = Secp256k1::new();
204
205                 let res = Arc::new(ChannelManager {
206                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
207                         fee_estimator: feeest.clone(),
208                         monitor: monitor.clone(),
209                         chain_monitor,
210                         tx_broadcaster,
211
212                         announce_channels_publicly,
213                         fee_proportional_millionths,
214                         secp_ctx,
215
216                         channel_state: Mutex::new(ChannelHolder{
217                                 by_id: HashMap::new(),
218                                 short_to_id: HashMap::new(),
219                                 next_forward: Instant::now(),
220                                 forward_htlcs: HashMap::new(),
221                                 claimable_htlcs: HashMap::new(),
222                         }),
223                         our_network_key,
224
225                         pending_events: Mutex::new(Vec::new()),
226                 });
227                 let weak_res = Arc::downgrade(&res);
228                 res.chain_monitor.register_listener(weak_res);
229                 Ok(res)
230         }
231
232         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, user_id: u64) -> Result<msgs::OpenChannel, HandleError> {
233                 let channel = Channel::new_outbound(&*self.fee_estimator, their_network_key, channel_value_satoshis, self.announce_channels_publicly, user_id);
234                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator)?;
235                 let mut channel_state = self.channel_state.lock().unwrap();
236                 match channel_state.by_id.insert(channel.channel_id(), channel) {
237                         Some(_) => panic!("RNG is bad???"),
238                         None => Ok(res)
239                 }
240         }
241
242         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
243         /// more information.
244         pub fn list_channels(&self) -> Vec<ChannelDetails> {
245                 let channel_state = self.channel_state.lock().unwrap();
246                 let mut res = Vec::with_capacity(channel_state.by_id.len());
247                 for (channel_id, channel) in channel_state.by_id.iter() {
248                         res.push(ChannelDetails {
249                                 channel_id: (*channel_id).clone(),
250                                 short_channel_id: channel.get_short_channel_id(),
251                                 remote_network_id: channel.get_their_node_id(),
252                                 channel_value_satoshis: channel.get_value_satoshis(),
253                                 user_id: channel.get_user_id(),
254                         });
255                 }
256                 res
257         }
258
259         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
260         /// will be accepted on the given channel, and after additional timeout/the closing of all
261         /// pending HTLCs, the channel will be closed on chain.
262         pub fn close_channel(&self, channel_id: &Uint256) -> Result<msgs::Shutdown, HandleError> {
263                 let res = {
264                         let mut channel_state = self.channel_state.lock().unwrap();
265                         match channel_state.by_id.entry(channel_id.clone()) {
266                                 hash_map::Entry::Occupied(mut chan_entry) => {
267                                         let res = chan_entry.get_mut().get_shutdown()?;
268                                         if chan_entry.get().is_shutdown() {
269                                                 chan_entry.remove_entry();
270                                         }
271                                         res
272                                 },
273                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "No such channel", msg: None})
274                         }
275                 };
276                 for payment_hash in res.1 {
277                         // unknown_next_peer...I dunno who that is anymore....
278                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
279                 }
280                 Ok(res.0)
281         }
282
283         #[inline]
284         fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
285                 ({
286                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
287                         hmac.input(&shared_secret[..]);
288                         let mut res = [0; 32];
289                         hmac.raw_result(&mut res);
290                         res
291                 },
292                 {
293                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
294                         hmac.input(&shared_secret[..]);
295                         let mut res = [0; 32];
296                         hmac.raw_result(&mut res);
297                         res
298                 })
299         }
300
301         #[inline]
302         fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
303                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
304                 hmac.input(&shared_secret[..]);
305                 let mut res = [0; 32];
306                 hmac.raw_result(&mut res);
307                 res
308         }
309
310         #[inline]
311         fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
312                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
313                 hmac.input(&shared_secret[..]);
314                 let mut res = [0; 32];
315                 hmac.raw_result(&mut res);
316                 res
317         }
318
319         fn construct_onion_keys(secp_ctx: &Secp256k1, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, HandleError> {
320                 let mut res = Vec::with_capacity(route.hops.len());
321                 let mut blinded_priv = session_priv.clone();
322                 let mut blinded_pub = secp_call!(PublicKey::from_secret_key(secp_ctx, &blinded_priv));
323                 let mut first_iteration = true;
324
325                 for hop in route.hops.iter() {
326                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
327
328                         let mut sha = Sha256::new();
329                         sha.input(&blinded_pub.serialize()[..]);
330                         sha.input(&shared_secret[..]);
331                         let mut blinding_factor = [0u8; 32];
332                         sha.result(&mut blinding_factor);
333
334                         if first_iteration {
335                                 blinded_pub = secp_call!(PublicKey::from_secret_key(secp_ctx, &blinded_priv));
336                                 first_iteration = false;
337                         }
338                         let ephemeral_pubkey = blinded_pub;
339
340                         secp_call!(blinded_priv.mul_assign(secp_ctx, &secp_call!(SecretKey::from_slice(secp_ctx, &blinding_factor))));
341                         blinded_pub = secp_call!(PublicKey::from_secret_key(secp_ctx, &blinded_priv));
342
343                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
344
345                         res.push(OnionKeys {
346                                 #[cfg(test)]
347                                 shared_secret: shared_secret,
348                                 #[cfg(test)]
349                                 blinding_factor: blinding_factor,
350                                 ephemeral_pubkey: ephemeral_pubkey,
351                                 rho: rho,
352                                 mu: mu,
353                         });
354                 }
355
356                 Ok(res)
357         }
358
359         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
360         fn build_onion_payloads(route: &Route) -> Result<(Vec<msgs::OnionHopData>, u64, u32), HandleError> {
361                 let mut cur_value_msat = 0u64;
362                 let mut cur_cltv = 0u32;
363                 let mut last_short_channel_id = 0;
364                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
365                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
366                 unsafe { res.set_len(route.hops.len()); }
367
368                 for (idx, hop) in route.hops.iter().enumerate().rev() {
369                         // First hop gets special values so that it can check, on receipt, that everything is
370                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
371                         // the intended recipient).
372                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
373                         let cltv = if cur_cltv == 0 { hop.cltv_expiry_delta } else { cur_cltv };
374                         res[idx] = msgs::OnionHopData {
375                                 realm: 0,
376                                 data: msgs::OnionRealm0HopData {
377                                         short_channel_id: last_short_channel_id,
378                                         amt_to_forward: value_msat,
379                                         outgoing_cltv_value: cltv,
380                                 },
381                                 hmac: [0; 32],
382                         };
383                         cur_value_msat += hop.fee_msat;
384                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
385                                 return Err(HandleError{err: "Channel fees overflowed?!", msg: None});
386                         }
387                         cur_cltv += hop.cltv_expiry_delta as u32;
388                         if cur_cltv >= 500000000 {
389                                 return Err(HandleError{err: "Channel CLTV overflowed?!", msg: None});
390                         }
391                         last_short_channel_id = hop.short_channel_id;
392                 }
393                 Ok((res, cur_value_msat, cur_cltv))
394         }
395
396         #[inline]
397         fn shift_arr_right(arr: &mut [u8; 20*65]) {
398                 unsafe {
399                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
400                 }
401                 for i in 0..65 {
402                         arr[i] = 0;
403                 }
404         }
405
406         #[inline]
407         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
408                 assert_eq!(dst.len(), src.len());
409
410                 for i in 0..dst.len() {
411                         dst[i] ^= src[i];
412                 }
413         }
414
415         const ZERO:[u8; 21*65] = [0; 21*65];
416         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: Vec<u8>) -> Result<msgs::OnionPacket, HandleError> {
417                 let mut buf = Vec::with_capacity(21*65);
418                 buf.resize(21*65, 0);
419
420                 let filler = {
421                         let iters = payloads.len() - 1;
422                         let end_len = iters * 65;
423                         let mut res = Vec::with_capacity(end_len);
424                         res.resize(end_len, 0);
425
426                         for (i, keys) in onion_keys.iter().enumerate() {
427                                 if i == payloads.len() - 1 { continue; }
428                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
429                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
430                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
431                         }
432                         res
433                 };
434
435                 let mut packet_data = [0; 20*65];
436                 let mut hmac_res = [0; 32];
437
438                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
439                         ChannelManager::shift_arr_right(&mut packet_data);
440                         payload.hmac = hmac_res;
441                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
442
443                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
444                         chacha.process(&packet_data, &mut buf[0..20*65]);
445                         packet_data[..].copy_from_slice(&buf[0..20*65]);
446
447                         if i == 0 {
448                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
449                         }
450
451                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
452                         hmac.input(&packet_data);
453                         hmac.input(&associated_data[..]);
454                         hmac.raw_result(&mut hmac_res);
455                 }
456
457                 Ok(msgs::OnionPacket{
458                         version: 0,
459                         public_key: onion_keys.first().unwrap().ephemeral_pubkey,
460                         hop_data: packet_data,
461                         hmac: hmac_res,
462                 })
463         }
464
465         /// Encrypts a failure packet. raw_packet can either be a
466         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
467         fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
468                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
469
470                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
471                 packet_crypted.resize(raw_packet.len(), 0);
472                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
473                 chacha.process(&raw_packet, &mut packet_crypted[..]);
474                 msgs::OnionErrorPacket {
475                         data: packet_crypted,
476                 }
477         }
478
479         fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
480                 assert!(failure_data.len() <= 256 - 2);
481
482                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
483
484                 let failuremsg = {
485                         let mut res = Vec::with_capacity(2 + failure_data.len());
486                         res.push(((failure_type >> 8) & 0xff) as u8);
487                         res.push(((failure_type >> 0) & 0xff) as u8);
488                         res.extend_from_slice(&failure_data[..]);
489                         res
490                 };
491                 let pad = {
492                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
493                         res.resize(256 - 2 - failure_data.len(), 0);
494                         res
495                 };
496                 let mut packet = msgs::DecodedOnionErrorPacket {
497                         hmac: [0; 32],
498                         failuremsg: failuremsg,
499                         pad: pad,
500                 };
501
502                 let mut hmac = Hmac::new(Sha256::new(), &um);
503                 hmac.input(&packet.encode()[32..]);
504                 hmac.raw_result(&mut packet.hmac);
505
506                 packet
507         }
508
509         #[inline]
510         fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
511                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
512                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
513         }
514
515         /// only fails if the channel does not yet have an assigned short_id
516         fn get_channel_update(&self, chan: &mut Channel) -> Result<msgs::ChannelUpdate, HandleError> {
517                 let short_channel_id = match chan.get_short_channel_id() {
518                         None => return Err(HandleError{err: "Channel not yet established", msg: None}),
519                         Some(id) => id,
520                 };
521
522                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).unwrap().serialize()[..] < chan.get_their_node_id().serialize()[..];
523
524                 let unsigned = msgs::UnsignedChannelUpdate {
525                         chain_hash: self.genesis_hash,
526                         short_channel_id: short_channel_id,
527                         timestamp: chan.get_channel_update_count(),
528                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
529                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
530                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
531                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
532                         fee_proportional_millionths: self.fee_proportional_millionths,
533                 };
534
535                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
536                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key).unwrap(); //TODO Can we unwrap here?
537
538                 Ok(msgs::ChannelUpdate {
539                         signature: sig,
540                         contents: unsigned
541                 })
542         }
543
544         /// Sends a payment along a given route, returning the UpdateAddHTLC message to give to the
545         /// first hop in route. Value parameters are provided via the last hop in route, see
546         /// documentation for RouteHop fields for more info.
547         /// See-also docs on Channel::send_htlc_and_commit.
548         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<Option<(msgs::UpdateAddHTLC, msgs::CommitmentSigned)>, HandleError> {
549                 if route.hops.len() < 1 || route.hops.len() > 20 {
550                         return Err(HandleError{err: "Route didn't go anywhere/had bogus size", msg: None});
551                 }
552                 let our_node_id = self.get_our_node_id();
553                 for (idx, hop) in route.hops.iter().enumerate() {
554                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
555                                 return Err(HandleError{err: "Route went through us but wasn't a simple rebalance loop to us", msg: None});
556                         }
557                 }
558
559                 let session_priv = secp_call!(SecretKey::from_slice(&self.secp_ctx, &{
560                         let mut session_key = [0; 32];
561                         rng::fill_bytes(&mut session_key);
562                         session_key
563                 }));
564
565                 let associated_data = Vec::new(); //TODO: What to put here?
566
567                 let onion_keys = ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv)?;
568                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route)?;
569                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, associated_data)?;
570
571                 let mut channel_state = self.channel_state.lock().unwrap();
572                 let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
573                         None => return Err(HandleError{err: "No channel available with first hop!", msg: None}),
574                         Some(id) => id.clone()
575                 };
576                 let res = {
577                         let chan = channel_state.by_id.get_mut(&id).unwrap();
578                         if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
579                                 return Err(HandleError{err: "Node ID mismatch on first hop!", msg: None});
580                         }
581                         chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, onion_packet)?
582                 };
583
584                 if channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::OutboundRoute {
585                         route: route,
586                 }).is_some() {
587                         // TODO: We need to track these better, we're not generating these, so a
588                         // third-party might make this happen:
589                         panic!("payment_hash was repeated! Don't let this happen");
590                 }
591
592                 Ok(res)
593         }
594
595         /// Call this upon creation of a funding transaction for the given channel.
596         /// Panics if a funding transaction has already been provided for this channel.
597         pub fn funding_transaction_generated(&self, temporary_channel_id: &Uint256, funding_txo: (Sha256dHash, u16)) {
598                 let (chan, msg) = {
599                         let mut channel_state = self.channel_state.lock().unwrap();
600                         match channel_state.by_id.remove(&temporary_channel_id) {
601                                 Some(mut chan) => {
602                                         match chan.get_outbound_funding_created(funding_txo.0, funding_txo.1) {
603                                                 Ok(funding_msg) => {
604                                                         (chan, funding_msg)
605                                                 },
606                                                 Err(_e) => {
607                                                         //TODO: Push e to pendingevents
608                                                         return;
609                                                 }
610                                         }
611                                 },
612                                 None => return
613                         }
614                 }; // Release channel lock for install_watch_outpoint call,
615                 let chan_monitor = chan.channel_monitor();
616                 match self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
617                         Ok(()) => {},
618                         Err(_e) => {
619                                 //TODO: Push e to pendingevents?
620                                 return;
621                         }
622                 };
623
624                 {
625                         let mut pending_events = self.pending_events.lock().unwrap();
626                         pending_events.push(events::Event::SendFundingCreated {
627                                 node_id: chan.get_their_node_id(),
628                                 msg: msg,
629                         });
630                 }
631
632                 let mut channel_state = self.channel_state.lock().unwrap();
633                 channel_state.by_id.insert(chan.channel_id(), chan);
634         }
635
636         fn get_announcement_sigs(&self, chan: &Channel) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
637                 if !chan.is_usable() { return Ok(None) }
638
639                 let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone())?;
640                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
641                 let our_node_sig = secp_call!(self.secp_ctx.sign(&msghash, &self.our_network_key));
642
643                 Ok(Some(msgs::AnnouncementSignatures {
644                         channel_id: chan.channel_id(),
645                         short_channel_id: chan.get_short_channel_id().unwrap(),
646                         node_signature: our_node_sig,
647                         bitcoin_signature: our_bitcoin_sig,
648                 }))
649         }
650
651         pub fn process_pending_htlc_forward(&self) {
652                 let mut new_events = Vec::new();
653                 let mut failed_forwards = Vec::new();
654                 {
655                         let mut channel_state_lock = self.channel_state.lock().unwrap();
656                         let channel_state = channel_state_lock.borrow_parts();
657
658                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
659                                 return;
660                         }
661
662                         for (short_chan_id, pending_forwards) in channel_state.forward_htlcs.drain() {
663                                 if short_chan_id != 0 {
664                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
665                                                 Some(chan_id) => chan_id.clone(),
666                                                 None => {
667                                                         failed_forwards.reserve(pending_forwards.len());
668                                                         for forward_info in pending_forwards {
669                                                                 failed_forwards.push((forward_info.payment_hash, 0x4000 | 10, None));
670                                                         }
671                                                         // TODO: Send a failure packet back on each pending_forward
672                                                         continue;
673                                                 }
674                                         };
675                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
676
677                                         let mut add_htlc_msgs = Vec::new();
678                                         for forward_info in pending_forwards {
679                                                 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, forward_info.onion_packet.unwrap()) {
680                                                         Err(_e) => {
681                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
682                                                                 failed_forwards.push((forward_info.payment_hash, 0x4000 | 7, Some(chan_update)));
683                                                                 continue;
684                                                         },
685                                                         Ok(update_add) => {
686                                                                 match update_add {
687                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
688                                                                         None => {
689                                                                                 // Nothing to do here...we're waiting on a remote
690                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
691                                                                                 // will automatically handle building the update_add_htlc and
692                                                                                 // commitment_signed messages when we can.
693                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
694                                                                                 // as we don't really want others relying on us relaying through
695                                                                                 // this channel currently :/.
696                                                                         }
697                                                                 }
698                                                         }
699                                                 }
700                                         }
701
702                                         if !add_htlc_msgs.is_empty() {
703                                                 let commitment_msg = match forward_chan.send_commitment() {
704                                                         Ok(msg) => msg,
705                                                         Err(_) => {
706                                                                 //TODO: Handle...this is bad!
707                                                                 continue;
708                                                         },
709                                                 };
710                                                 new_events.push(events::Event::SendHTLCs {
711                                                         node_id: forward_chan.get_their_node_id(),
712                                                         msgs: add_htlc_msgs,
713                                                         commitment_msg: commitment_msg,
714                                                 });
715                                         }
716                                 } else {
717                                         for forward_info in pending_forwards {
718                                                 new_events.push(events::Event::PaymentReceived {
719                                                         payment_hash: forward_info.payment_hash,
720                                                         amt: forward_info.amt_to_forward,
721                                                 });
722                                         }
723                                 }
724                         }
725                 }
726
727                 for failed_forward in failed_forwards.drain(..) {
728                         match failed_forward.2 {
729                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: Vec::new() }),
730                                 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: chan_update.encode() }),
731                         };
732                 }
733
734                 if new_events.is_empty() { return }
735
736                 let mut events = self.pending_events.lock().unwrap();
737                 events.reserve(new_events.len());
738                 for event in new_events.drain(..) {
739                         events.push(event);
740                 }
741         }
742
743         /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
744         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
745                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() })
746         }
747
748         fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, payment_hash: &[u8; 32], onion_error: HTLCFailReason) -> bool {
749                 let mut pending_htlc = {
750                         match channel_state.claimable_htlcs.remove(payment_hash) {
751                                 Some(pending_htlc) => pending_htlc,
752                                 None => return false,
753                         }
754                 };
755
756                 match pending_htlc {
757                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, .. } => {
758                                 pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
759                         },
760                         _ => {}
761                 }
762
763                 match pending_htlc {
764                         PendingOutboundHTLC::CycledRoute { .. } => { panic!("WAT"); },
765                         PendingOutboundHTLC::OutboundRoute { .. } => {
766                                 //TODO: DECRYPT route from OutboundRoute
767                                 mem::drop(channel_state);
768                                 let mut pending_events = self.pending_events.lock().unwrap();
769                                 pending_events.push(events::Event::PaymentFailed {
770                                         payment_hash: payment_hash.clone()
771                                 });
772                                 false
773                         },
774                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret } => {
775                                 let err_packet = match onion_error {
776                                         HTLCFailReason::Reason { failure_code, data } => {
777                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
778                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
779                                         },
780                                         HTLCFailReason::ErrorPacket { err } => {
781                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
782                                         }
783                                 };
784
785                                 let (node_id, fail_msgs) = {
786                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
787                                                 Some(chan_id) => chan_id.clone(),
788                                                 None => return false
789                                         };
790
791                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
792                                         match chan.get_update_fail_htlc_and_commit(payment_hash, err_packet) {
793                                                 Ok(msg) => (chan.get_their_node_id(), msg),
794                                                 Err(_e) => {
795                                                         //TODO: Do something with e?
796                                                         return false;
797                                                 },
798                                         }
799                                 };
800
801                                 match fail_msgs {
802                                         Some(msgs) => {
803                                                 mem::drop(channel_state);
804                                                 let mut pending_events = self.pending_events.lock().unwrap();
805                                                 pending_events.push(events::Event::SendFailHTLC {
806                                                         node_id,
807                                                         msg: msgs.0,
808                                                         commitment_msg: msgs.1,
809                                                 });
810                                         },
811                                         None => {},
812                                 }
813
814                                 true
815                         },
816                 }
817         }
818
819         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
820         /// generating message events for the net layer to claim the payment, if possible. Thus, you
821         /// should probably kick the net layer to go send messages if this returns true!
822         /// May panic if called except in response to a PaymentReceived event.
823         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
824                 self.claim_funds_internal(payment_preimage, true)
825         }
826         pub fn claim_funds_internal(&self, payment_preimage: [u8; 32], from_user: bool) -> bool {
827                 let mut sha = Sha256::new();
828                 sha.input(&payment_preimage);
829                 let mut payment_hash = [0; 32];
830                 sha.result(&mut payment_hash);
831
832                 let mut channel_state = self.channel_state.lock().unwrap();
833                 let mut pending_htlc = {
834                         match channel_state.claimable_htlcs.remove(&payment_hash) {
835                                 Some(pending_htlc) => pending_htlc,
836                                 None => return false,
837                         }
838                 };
839
840                 match pending_htlc {
841                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, route } => {
842                                 if from_user { // This was the end hop back to us
843                                         pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
844                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::OutboundRoute { route });
845                                 } else { // This came from the first upstream node
846                                         // Bank error in our favor! Maybe we should tell the user this somehow???
847                                         pending_htlc = PendingOutboundHTLC::OutboundRoute { route };
848                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret });
849                                 }
850                         },
851                         _ => {},
852                 }
853
854                 match pending_htlc {
855                         PendingOutboundHTLC::CycledRoute { .. } => { panic!("WAT"); },
856                         PendingOutboundHTLC::OutboundRoute { .. } => {
857                                 if from_user {
858                                         panic!("Called claim_funds with a preimage for an outgoing payment. There is nothing we can do with this, and something is seriously wrong if you knew this...");
859                                 }
860                                 mem::drop(channel_state);
861                                 let mut pending_events = self.pending_events.lock().unwrap();
862                                 pending_events.push(events::Event::PaymentSent {
863                                         payment_preimage
864                                 });
865                                 false
866                         },
867                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, .. } => {
868                                 let (node_id, fulfill_msgs, monitor) = {
869                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
870                                                 Some(chan_id) => chan_id.clone(),
871                                                 None => return false
872                                         };
873
874                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
875                                         match chan.get_update_fulfill_htlc_and_commit(payment_preimage) {
876                                                 Ok(msg) => (chan.get_their_node_id(), msg, if from_user { Some(chan.channel_monitor()) } else { None }),
877                                                 Err(_e) => {
878                                                         //TODO: Do something with e?
879                                                         return false;
880                                                 },
881                                         }
882                                 };
883
884                                 mem::drop(channel_state);
885                                 match fulfill_msgs {
886                                         Some(msgs) => {
887                                                 let mut pending_events = self.pending_events.lock().unwrap();
888                                                 pending_events.push(events::Event::SendFulfillHTLC {
889                                                         node_id: node_id,
890                                                         msg: msgs.0,
891                                                         commitment_msg: msgs.1,
892                                                 });
893                                         },
894                                         None => {},
895                                 }
896
897                                 //TODO: It may not be possible to handle add_update_monitor fails gracefully, maybe
898                                 //it should return no Err? Sadly, panic!()s instead doesn't help much :(
899                                 if from_user {
900                                         match self.monitor.add_update_monitor(monitor.as_ref().unwrap().get_funding_txo().unwrap(), monitor.unwrap()) {
901                                                 Ok(()) => true,
902                                                 Err(_) => true,
903                                         }
904                                 } else { true }
905                         },
906                 }
907         }
908
909         /// Gets the node_id held by this ChannelManager
910         pub fn get_our_node_id(&self) -> PublicKey {
911                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).unwrap()
912         }
913 }
914
915 impl events::EventsProvider for ChannelManager {
916         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
917                 let mut pending_events = self.pending_events.lock().unwrap();
918                 let mut ret = Vec::new();
919                 mem::swap(&mut ret, &mut *pending_events);
920                 ret
921         }
922 }
923
924 impl ChainListener for ChannelManager {
925         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
926                 let mut new_funding_locked_messages = Vec::new();
927                 {
928                         let mut channel_state = self.channel_state.lock().unwrap();
929                         let mut short_to_ids_to_insert = Vec::new();
930                         for channel in channel_state.by_id.values_mut() {
931                                 match channel.block_connected(header, height, txn_matched, indexes_of_txn_matched) {
932                                         Some(funding_locked) => {
933                                                 let announcement_sigs = match self.get_announcement_sigs(channel) {
934                                                         Ok(res) => res,
935                                                         Err(_e) => {
936                                                                 //TODO: push e on events and blow up the channel (it has bad keys)
937                                                                 continue;
938                                                         }
939                                                 };
940                                                 new_funding_locked_messages.push(events::Event::SendFundingLocked {
941                                                         node_id: channel.get_their_node_id(),
942                                                         msg: funding_locked,
943                                                         announcement_sigs: announcement_sigs
944                                                 });
945                                                 short_to_ids_to_insert.push((channel.get_short_channel_id().unwrap(), channel.channel_id()));
946                                         },
947                                         None => {}
948                                 }
949                                 //TODO: Check if channel was closed (or disabled) here
950                         }
951                         for to_insert in short_to_ids_to_insert {
952                                 channel_state.short_to_id.insert(to_insert.0, to_insert.1);
953                         }
954                 }
955                 let mut pending_events = self.pending_events.lock().unwrap();
956                 for funding_locked in new_funding_locked_messages.drain(..) {
957                         pending_events.push(funding_locked);
958                 }
959         }
960
961         fn block_disconnected(&self, header: &BlockHeader) {
962                 let mut channel_state = self.channel_state.lock().unwrap();
963                 for channel in channel_state.by_id.values_mut() {
964                         if channel.block_disconnected(header) {
965                                 //TODO Close channel here
966                         }
967                 }
968         }
969 }
970
971 impl ChannelMessageHandler for ChannelManager {
972         //TODO: Handle errors and close channel (or so)
973         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
974                 if msg.chain_hash != self.genesis_hash {
975                         return Err(HandleError{err: "Unknown genesis block hash", msg: None});
976                 }
977                 let mut channel_state = self.channel_state.lock().unwrap();
978                 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
979                         return Err(HandleError{err: "temporary_channel_id collision!", msg: None});
980                 }
981                 let channel = Channel::new_from_req(&*self.fee_estimator, their_node_id.clone(), msg, 0, self.announce_channels_publicly)?;
982                 let accept_msg = channel.get_accept_channel()?;
983                 channel_state.by_id.insert(channel.channel_id(), channel);
984                 Ok(accept_msg)
985         }
986
987         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
988                 let (value, output_script, user_id) = {
989                         let mut channel_state = self.channel_state.lock().unwrap();
990                         match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
991                                 Some(chan) => {
992                                         if chan.get_their_node_id() != *their_node_id {
993                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
994                                         }
995                                         chan.accept_channel(&msg)?;
996                                         (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
997                                 },
998                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
999                         }
1000                 };
1001                 let mut pending_events = self.pending_events.lock().unwrap();
1002                 pending_events.push(events::Event::FundingGenerationReady {
1003                         temporary_channel_id: msg.temporary_channel_id,
1004                         channel_value_satoshis: value,
1005                         output_script: output_script,
1006                         user_channel_id: user_id,
1007                 });
1008                 Ok(())
1009         }
1010
1011         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
1012                 //TODO: broke this - a node shouldn't be able to get their channel removed by sending a
1013                 //funding_created a second time, or long after the first, or whatever (note this also
1014                 //leaves the short_to_id map in a busted state.
1015                 let chan = {
1016                         let mut channel_state = self.channel_state.lock().unwrap();
1017                         match channel_state.by_id.remove(&msg.temporary_channel_id) {
1018                                 Some(mut chan) => {
1019                                         if chan.get_their_node_id() != *their_node_id {
1020                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1021                                         }
1022                                         match chan.funding_created(msg) {
1023                                                 Ok(funding_msg) => {
1024                                                         (chan, funding_msg)
1025                                                 },
1026                                                 Err(e) => {
1027                                                         return Err(e);
1028                                                 }
1029                                         }
1030                                 },
1031                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1032                         }
1033                 }; // Release channel lock for install_watch_outpoint call,
1034                    // note that this means if the remote end is misbehaving and sends a message for the same
1035                    // channel back-to-back with funding_created, we'll end up thinking they sent a message
1036                    // for a bogus channel.
1037                 let chan_monitor = chan.0.channel_monitor();
1038                 self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor)?;
1039                 let mut channel_state = self.channel_state.lock().unwrap();
1040                 channel_state.by_id.insert(chan.1.channel_id, chan.0);
1041                 Ok(chan.1)
1042         }
1043
1044         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
1045                 let (funding_txo, user_id) = {
1046                         let mut channel_state = self.channel_state.lock().unwrap();
1047                         match channel_state.by_id.get_mut(&msg.channel_id) {
1048                                 Some(chan) => {
1049                                         if chan.get_their_node_id() != *their_node_id {
1050                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1051                                         }
1052                                         chan.funding_signed(&msg)?;
1053                                         (chan.get_funding_txo().unwrap(), chan.get_user_id())
1054                                 },
1055                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1056                         }
1057                 };
1058                 let mut pending_events = self.pending_events.lock().unwrap();
1059                 pending_events.push(events::Event::FundingBroadcastSafe {
1060                         funding_txo: funding_txo,
1061                         user_channel_id: user_id,
1062                 });
1063                 Ok(())
1064         }
1065
1066         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
1067                 let mut channel_state = self.channel_state.lock().unwrap();
1068                 match channel_state.by_id.get_mut(&msg.channel_id) {
1069                         Some(chan) => {
1070                                 if chan.get_their_node_id() != *their_node_id {
1071                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1072                                 }
1073                                 chan.funding_locked(&msg)?;
1074                                 return Ok(self.get_announcement_sigs(chan)?);
1075                         },
1076                         None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1077                 };
1078         }
1079
1080         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
1081                 let res = {
1082                         let mut channel_state = self.channel_state.lock().unwrap();
1083
1084                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1085                                 hash_map::Entry::Occupied(mut chan_entry) => {
1086                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1087                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1088                                         }
1089                                         let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg)?;
1090                                         if chan_entry.get().is_shutdown() {
1091                                                 chan_entry.remove_entry();
1092                                         }
1093                                         res
1094                                 },
1095                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1096                         }
1097                 };
1098                 for payment_hash in res.2 {
1099                         // unknown_next_peer...I dunno who that is anymore....
1100                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1101                 }
1102                 Ok((res.0, res.1))
1103         }
1104
1105         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
1106                 let res = {
1107                         let mut channel_state = self.channel_state.lock().unwrap();
1108                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1109                                 hash_map::Entry::Occupied(mut chan_entry) => {
1110                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1111                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1112                                         }
1113                                         let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg)?;
1114                                         if res.1.is_some() {
1115                                                 // We're done with this channel, we've got a signed closing transaction and
1116                                                 // will send the closing_signed back to the remote peer upon return. This
1117                                                 // also implies there are no pending HTLCs left on the channel, so we can
1118                                                 // fully delete it from tracking (the channel monitor is still around to
1119                                                 // watch for old state broadcasts)!
1120                                                 chan_entry.remove_entry();
1121                                         }
1122                                         res
1123                                 },
1124                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1125                         }
1126                 };
1127                 if let Some(broadcast_tx) = res.1 {
1128                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1129                 }
1130                 Ok(res.0)
1131         }
1132
1133         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
1134                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1135                 //determine the state of the payment based on our response/if we forward anything/the time
1136                 //we take to respond. We should take care to avoid allowing such an attack.
1137                 //
1138                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1139                 //us repeatedly garbled in different ways, and compare our error messages, which are
1140                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1141                 //but we should prevent it anyway.
1142
1143                 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key, &self.our_network_key);
1144                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1145
1146                 let associated_data = Vec::new(); //TODO: What to put here?
1147
1148                 macro_rules! get_onion_hash {
1149                         () => {
1150                                 {
1151                                         let mut sha = Sha256::new();
1152                                         sha.input(&msg.onion_routing_packet.hop_data);
1153                                         let mut onion_hash = [0; 32];
1154                                         sha.result(&mut onion_hash);
1155                                         onion_hash
1156                                 }
1157                         }
1158                 }
1159
1160                 macro_rules! return_err {
1161                         ($msg: expr, $err_code: expr, $data: expr) => {
1162                                 return Err(msgs::HandleError {
1163                                         err: $msg,
1164                                         msg: Some(msgs::ErrorAction::UpdateFailHTLC {
1165                                                 msg: msgs::UpdateFailHTLC {
1166                                                         channel_id: msg.channel_id,
1167                                                         htlc_id: msg.htlc_id,
1168                                                         reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1169                                                 }
1170                                         }),
1171                                 });
1172                         }
1173                 }
1174
1175                 if msg.onion_routing_packet.version != 0 {
1176                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1177                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1178                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1179                         //receiving node would have to brute force to figure out which version was put in the
1180                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1181                         //node knows the HMAC matched, so they already know what is there...
1182                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1183                 }
1184
1185                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1186                 hmac.input(&msg.onion_routing_packet.hop_data);
1187                 hmac.input(&associated_data[..]);
1188                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1189                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1190                 }
1191
1192                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1193                 let next_hop_data = {
1194                         let mut decoded = [0; 65];
1195                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1196                         match msgs::OnionHopData::decode(&decoded[..]) {
1197                                 Err(err) => {
1198                                         let error_code = match err {
1199                                                 msgs::DecodeError::UnknownRealmByte => 0x4000 | 1,
1200                                                 _ => 0x2000 | 2, // Should never happen
1201                                         };
1202                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1203                                 },
1204                                 Ok(msg) => msg
1205                         }
1206                 };
1207
1208                 let mut pending_forward_info = if next_hop_data.hmac == [0; 32] {
1209                                 // OUR PAYMENT!
1210                                 if next_hop_data.data.amt_to_forward != msg.amount_msat {
1211                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1212                                 }
1213                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1214                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1215                                 }
1216
1217                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1218                                 // message, however that would leak that we are the recipient of this payment, so
1219                                 // instead we stay symmetric with the forwarding case, only responding (after a
1220                                 // delay) once they've send us a commitment_signed!
1221
1222                                 PendingForwardHTLCInfo {
1223                                         onion_packet: None,
1224                                         payment_hash: msg.payment_hash.clone(),
1225                                         short_channel_id: 0,
1226                                         prev_short_channel_id: 0,
1227                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1228                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1229                                 }
1230                         } else {
1231                                 let mut new_packet_data = [0; 20*65];
1232                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1233                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1234
1235                                 let mut new_pubkey = msg.onion_routing_packet.public_key.clone();
1236
1237                                 let blinding_factor = {
1238                                         let mut sha = Sha256::new();
1239                                         sha.input(&new_pubkey.serialize()[..]);
1240                                         sha.input(&shared_secret[..]);
1241                                         let mut res = [0u8; 32];
1242                                         sha.result(&mut res);
1243                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1244                                                 Err(_) => {
1245                                                         // Return temporary node failure as its technically our issue, not the
1246                                                         // channel's issue.
1247                                                         return_err!("Blinding factor is an invalid private key", 0x2000 | 2, &[0;0]);
1248                                                 },
1249                                                 Ok(key) => key
1250                                         }
1251                                 };
1252
1253                                 match new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1254                                         Err(_) => {
1255                                                 // Return temporary node failure as its technically our issue, not the
1256                                                 // channel's issue.
1257                                                 return_err!("New blinding factor is an invalid private key", 0x2000 | 2, &[0;0]);
1258                                         },
1259                                         Ok(_) => {}
1260                                 };
1261
1262                                 let outgoing_packet = msgs::OnionPacket {
1263                                         version: 0,
1264                                         public_key: new_pubkey,
1265                                         hop_data: new_packet_data,
1266                                         hmac: next_hop_data.hmac.clone(),
1267                                 };
1268
1269                                 //TODO: Check amt_to_forward and outgoing_cltv_value are within acceptable ranges!
1270
1271                                 PendingForwardHTLCInfo {
1272                                         onion_packet: Some(outgoing_packet),
1273                                         payment_hash: msg.payment_hash.clone(),
1274                                         short_channel_id: next_hop_data.data.short_channel_id,
1275                                         prev_short_channel_id: 0,
1276                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1277                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1278                                 }
1279                         };
1280
1281                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1282                 let channel_state = channel_state_lock.borrow_parts();
1283
1284                 if pending_forward_info.onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1285                         let forwarding_id = match channel_state.short_to_id.get(&pending_forward_info.short_channel_id) {
1286                                 None => {
1287                                         return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1288                                 },
1289                                 Some(id) => id.clone(),
1290                         };
1291                         let chan = channel_state.by_id.get_mut(&forwarding_id).unwrap();
1292                         if !chan.is_live() {
1293                                 let chan_update = self.get_channel_update(chan).unwrap();
1294                                 return_err!("Forwarding channel is not in a ready state.", 0x4000 | 10, &chan_update.encode()[..]);
1295                         }
1296                 }
1297
1298                 let claimable_htlcs_entry = channel_state.claimable_htlcs.entry(msg.payment_hash.clone());
1299
1300                 // We dont correctly handle payments that route through us twice on their way to their
1301                 // destination. That's OK since those nodes are probably busted or trying to do network
1302                 // mapping through repeated loops. In either case, we want them to stop talking to us, so
1303                 // we send permanent_node_failure.
1304                 match &claimable_htlcs_entry {
1305                         &hash_map::Entry::Occupied(ref e) => {
1306                                 let mut acceptable_cycle = false;
1307                                 match e.get() {
1308                                         &PendingOutboundHTLC::OutboundRoute { .. } => {
1309                                                 acceptable_cycle = pending_forward_info.short_channel_id == 0;
1310                                         },
1311                                         _ => {},
1312                                 }
1313                                 if !acceptable_cycle {
1314                                         return_err!("Payment looped through us twice", 0x4000 | 0x2000 | 2, &[0;0]);
1315                                 }
1316                         },
1317                         _ => {},
1318                 }
1319
1320                 let (source_short_channel_id, res) = match channel_state.by_id.get_mut(&msg.channel_id) {
1321                         Some(chan) => {
1322                                 if chan.get_their_node_id() != *their_node_id {
1323                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1324                                 }
1325                                 if !chan.is_usable() {
1326                                         return Err(HandleError{err: "Channel not yet available for receiving HTLCs", msg: None});
1327                                 }
1328                                 let short_channel_id = chan.get_short_channel_id().unwrap();
1329                                 pending_forward_info.prev_short_channel_id = short_channel_id;
1330                                 (short_channel_id, chan.update_add_htlc(&msg, pending_forward_info)?)
1331                         },
1332                         None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None}), //TODO: panic?
1333                 };
1334
1335                 match claimable_htlcs_entry {
1336                         hash_map::Entry::Occupied(mut e) => {
1337                                 let outbound_route = e.get_mut();
1338                                 let route = match outbound_route {
1339                                         &mut PendingOutboundHTLC::OutboundRoute { ref route } => {
1340                                                 route.clone()
1341                                         },
1342                                         _ => { panic!("WAT") },
1343                                 };
1344                                 *outbound_route = PendingOutboundHTLC::CycledRoute {
1345                                         source_short_channel_id,
1346                                         incoming_packet_shared_secret: shared_secret,
1347                                         route
1348                                 };
1349                         },
1350                         hash_map::Entry::Vacant(e) => {
1351                                 e.insert(PendingOutboundHTLC::IntermediaryHopData {
1352                                         source_short_channel_id,
1353                                         incoming_packet_shared_secret: shared_secret,
1354                                 });
1355                         }
1356                 }
1357
1358                 Ok(res)
1359         }
1360
1361         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
1362                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1363                 // Claim funds first, cause we don't really care if the channel we received the message on
1364                 // is broken, we may have enough info to get our own money!
1365                 self.claim_funds_internal(msg.payment_preimage.clone(), false);
1366
1367                 let monitor = {
1368                         let mut channel_state = self.channel_state.lock().unwrap();
1369                         match channel_state.by_id.get_mut(&msg.channel_id) {
1370                                 Some(chan) => {
1371                                         if chan.get_their_node_id() != *their_node_id {
1372                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1373                                         }
1374                                         chan.update_fulfill_htlc(&msg)?;
1375                                         chan.channel_monitor()
1376                                 },
1377                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1378                         }
1379                 };
1380                 self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor)?;
1381                 Ok(())
1382         }
1383
1384         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
1385                 let mut channel_state = self.channel_state.lock().unwrap();
1386                 match channel_state.by_id.get_mut(&msg.channel_id) {
1387                         Some(chan) => {
1388                                 if chan.get_their_node_id() != *their_node_id {
1389                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1390                                 }
1391                                 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
1392                         },
1393                         None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1394                 }
1395         }
1396
1397         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
1398                 let mut channel_state = self.channel_state.lock().unwrap();
1399                 match channel_state.by_id.get_mut(&msg.channel_id) {
1400                         Some(chan) => {
1401                                 if chan.get_their_node_id() != *their_node_id {
1402                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1403                                 }
1404                                 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() })
1405                         },
1406                         None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1407                 }
1408         }
1409
1410         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
1411                 let (res, monitor) = {
1412                         let mut channel_state = self.channel_state.lock().unwrap();
1413                         match channel_state.by_id.get_mut(&msg.channel_id) {
1414                                 Some(chan) => {
1415                                         if chan.get_their_node_id() != *their_node_id {
1416                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1417                                         }
1418                                         (chan.commitment_signed(&msg)?, chan.channel_monitor())
1419                                 },
1420                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1421                         }
1422                 };
1423                 //TODO: Only if we store HTLC sigs
1424                 self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor)?;
1425
1426                 Ok(res)
1427         }
1428
1429         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
1430                 let ((res, mut pending_forwards, mut pending_failures), monitor) = {
1431                         let mut channel_state = self.channel_state.lock().unwrap();
1432                         match channel_state.by_id.get_mut(&msg.channel_id) {
1433                                 Some(chan) => {
1434                                         if chan.get_their_node_id() != *their_node_id {
1435                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1436                                         }
1437                                         (chan.revoke_and_ack(&msg)?, chan.channel_monitor())
1438                                 },
1439                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1440                         }
1441                 };
1442                 self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor)?;
1443                 for failure in pending_failures.drain(..) {
1444                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failure.0, failure.1);
1445                 }
1446
1447                 let mut forward_event = None;
1448                 if !pending_forwards.is_empty() {
1449                         let mut channel_state = self.channel_state.lock().unwrap();
1450                         if channel_state.forward_htlcs.is_empty() {
1451                                 forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
1452                                 channel_state.next_forward = forward_event.unwrap();
1453                         }
1454                         for forward_info in pending_forwards.drain(..) {
1455                                 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
1456                                         hash_map::Entry::Occupied(mut entry) => {
1457                                                 entry.get_mut().push(forward_info);
1458                                         },
1459                                         hash_map::Entry::Vacant(entry) => {
1460                                                 entry.insert(vec!(forward_info));
1461                                         }
1462                                 }
1463                         }
1464                 }
1465                 match forward_event {
1466                         Some(time) => {
1467                                 let mut pending_events = self.pending_events.lock().unwrap();
1468                                 pending_events.push(events::Event::PendingHTLCsForwardable {
1469                                         time_forwardable: time
1470                                 });
1471                         }
1472                         None => {},
1473                 }
1474
1475                 Ok(res)
1476         }
1477
1478         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
1479                 let mut channel_state = self.channel_state.lock().unwrap();
1480                 match channel_state.by_id.get_mut(&msg.channel_id) {
1481                         Some(chan) => {
1482                                 if chan.get_their_node_id() != *their_node_id {
1483                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1484                                 }
1485                                 chan.update_fee(&*self.fee_estimator, &msg)
1486                         },
1487                         None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1488                 }
1489         }
1490
1491         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
1492                 let (chan_announcement, chan_update) = {
1493                         let mut channel_state = self.channel_state.lock().unwrap();
1494                         match channel_state.by_id.get_mut(&msg.channel_id) {
1495                                 Some(chan) => {
1496                                         if chan.get_their_node_id() != *their_node_id {
1497                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", msg: None})
1498                                         }
1499                                         if !chan.is_usable() {
1500                                                 return Err(HandleError{err: "Got an announcement_signatures before we were ready for it", msg: None });
1501                                         }
1502
1503                                         let our_node_id = self.get_our_node_id();
1504                                         let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())?;
1505
1506                                         let were_node_one = announcement.node_id_1 == our_node_id;
1507                                         let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1508                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }));
1509                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }));
1510
1511                                         let our_node_sig = secp_call!(self.secp_ctx.sign(&msghash, &self.our_network_key));
1512
1513                                         (msgs::ChannelAnnouncement {
1514                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
1515                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
1516                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
1517                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
1518                                                 contents: announcement,
1519                                         }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
1520                                 },
1521                                 None => return Err(HandleError{err: "Failed to find corresponding channel", msg: None})
1522                         }
1523                 };
1524                 let mut pending_events = self.pending_events.lock().unwrap();
1525                 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
1526                 Ok(())
1527         }
1528
1529         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
1530                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1531                 let channel_state = channel_state_lock.borrow_parts();
1532                 let short_to_id = channel_state.short_to_id;
1533                 if no_connection_possible {
1534                         channel_state.by_id.retain(move |_, chan| {
1535                                 if chan.get_their_node_id() == *their_node_id {
1536                                         match chan.get_short_channel_id() {
1537                                                 Some(short_id) => {
1538                                                         short_to_id.remove(&short_id);
1539                                                 },
1540                                                 None => {},
1541                                         }
1542                                         //TODO: get the latest commitment tx, any HTLC txn built on top of it, etc out
1543                                         //of the channel and throw those into the announcement blackhole.
1544                                         false
1545                                 } else {
1546                                         true
1547                                 }
1548                         });
1549                 } else {
1550                         for chan in channel_state.by_id {
1551                                 if chan.1.get_their_node_id() == *their_node_id {
1552                                         //TODO: mark channel disabled (and maybe announce such after a timeout). Also
1553                                         //fail and wipe any uncommitted outbound HTLCs as those are considered after
1554                                         //reconnect.
1555                                 }
1556                         }
1557                 }
1558         }
1559 }
1560
1561 #[cfg(test)]
1562 mod tests {
1563         use chain::chaininterface;
1564         use ln::channelmanager::{ChannelManager,OnionKeys};
1565         use ln::router::{Route, RouteHop, Router};
1566         use ln::msgs;
1567         use ln::msgs::{MsgEncodable,ChannelMessageHandler,RoutingMessageHandler};
1568         use util::test_utils;
1569         use util::events::{Event, EventsProvider};
1570
1571         use bitcoin::util::misc::hex_bytes;
1572         use bitcoin::util::hash::Sha256dHash;
1573         use bitcoin::util::uint::Uint256;
1574         use bitcoin::blockdata::block::BlockHeader;
1575         use bitcoin::blockdata::transaction::{Transaction, TxOut};
1576         use bitcoin::network::constants::Network;
1577         use bitcoin::network::serialize::serialize;
1578         use bitcoin::network::serialize::BitcoinHash;
1579
1580         use secp256k1::Secp256k1;
1581         use secp256k1::key::{PublicKey,SecretKey};
1582
1583         use crypto::sha2::Sha256;
1584         use crypto::digest::Digest;
1585
1586         use rand::{thread_rng,Rng};
1587
1588         use std::collections::HashMap;
1589         use std::default::Default;
1590         use std::sync::{Arc, Mutex};
1591         use std::time::Instant;
1592
1593         fn build_test_onion_keys() -> Vec<OnionKeys> {
1594                 // Keys from BOLT 4, used in both test vector tests
1595                 let secp_ctx = Secp256k1::new();
1596
1597                 let route = Route {
1598                         hops: vec!(
1599                                         RouteHop {
1600                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex_bytes("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1601                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
1602                                         },
1603                                         RouteHop {
1604                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex_bytes("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1605                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
1606                                         },
1607                                         RouteHop {
1608                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex_bytes("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1609                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
1610                                         },
1611                                         RouteHop {
1612                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex_bytes("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
1613                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
1614                                         },
1615                                         RouteHop {
1616                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex_bytes("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
1617                                                 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
1618                                         },
1619                         ),
1620                 };
1621
1622                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex_bytes("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
1623
1624                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1625                 assert_eq!(onion_keys.len(), route.hops.len());
1626                 onion_keys
1627         }
1628
1629         #[test]
1630         fn onion_vectors() {
1631                 // Packet creation test vectors from BOLT 4
1632                 let onion_keys = build_test_onion_keys();
1633
1634                 assert_eq!(onion_keys[0].shared_secret[..], hex_bytes("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
1635                 assert_eq!(onion_keys[0].blinding_factor[..], hex_bytes("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
1636                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex_bytes("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
1637                 assert_eq!(onion_keys[0].rho, hex_bytes("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
1638                 assert_eq!(onion_keys[0].mu, hex_bytes("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
1639
1640                 assert_eq!(onion_keys[1].shared_secret[..], hex_bytes("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
1641                 assert_eq!(onion_keys[1].blinding_factor[..], hex_bytes("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
1642                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex_bytes("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
1643                 assert_eq!(onion_keys[1].rho, hex_bytes("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
1644                 assert_eq!(onion_keys[1].mu, hex_bytes("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
1645
1646                 assert_eq!(onion_keys[2].shared_secret[..], hex_bytes("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
1647                 assert_eq!(onion_keys[2].blinding_factor[..], hex_bytes("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
1648                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex_bytes("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
1649                 assert_eq!(onion_keys[2].rho, hex_bytes("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
1650                 assert_eq!(onion_keys[2].mu, hex_bytes("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
1651
1652                 assert_eq!(onion_keys[3].shared_secret[..], hex_bytes("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
1653                 assert_eq!(onion_keys[3].blinding_factor[..], hex_bytes("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
1654                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex_bytes("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
1655                 assert_eq!(onion_keys[3].rho, hex_bytes("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
1656                 assert_eq!(onion_keys[3].mu, hex_bytes("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
1657
1658                 assert_eq!(onion_keys[4].shared_secret[..], hex_bytes("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
1659                 assert_eq!(onion_keys[4].blinding_factor[..], hex_bytes("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
1660                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex_bytes("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
1661                 assert_eq!(onion_keys[4].rho, hex_bytes("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
1662                 assert_eq!(onion_keys[4].mu, hex_bytes("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
1663
1664                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
1665                 let payloads = vec!(
1666                         msgs::OnionHopData {
1667                                 realm: 0,
1668                                 data: msgs::OnionRealm0HopData {
1669                                         short_channel_id: 0,
1670                                         amt_to_forward: 0,
1671                                         outgoing_cltv_value: 0,
1672                                 },
1673                                 hmac: [0; 32],
1674                         },
1675                         msgs::OnionHopData {
1676                                 realm: 0,
1677                                 data: msgs::OnionRealm0HopData {
1678                                         short_channel_id: 0x0101010101010101,
1679                                         amt_to_forward: 0x0100000001,
1680                                         outgoing_cltv_value: 0,
1681                                 },
1682                                 hmac: [0; 32],
1683                         },
1684                         msgs::OnionHopData {
1685                                 realm: 0,
1686                                 data: msgs::OnionRealm0HopData {
1687                                         short_channel_id: 0x0202020202020202,
1688                                         amt_to_forward: 0x0200000002,
1689                                         outgoing_cltv_value: 0,
1690                                 },
1691                                 hmac: [0; 32],
1692                         },
1693                         msgs::OnionHopData {
1694                                 realm: 0,
1695                                 data: msgs::OnionRealm0HopData {
1696                                         short_channel_id: 0x0303030303030303,
1697                                         amt_to_forward: 0x0300000003,
1698                                         outgoing_cltv_value: 0,
1699                                 },
1700                                 hmac: [0; 32],
1701                         },
1702                         msgs::OnionHopData {
1703                                 realm: 0,
1704                                 data: msgs::OnionRealm0HopData {
1705                                         short_channel_id: 0x0404040404040404,
1706                                         amt_to_forward: 0x0400000004,
1707                                         outgoing_cltv_value: 0,
1708                                 },
1709                                 hmac: [0; 32],
1710                         },
1711                 );
1712
1713                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, hex_bytes("4242424242424242424242424242424242424242424242424242424242424242").unwrap()).unwrap();
1714                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
1715                 // anyway...
1716                 assert_eq!(packet.encode(), hex_bytes("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
1717         }
1718
1719         #[test]
1720         fn test_failure_packet_onion() {
1721                 // Returning Errors test vectors from BOLT 4
1722
1723                 let onion_keys = build_test_onion_keys();
1724                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
1725                 assert_eq!(onion_error.encode(), hex_bytes("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
1726
1727                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
1728                 assert_eq!(onion_packet_1.data, hex_bytes("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
1729
1730                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
1731                 assert_eq!(onion_packet_2.data, hex_bytes("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
1732
1733                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
1734                 assert_eq!(onion_packet_3.data, hex_bytes("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
1735
1736                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
1737                 assert_eq!(onion_packet_4.data, hex_bytes("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
1738
1739                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
1740                 assert_eq!(onion_packet_5.data, hex_bytes("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
1741         }
1742
1743         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
1744                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1745                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
1746                 for i in 2..100 {
1747                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1748                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
1749                 }
1750         }
1751
1752         struct Node {
1753                 feeest: Arc<test_utils::TestFeeEstimator>,
1754                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
1755                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
1756                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
1757                 node_id: SecretKey,
1758                 node: Arc<ChannelManager>,
1759                 router: Router,
1760         }
1761
1762         static mut CHAN_COUNT: u32 = 0;
1763         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, Uint256, Transaction) {
1764                 let open_chan = node_a.node.create_channel(node_b.node.get_our_node_id(), 100000, 42).unwrap();
1765                 let accept_chan = node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &open_chan).unwrap();
1766                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
1767
1768                 let chan_id = unsafe { CHAN_COUNT };
1769                 let tx;
1770                 let funding_output;
1771
1772                 let events_1 = node_a.node.get_and_clear_pending_events();
1773                 assert_eq!(events_1.len(), 1);
1774                 match events_1[0] {
1775                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
1776                                 assert_eq!(*channel_value_satoshis, 100000);
1777                                 assert_eq!(user_channel_id, 42);
1778
1779                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
1780                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
1781                                 }]};
1782                                 funding_output = (Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
1783
1784                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output.clone());
1785                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
1786                                 assert_eq!(added_monitors.len(), 1);
1787                                 assert_eq!(added_monitors[0].0, funding_output);
1788                                 added_monitors.clear();
1789                         },
1790                         _ => panic!("Unexpected event"),
1791                 }
1792
1793                 let events_2 = node_a.node.get_and_clear_pending_events();
1794                 assert_eq!(events_2.len(), 1);
1795                 let funding_signed = match events_2[0] {
1796                         Event::SendFundingCreated { ref node_id, ref msg } => {
1797                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
1798                                 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
1799                                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
1800                                 assert_eq!(added_monitors.len(), 1);
1801                                 assert_eq!(added_monitors[0].0, funding_output);
1802                                 added_monitors.clear();
1803                                 res
1804                         },
1805                         _ => panic!("Unexpected event"),
1806                 };
1807
1808                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
1809
1810                 let events_3 = node_a.node.get_and_clear_pending_events();
1811                 assert_eq!(events_3.len(), 1);
1812                 match events_3[0] {
1813                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
1814                                 assert_eq!(user_channel_id, 42);
1815                                 assert_eq!(*funding_txo, funding_output);
1816                         },
1817                         _ => panic!("Unexpected event"),
1818                 };
1819
1820                 confirm_transaction(&node_a.chain_monitor, &tx, chan_id);
1821                 let events_4 = node_a.node.get_and_clear_pending_events();
1822                 assert_eq!(events_4.len(), 1);
1823                 match events_4[0] {
1824                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
1825                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
1826                                 assert!(announcement_sigs.is_none());
1827                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), msg).unwrap()
1828                         },
1829                         _ => panic!("Unexpected event"),
1830                 };
1831
1832                 let channel_id;
1833
1834                 confirm_transaction(&node_b.chain_monitor, &tx, chan_id);
1835                 let events_5 = node_b.node.get_and_clear_pending_events();
1836                 assert_eq!(events_5.len(), 1);
1837                 let as_announcement_sigs = match events_5[0] {
1838                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
1839                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
1840                                 channel_id = msg.channel_id.clone();
1841                                 let as_announcement_sigs = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap().unwrap();
1842                                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &(*announcement_sigs).clone().unwrap()).unwrap();
1843                                 as_announcement_sigs
1844                         },
1845                         _ => panic!("Unexpected event"),
1846                 };
1847
1848                 let events_6 = node_a.node.get_and_clear_pending_events();
1849                 assert_eq!(events_6.len(), 1);
1850                 let (announcement, as_update) = match events_6[0] {
1851                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1852                                 (msg, update_msg)
1853                         },
1854                         _ => panic!("Unexpected event"),
1855                 };
1856
1857                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_announcement_sigs).unwrap();
1858                 let events_7 = node_b.node.get_and_clear_pending_events();
1859                 assert_eq!(events_7.len(), 1);
1860                 let bs_update = match events_7[0] {
1861                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1862                                 assert!(*announcement == *msg);
1863                                 update_msg
1864                         },
1865                         _ => panic!("Unexpected event"),
1866                 };
1867
1868                 unsafe {
1869                         CHAN_COUNT += 1;
1870                 }
1871
1872                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone(), channel_id, tx)
1873         }
1874
1875         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Uint256, Transaction) {
1876                 let chan_announcement = create_chan_between_nodes(&nodes[a], &nodes[b]);
1877                 for node in nodes {
1878                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
1879                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
1880                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
1881                 }
1882                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
1883         }
1884
1885         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &Uint256, funding_tx: Transaction, close_inbound_first: bool) {
1886                 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
1887                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
1888                 let (tx_a, tx_b);
1889
1890                 let shutdown_a = node_a.close_channel(channel_id).unwrap();
1891                 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
1892                 if !close_inbound_first {
1893                         assert!(closing_signed_b.is_none());
1894                 }
1895                 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
1896                 assert!(empty_a.is_none());
1897                 if close_inbound_first {
1898                         assert!(closing_signed_a.is_none());
1899                         closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
1900                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1901                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1902
1903                         let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
1904                         assert!(empty_b.is_none());
1905                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1906                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1907                 } else {
1908                         closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
1909                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1910                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1911
1912                         let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
1913                         assert!(empty_a2.is_none());
1914                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1915                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1916                 }
1917                 assert_eq!(tx_a, tx_b);
1918                 let mut funding_tx_map = HashMap::new();
1919                 funding_tx_map.insert(funding_tx.txid(), funding_tx);
1920                 tx_a.verify(&funding_tx_map).unwrap();
1921         }
1922
1923         struct SendEvent {
1924                 node_id: PublicKey,
1925                 msgs: Vec<msgs::UpdateAddHTLC>,
1926                 commitment_msg: msgs::CommitmentSigned,
1927         }
1928         impl SendEvent {
1929                 fn from_event(event: Event) -> SendEvent {
1930                         match event {
1931                                 Event::SendHTLCs { node_id, msgs, commitment_msg } => {
1932                                         SendEvent { node_id: node_id, msgs: msgs, commitment_msg: commitment_msg }
1933                                 },
1934                                 _ => panic!("Unexpected event type!"),
1935                         }
1936                 }
1937         }
1938
1939         static mut PAYMENT_COUNT: u8 = 0;
1940         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
1941                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
1942                 unsafe { PAYMENT_COUNT += 1 };
1943                 let our_payment_hash = {
1944                         let mut sha = Sha256::new();
1945                         sha.input(&our_payment_preimage[..]);
1946                         let mut ret = [0; 32];
1947                         sha.result(&mut ret);
1948                         ret
1949                 };
1950
1951                 let mut payment_event = {
1952                         let msgs = origin_node.node.send_payment(route, our_payment_hash).unwrap().unwrap();
1953                         SendEvent {
1954                                 node_id: expected_route[0].node.get_our_node_id(),
1955                                 msgs: vec!(msgs.0),
1956                                 commitment_msg: msgs.1,
1957                         }
1958                 };
1959                 let mut prev_node = origin_node;
1960
1961                 for (idx, &node) in expected_route.iter().enumerate() {
1962                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1963
1964                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1965                         {
1966                                 let added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
1967                                 assert_eq!(added_monitors.len(), 0);
1968                         }
1969
1970                         let revoke_and_ack = node.node.handle_commitment_signed(&prev_node.node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
1971                         {
1972                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
1973                                 assert_eq!(added_monitors.len(), 1);
1974                                 added_monitors.clear();
1975                         }
1976                         assert!(prev_node.node.handle_revoke_and_ack(&node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
1977                         let prev_revoke_and_ack = prev_node.node.handle_commitment_signed(&node.node.get_our_node_id(), &revoke_and_ack.1.unwrap()).unwrap();
1978                         {
1979                                 let mut added_monitors = prev_node.chan_monitor.added_monitors.lock().unwrap();
1980                                 assert_eq!(added_monitors.len(), 2);
1981                                 added_monitors.clear();
1982                         }
1983                         assert!(node.node.handle_revoke_and_ack(&prev_node.node.get_our_node_id(), &prev_revoke_and_ack.0).unwrap().is_none());
1984                         assert!(prev_revoke_and_ack.1.is_none());
1985                         {
1986                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
1987                                 assert_eq!(added_monitors.len(), 1);
1988                                 added_monitors.clear();
1989                         }
1990
1991                         let events_1 = node.node.get_and_clear_pending_events();
1992                         assert_eq!(events_1.len(), 1);
1993                         match events_1[0] {
1994                                 Event::PendingHTLCsForwardable { .. } => { },
1995                                 _ => panic!("Unexpected event"),
1996                         };
1997
1998                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
1999                         node.node.process_pending_htlc_forward();
2000
2001                         let mut events_2 = node.node.get_and_clear_pending_events();
2002                         assert_eq!(events_2.len(), 1);
2003                         if idx == expected_route.len() - 1 {
2004                                 match events_2[0] {
2005                                         Event::PaymentReceived { ref payment_hash, amt } => {
2006                                                 assert_eq!(our_payment_hash, *payment_hash);
2007                                                 assert_eq!(amt, recv_value);
2008                                         },
2009                                         _ => panic!("Unexpected event"),
2010                                 }
2011                         } else {
2012                                 for event in events_2.drain(..) {
2013                                         payment_event = SendEvent::from_event(event);
2014                                 }
2015                                 assert_eq!(payment_event.msgs.len(), 1);
2016                         }
2017
2018                         prev_node = node;
2019                 }
2020
2021                 (our_payment_preimage, our_payment_hash)
2022         }
2023
2024         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
2025                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
2026                 {
2027                         let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2028                         assert_eq!(added_monitors.len(), 1);
2029                         added_monitors.clear();
2030                 }
2031
2032                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
2033                 macro_rules! update_fulfill_dance {
2034                         ($node: expr, $prev_node: expr) => {
2035                                 {
2036                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2037                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2038                                         {
2039                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2040                                                 assert_eq!(added_monitors.len(), 2);
2041                                                 added_monitors.clear();
2042                                         }
2043                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2044                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2045                                         assert!(revoke_and_ack.1.is_none());
2046                                         {
2047                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2048                                                 assert_eq!(added_monitors.len(), 2);
2049                                                 added_monitors.clear();
2050                                         }
2051                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2052                                         {
2053                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2054                                                 assert_eq!(added_monitors.len(), 1);
2055                                                 added_monitors.clear();
2056                                         }
2057                                 }
2058                         }
2059                 }
2060
2061                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2062                 let mut prev_node = expected_route.last().unwrap();
2063                 for node in expected_route.iter().rev() {
2064                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2065                         if next_msgs.is_some() {
2066                                 update_fulfill_dance!(node, prev_node);
2067                         }
2068
2069                         let events = node.node.get_and_clear_pending_events();
2070                         assert_eq!(events.len(), 1);
2071                         match events[0] {
2072                                 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
2073                                         expected_next_node = node_id.clone();
2074                                         next_msgs = Some((msg.clone(), commitment_msg.clone()));
2075                                 },
2076                                 _ => panic!("Unexpected event"),
2077                         };
2078
2079                         prev_node = node;
2080                 }
2081
2082                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2083                 update_fulfill_dance!(origin_node, expected_route.first().unwrap());
2084
2085                 let events = origin_node.node.get_and_clear_pending_events();
2086                 assert_eq!(events.len(), 1);
2087                 match events[0] {
2088                         Event::PaymentSent { payment_preimage } => {
2089                                 assert_eq!(payment_preimage, our_payment_preimage);
2090                         },
2091                         _ => panic!("Unexpected event"),
2092                 }
2093         }
2094
2095         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2096                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), &Vec::new(), recv_value, 142).unwrap();
2097                 assert_eq!(route.hops.len(), expected_route.len());
2098                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2099                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2100                 }
2101
2102                 send_along_route(origin_node, route, expected_route, recv_value)
2103         }
2104
2105         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
2106                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), &Vec::new(), recv_value, 142).unwrap();
2107                 assert_eq!(route.hops.len(), expected_route.len());
2108                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2109                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2110                 }
2111
2112                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
2113                 unsafe { PAYMENT_COUNT += 1 };
2114                 let our_payment_hash = {
2115                         let mut sha = Sha256::new();
2116                         sha.input(&our_payment_preimage[..]);
2117                         let mut ret = [0; 32];
2118                         sha.result(&mut ret);
2119                         ret
2120                 };
2121
2122                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
2123                 assert_eq!(err.err, "Cannot send value that would put us over our max HTLC value in flight");
2124         }
2125
2126         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
2127                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
2128                 claim_payment(&origin, expected_route, our_payment_preimage);
2129         }
2130
2131         fn send_failed_payment(origin_node: &Node, expected_route: &[&Node]) {
2132                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), &Vec::new(), 1000000, 142).unwrap();
2133                 assert_eq!(route.hops.len(), expected_route.len());
2134                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2135                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2136                 }
2137                 let our_payment_hash = send_along_route(origin_node, route, expected_route, 1000000).1;
2138
2139                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
2140
2141                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
2142                 macro_rules! update_fail_dance {
2143                         ($node: expr, $prev_node: expr) => {
2144                                 {
2145                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2146                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2147                                         {
2148                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2149                                                 assert_eq!(added_monitors.len(), 1);
2150                                                 added_monitors.clear();
2151                                         }
2152                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2153                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2154                                         assert!(revoke_and_ack.1.is_none());
2155                                         {
2156                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2157                                                 assert_eq!(added_monitors.len(), 2);
2158                                                 added_monitors.clear();
2159                                         }
2160                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2161                                         {
2162                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2163                                                 assert_eq!(added_monitors.len(), 1);
2164                                                 added_monitors.clear();
2165                                         }
2166                                 }
2167                         }
2168                 }
2169
2170                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2171                 let mut prev_node = expected_route.last().unwrap();
2172                 for node in expected_route.iter().rev() {
2173                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2174                         if next_msgs.is_some() {
2175                                 update_fail_dance!(node, prev_node);
2176                         }
2177
2178                         let events = node.node.get_and_clear_pending_events();
2179                         assert_eq!(events.len(), 1);
2180                         match events[0] {
2181                                 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
2182                                         expected_next_node = node_id.clone();
2183                                         next_msgs = Some((msg.clone(), commitment_msg.clone()));
2184                                 },
2185                                 _ => panic!("Unexpected event"),
2186                         };
2187
2188                         prev_node = node;
2189                 }
2190
2191                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2192                 update_fail_dance!(origin_node, expected_route.first().unwrap());
2193
2194                 let events = origin_node.node.get_and_clear_pending_events();
2195                 assert_eq!(events.len(), 1);
2196                 match events[0] {
2197                         Event::PaymentFailed { payment_hash } => {
2198                                 assert_eq!(payment_hash, our_payment_hash);
2199                         },
2200                         _ => panic!("Unexpected event"),
2201                 }
2202         }
2203
2204         fn create_network(node_count: usize) -> Vec<Node> {
2205                 let mut nodes = Vec::new();
2206                 let mut rng = thread_rng();
2207                 let secp_ctx = Secp256k1::new();
2208
2209                 for _ in 0..node_count {
2210                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_vbyte: 1 });
2211                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new());
2212                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
2213                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
2214                         let node_id = {
2215                                 let mut key_slice = [0; 32];
2216                                 rng.fill_bytes(&mut key_slice);
2217                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
2218                         };
2219                         let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone()).unwrap();
2220                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id).unwrap());
2221                         nodes.push(Node { feeest, chain_monitor, tx_broadcaster, chan_monitor, node_id, node, router });
2222                 }
2223
2224                 nodes
2225         }
2226
2227         #[test]
2228         fn fake_network_test() {
2229                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2230                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
2231                 let nodes = create_network(4);
2232
2233                 // Create some initial channels
2234                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2235                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2236                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2237
2238                 // Rebalance the network a bit by relaying one payment through all the channels...
2239                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2240                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2241                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2242                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2243
2244                 // Send some more payments
2245                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
2246                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
2247                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
2248
2249                 // Test failure packets
2250                 send_failed_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..]);
2251
2252                 // Add a new channel that skips 3
2253                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
2254
2255                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
2256                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
2257                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2258                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2259                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2260                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2261                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2262
2263                 // Do some rebalance loop payments, simultaneously
2264                 let mut hops = Vec::with_capacity(3);
2265                 hops.push(RouteHop {
2266                         pubkey: nodes[2].node.get_our_node_id(),
2267                         short_channel_id: chan_2.0.contents.short_channel_id,
2268                         fee_msat: 0,
2269                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
2270                 });
2271                 hops.push(RouteHop {
2272                         pubkey: nodes[3].node.get_our_node_id(),
2273                         short_channel_id: chan_3.0.contents.short_channel_id,
2274                         fee_msat: 0,
2275                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
2276                 });
2277                 hops.push(RouteHop {
2278                         pubkey: nodes[1].node.get_our_node_id(),
2279                         short_channel_id: chan_4.0.contents.short_channel_id,
2280                         fee_msat: 1000000,
2281                         cltv_expiry_delta: 142,
2282                 });
2283                 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
2284                 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
2285                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
2286
2287                 let mut hops = Vec::with_capacity(3);
2288                 hops.push(RouteHop {
2289                         pubkey: nodes[3].node.get_our_node_id(),
2290                         short_channel_id: chan_4.0.contents.short_channel_id,
2291                         fee_msat: 0,
2292                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
2293                 });
2294                 hops.push(RouteHop {
2295                         pubkey: nodes[2].node.get_our_node_id(),
2296                         short_channel_id: chan_3.0.contents.short_channel_id,
2297                         fee_msat: 0,
2298                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
2299                 });
2300                 hops.push(RouteHop {
2301                         pubkey: nodes[1].node.get_our_node_id(),
2302                         short_channel_id: chan_2.0.contents.short_channel_id,
2303                         fee_msat: 1000000,
2304                         cltv_expiry_delta: 142,
2305                 });
2306                 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
2307                 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
2308                 let payment_preimage_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).0;
2309
2310                 // Claim the rebalances...
2311                 claim_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_preimage_2);
2312                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
2313
2314                 // Add a duplicate new channel from 2 to 4
2315                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
2316
2317                 // Send some payments across both channels
2318                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2319                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2320                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
2321
2322                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
2323
2324                 //TODO: Test that routes work again here as we've been notified that the channel is full
2325
2326                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
2327                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
2328                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
2329
2330                 // Close down the channels...
2331                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
2332                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
2333                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
2334                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
2335                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
2336
2337                 // Check that we processed all pending events
2338                 for node in nodes {
2339                         assert_eq!(node.node.get_and_clear_pending_events().len(), 0);
2340                         assert_eq!(node.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2341                 }
2342         }
2343 }