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