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