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