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