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