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