aedb48d36a472685d669115487db3392c4ed1405
[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
8 use secp256k1::key::{SecretKey,PublicKey};
9 use secp256k1::{Secp256k1,Message};
10 use secp256k1::ecdh::SharedSecret;
11 use secp256k1;
12
13 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
14 use chain::transaction::OutPoint;
15 use ln::channel::{Channel, ChannelKeys};
16 use ln::channelmonitor::ManyChannelMonitor;
17 use ln::router::{Route,RouteHop};
18 use ln::msgs;
19 use ln::msgs::{HandleError,ChannelMessageHandler,MsgEncodable,MsgDecodable};
20 use util::{byte_utils, events, internal_traits, rng};
21 use util::sha2::Sha256;
22 use util::chacha20poly1305rfc::ChaCha20;
23 use util::logger::Logger;
24 use util::errors::APIError;
25
26 use crypto;
27 use crypto::mac::{Mac,MacResult};
28 use crypto::hmac::Hmac;
29 use crypto::digest::Digest;
30 use crypto::symmetriccipher::SynchronousStreamCipher;
31
32 use std::{ptr, mem};
33 use std::collections::HashMap;
34 use std::collections::hash_map;
35 use std::sync::{Mutex,MutexGuard,Arc};
36 use std::sync::atomic::{AtomicUsize, Ordering};
37 use std::time::{Instant,Duration};
38
39 mod channel_held_info {
40         use ln::msgs;
41
42         /// Stores the info we will need to send when we want to forward an HTLC onwards
43         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
44         pub struct PendingForwardHTLCInfo {
45                 pub(super) onion_packet: Option<msgs::OnionPacket>,
46                 pub(super) payment_hash: [u8; 32],
47                 pub(super) short_channel_id: u64,
48                 pub(super) prev_short_channel_id: u64,
49                 pub(super) amt_to_forward: u64,
50                 pub(super) outgoing_cltv_value: u32,
51         }
52
53         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
54         pub enum HTLCFailureMsg {
55                 Relay(msgs::UpdateFailHTLC),
56                 Malformed(msgs::UpdateFailMalformedHTLC),
57         }
58
59         /// Stores whether we can't forward an HTLC or relevant forwarding info
60         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
61         pub enum PendingHTLCStatus {
62                 Forward(PendingForwardHTLCInfo),
63                 Fail(HTLCFailureMsg),
64         }
65
66         #[cfg(feature = "fuzztarget")]
67         impl PendingHTLCStatus {
68                 pub fn dummy() -> Self {
69                         PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
70                                 onion_packet: None,
71                                 payment_hash: [0; 32],
72                                 short_channel_id: 0,
73                                 prev_short_channel_id: 0,
74                                 amt_to_forward: 0,
75                                 outgoing_cltv_value: 0,
76                         })
77                 }
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailReason {
82                 ErrorPacket {
83                         err: msgs::OnionErrorPacket,
84                 },
85                 Reason {
86                         failure_code: u16,
87                         data: Vec<u8>,
88                 }
89         }
90
91         #[cfg(feature = "fuzztarget")]
92         impl HTLCFailReason {
93                 pub fn dummy() -> Self {
94                         HTLCFailReason::Reason {
95                                 failure_code: 0, data: Vec::new(),
96                         }
97                 }
98         }
99 }
100 #[cfg(feature = "fuzztarget")]
101 pub use self::channel_held_info::*;
102 #[cfg(not(feature = "fuzztarget"))]
103 pub(crate) use self::channel_held_info::*;
104
105 enum PendingOutboundHTLC {
106         IntermediaryHopData {
107                 source_short_channel_id: u64,
108                 incoming_packet_shared_secret: SharedSecret,
109         },
110         OutboundRoute {
111                 route: Route,
112                 session_priv: SecretKey,
113         },
114         /// Used for channel rebalancing
115         CycledRoute {
116                 source_short_channel_id: u64,
117                 incoming_packet_shared_secret: SharedSecret,
118                 route: Route,
119                 session_priv: SecretKey,
120         }
121 }
122
123 struct MsgHandleErrInternal {
124         err: msgs::HandleError,
125         needs_channel_force_close: bool,
126 }
127 impl MsgHandleErrInternal {
128         #[inline]
129         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
130                 Self {
131                         err: HandleError {
132                                 err,
133                                 action: Some(msgs::ErrorAction::SendErrorMessage {
134                                         msg: msgs::ErrorMessage {
135                                                 channel_id,
136                                                 data: err.to_string()
137                                         },
138                                 }),
139                         },
140                         needs_channel_force_close: false,
141                 }
142         }
143         #[inline]
144         fn send_err_msg_close_chan(err: &'static str, channel_id: [u8; 32]) -> Self {
145                 Self {
146                         err: HandleError {
147                                 err,
148                                 action: Some(msgs::ErrorAction::SendErrorMessage {
149                                         msg: msgs::ErrorMessage {
150                                                 channel_id,
151                                                 data: err.to_string()
152                                         },
153                                 }),
154                         },
155                         needs_channel_force_close: true,
156                 }
157         }
158         #[inline]
159         fn from_maybe_close(err: msgs::HandleError) -> Self {
160                 Self { err, needs_channel_force_close: true }
161         }
162         #[inline]
163         fn from_no_close(err: msgs::HandleError) -> Self {
164                 Self { err, needs_channel_force_close: false }
165         }
166 }
167
168 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
169 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
170 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
171 /// probably increase this significantly.
172 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
173
174 struct ChannelHolder {
175         by_id: HashMap<[u8; 32], Channel>,
176         short_to_id: HashMap<u64, [u8; 32]>,
177         next_forward: Instant,
178         /// short channel id -> forward infos. Key of 0 means payments received
179         /// Note that while this is held in the same mutex as the channels themselves, no consistency
180         /// guarantees are made about there existing a channel with the short id here, nor the short
181         /// ids in the PendingForwardHTLCInfo!
182         forward_htlcs: HashMap<u64, Vec<PendingForwardHTLCInfo>>,
183         /// Note that while this is held in the same mutex as the channels themselves, no consistency
184         /// guarantees are made about the channels given here actually existing anymore by the time you
185         /// go to read them!
186         claimable_htlcs: HashMap<[u8; 32], PendingOutboundHTLC>,
187 }
188 struct MutChannelHolder<'a> {
189         by_id: &'a mut HashMap<[u8; 32], Channel>,
190         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
191         next_forward: &'a mut Instant,
192         forward_htlcs: &'a mut HashMap<u64, Vec<PendingForwardHTLCInfo>>,
193         claimable_htlcs: &'a mut HashMap<[u8; 32], PendingOutboundHTLC>,
194 }
195 impl ChannelHolder {
196         fn borrow_parts(&mut self) -> MutChannelHolder {
197                 MutChannelHolder {
198                         by_id: &mut self.by_id,
199                         short_to_id: &mut self.short_to_id,
200                         next_forward: &mut self.next_forward,
201                         forward_htlcs: &mut self.forward_htlcs,
202                         claimable_htlcs: &mut self.claimable_htlcs,
203                 }
204         }
205 }
206
207 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
208 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
209
210 /// Manager which keeps track of a number of channels and sends messages to the appropriate
211 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
212 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
213 /// to individual Channels.
214 pub struct ChannelManager {
215         genesis_hash: Sha256dHash,
216         fee_estimator: Arc<FeeEstimator>,
217         monitor: Arc<ManyChannelMonitor>,
218         chain_monitor: Arc<ChainWatchInterface>,
219         tx_broadcaster: Arc<BroadcasterInterface>,
220
221         announce_channels_publicly: bool,
222         fee_proportional_millionths: u32,
223         latest_block_height: AtomicUsize,
224         secp_ctx: Secp256k1<secp256k1::All>,
225
226         channel_state: Mutex<ChannelHolder>,
227         our_network_key: SecretKey,
228
229         pending_events: Mutex<Vec<events::Event>>,
230
231         logger: Arc<Logger>,
232 }
233
234 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
235
236 macro_rules! secp_call {
237         ( $res: expr, $err: expr ) => {
238                 match $res {
239                         Ok(key) => key,
240                         Err(_) => return Err($err),
241                 }
242         };
243 }
244
245 struct OnionKeys {
246         #[cfg(test)]
247         shared_secret: SharedSecret,
248         #[cfg(test)]
249         blinding_factor: [u8; 32],
250         ephemeral_pubkey: PublicKey,
251         rho: [u8; 32],
252         mu: [u8; 32],
253 }
254
255 pub struct ChannelDetails {
256         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
257         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
258         /// Note that this means this value is *not* persistent - it can change once during the
259         /// lifetime of the channel.
260         pub channel_id: [u8; 32],
261         /// The position of the funding transaction in the chain. None if the funding transaction has
262         /// not yet been confirmed and the channel fully opened.
263         pub short_channel_id: Option<u64>,
264         pub remote_network_id: PublicKey,
265         pub channel_value_satoshis: u64,
266         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
267         pub user_id: u64,
268 }
269
270 impl ChannelManager {
271         /// Constructs a new ChannelManager to hold several channels and route between them. This is
272         /// the main "logic hub" for all channel-related actions, and implements ChannelMessageHandler.
273         /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
274         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
275         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
276         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>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
277                 let secp_ctx = Secp256k1::new();
278
279                 let res = Arc::new(ChannelManager {
280                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
281                         fee_estimator: feeest.clone(),
282                         monitor: monitor.clone(),
283                         chain_monitor,
284                         tx_broadcaster,
285
286                         announce_channels_publicly,
287                         fee_proportional_millionths,
288                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
289                         secp_ctx,
290
291                         channel_state: Mutex::new(ChannelHolder{
292                                 by_id: HashMap::new(),
293                                 short_to_id: HashMap::new(),
294                                 next_forward: Instant::now(),
295                                 forward_htlcs: HashMap::new(),
296                                 claimable_htlcs: HashMap::new(),
297                         }),
298                         our_network_key,
299
300                         pending_events: Mutex::new(Vec::new()),
301
302                         logger,
303                 });
304                 let weak_res = Arc::downgrade(&res);
305                 res.chain_monitor.register_listener(weak_res);
306                 Ok(res)
307         }
308
309         /// Creates a new outbound channel to the given remote node and with the given value.
310         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
311         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
312         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
313         /// may wish to avoid using 0 for user_id here.
314         /// If successful, will generate a SendOpenChannel event, so you should probably poll
315         /// PeerManager::process_events afterwards.
316         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
317         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
318                 let chan_keys = if cfg!(feature = "fuzztarget") {
319                         ChannelKeys {
320                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
321                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
322                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
323                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
324                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
325                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
326                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
327                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
328                         }
329                 } else {
330                         let mut key_seed = [0u8; 32];
331                         rng::fill_bytes(&mut key_seed);
332                         match ChannelKeys::new_from_seed(&key_seed) {
333                                 Ok(key) => key,
334                                 Err(_) => panic!("RNG is busted!")
335                         }
336                 };
337
338                 let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
339                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator)?;
340                 let mut channel_state = self.channel_state.lock().unwrap();
341                 match channel_state.by_id.insert(channel.channel_id(), channel) {
342                         Some(_) => panic!("RNG is bad???"),
343                         None => {}
344                 }
345
346                 let mut events = self.pending_events.lock().unwrap();
347                 events.push(events::Event::SendOpenChannel {
348                         node_id: their_network_key,
349                         msg: res,
350                 });
351                 Ok(())
352         }
353
354         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
355         /// more information.
356         pub fn list_channels(&self) -> Vec<ChannelDetails> {
357                 let channel_state = self.channel_state.lock().unwrap();
358                 let mut res = Vec::with_capacity(channel_state.by_id.len());
359                 for (channel_id, channel) in channel_state.by_id.iter() {
360                         res.push(ChannelDetails {
361                                 channel_id: (*channel_id).clone(),
362                                 short_channel_id: channel.get_short_channel_id(),
363                                 remote_network_id: channel.get_their_node_id(),
364                                 channel_value_satoshis: channel.get_value_satoshis(),
365                                 user_id: channel.get_user_id(),
366                         });
367                 }
368                 res
369         }
370
371         /// Gets the list of usable channels, in random order. Useful as an argument to
372         /// Router::get_route to ensure non-announced channels are used.
373         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
374                 let channel_state = self.channel_state.lock().unwrap();
375                 let mut res = Vec::with_capacity(channel_state.by_id.len());
376                 for (channel_id, channel) in channel_state.by_id.iter() {
377                         if channel.is_usable() {
378                                 res.push(ChannelDetails {
379                                         channel_id: (*channel_id).clone(),
380                                         short_channel_id: channel.get_short_channel_id(),
381                                         remote_network_id: channel.get_their_node_id(),
382                                         channel_value_satoshis: channel.get_value_satoshis(),
383                                         user_id: channel.get_user_id(),
384                                 });
385                         }
386                 }
387                 res
388         }
389
390         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
391         /// will be accepted on the given channel, and after additional timeout/the closing of all
392         /// pending HTLCs, the channel will be closed on chain.
393         /// May generate a SendShutdown event on success, which should be relayed.
394         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), HandleError> {
395                 let (res, node_id, chan_option) = {
396                         let mut channel_state_lock = self.channel_state.lock().unwrap();
397                         let channel_state = channel_state_lock.borrow_parts();
398                         match channel_state.by_id.entry(channel_id.clone()) {
399                                 hash_map::Entry::Occupied(mut chan_entry) => {
400                                         let res = chan_entry.get_mut().get_shutdown()?;
401                                         if chan_entry.get().is_shutdown() {
402                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
403                                                         channel_state.short_to_id.remove(&short_id);
404                                                 }
405                                                 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
406                                         } else { (res, chan_entry.get().get_their_node_id(), None) }
407                                 },
408                                 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "No such channel", action: None})
409                         }
410                 };
411                 for payment_hash in res.1 {
412                         // unknown_next_peer...I dunno who that is anymore....
413                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
414                 }
415                 let chan_update = if let Some(chan) = chan_option {
416                         if let Ok(update) = self.get_channel_update(&chan) {
417                                 Some(update)
418                         } else { None }
419                 } else { None };
420
421                 let mut events = self.pending_events.lock().unwrap();
422                 if let Some(update) = chan_update {
423                         events.push(events::Event::BroadcastChannelUpdate {
424                                 msg: update
425                         });
426                 }
427                 events.push(events::Event::SendShutdown {
428                         node_id,
429                         msg: res.0
430                 });
431
432                 Ok(())
433         }
434
435         #[inline]
436         fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<[u8; 32]>)) {
437                 let (local_txn, failed_htlcs) = shutdown_res;
438                 for payment_hash in failed_htlcs {
439                         // unknown_next_peer...I dunno who that is anymore....
440                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
441                 }
442                 for tx in local_txn {
443                         self.tx_broadcaster.broadcast_transaction(&tx);
444                 }
445                 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
446                 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
447                 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
448                 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
449                 //timeouts are hit and our claims confirm).
450                 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
451                 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
452         }
453
454         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
455         /// the chain and rejecting new HTLCs on the given channel.
456         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
457                 let mut chan = {
458                         let mut channel_state_lock = self.channel_state.lock().unwrap();
459                         let channel_state = channel_state_lock.borrow_parts();
460                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
461                                 if let Some(short_id) = chan.get_short_channel_id() {
462                                         channel_state.short_to_id.remove(&short_id);
463                                 }
464                                 chan
465                         } else {
466                                 return;
467                         }
468                 };
469                 self.finish_force_close_channel(chan.force_shutdown());
470                 let mut events = self.pending_events.lock().unwrap();
471                 if let Ok(update) = self.get_channel_update(&chan) {
472                         events.push(events::Event::BroadcastChannelUpdate {
473                                 msg: update
474                         });
475                 }
476         }
477
478         /// Force close all channels, immediately broadcasting the latest local commitment transaction
479         /// for each to the chain and rejecting new HTLCs on each.
480         pub fn force_close_all_channels(&self) {
481                 for chan in self.list_channels() {
482                         self.force_close_channel(&chan.channel_id);
483                 }
484         }
485
486         #[inline]
487         fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
488                 ({
489                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
490                         hmac.input(&shared_secret[..]);
491                         let mut res = [0; 32];
492                         hmac.raw_result(&mut res);
493                         res
494                 },
495                 {
496                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
497                         hmac.input(&shared_secret[..]);
498                         let mut res = [0; 32];
499                         hmac.raw_result(&mut res);
500                         res
501                 })
502         }
503
504         #[inline]
505         fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
506                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
507                 hmac.input(&shared_secret[..]);
508                 let mut res = [0; 32];
509                 hmac.raw_result(&mut res);
510                 res
511         }
512
513         #[inline]
514         fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
515                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
516                 hmac.input(&shared_secret[..]);
517                 let mut res = [0; 32];
518                 hmac.raw_result(&mut res);
519                 res
520         }
521
522         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
523         #[inline]
524         fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
525                 let mut blinded_priv = session_priv.clone();
526                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
527
528                 for hop in route.hops.iter() {
529                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
530
531                         let mut sha = Sha256::new();
532                         sha.input(&blinded_pub.serialize()[..]);
533                         sha.input(&shared_secret[..]);
534                         let mut blinding_factor = [0u8; 32];
535                         sha.result(&mut blinding_factor);
536
537                         let ephemeral_pubkey = blinded_pub;
538
539                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
540                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
541
542                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
543                 }
544
545                 Ok(())
546         }
547
548         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
549         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
550                 let mut res = Vec::with_capacity(route.hops.len());
551
552                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
553                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
554
555                         res.push(OnionKeys {
556                                 #[cfg(test)]
557                                 shared_secret,
558                                 #[cfg(test)]
559                                 blinding_factor: _blinding_factor,
560                                 ephemeral_pubkey,
561                                 rho,
562                                 mu,
563                         });
564                 })?;
565
566                 Ok(res)
567         }
568
569         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
570         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), HandleError> {
571                 let mut cur_value_msat = 0u64;
572                 let mut cur_cltv = starting_htlc_offset;
573                 let mut last_short_channel_id = 0;
574                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
575                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
576                 unsafe { res.set_len(route.hops.len()); }
577
578                 for (idx, hop) in route.hops.iter().enumerate().rev() {
579                         // First hop gets special values so that it can check, on receipt, that everything is
580                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
581                         // the intended recipient).
582                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
583                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
584                         res[idx] = msgs::OnionHopData {
585                                 realm: 0,
586                                 data: msgs::OnionRealm0HopData {
587                                         short_channel_id: last_short_channel_id,
588                                         amt_to_forward: value_msat,
589                                         outgoing_cltv_value: cltv,
590                                 },
591                                 hmac: [0; 32],
592                         };
593                         cur_value_msat += hop.fee_msat;
594                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
595                                 return Err(HandleError{err: "Channel fees overflowed?!", action: None});
596                         }
597                         cur_cltv += hop.cltv_expiry_delta as u32;
598                         if cur_cltv >= 500000000 {
599                                 return Err(HandleError{err: "Channel CLTV overflowed?!", action: None});
600                         }
601                         last_short_channel_id = hop.short_channel_id;
602                 }
603                 Ok((res, cur_value_msat, cur_cltv))
604         }
605
606         #[inline]
607         fn shift_arr_right(arr: &mut [u8; 20*65]) {
608                 unsafe {
609                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
610                 }
611                 for i in 0..65 {
612                         arr[i] = 0;
613                 }
614         }
615
616         #[inline]
617         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
618                 assert_eq!(dst.len(), src.len());
619
620                 for i in 0..dst.len() {
621                         dst[i] ^= src[i];
622                 }
623         }
624
625         const ZERO:[u8; 21*65] = [0; 21*65];
626         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> Result<msgs::OnionPacket, HandleError> {
627                 let mut buf = Vec::with_capacity(21*65);
628                 buf.resize(21*65, 0);
629
630                 let filler = {
631                         let iters = payloads.len() - 1;
632                         let end_len = iters * 65;
633                         let mut res = Vec::with_capacity(end_len);
634                         res.resize(end_len, 0);
635
636                         for (i, keys) in onion_keys.iter().enumerate() {
637                                 if i == payloads.len() - 1 { continue; }
638                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
639                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
640                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
641                         }
642                         res
643                 };
644
645                 let mut packet_data = [0; 20*65];
646                 let mut hmac_res = [0; 32];
647
648                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
649                         ChannelManager::shift_arr_right(&mut packet_data);
650                         payload.hmac = hmac_res;
651                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
652
653                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
654                         chacha.process(&packet_data, &mut buf[0..20*65]);
655                         packet_data[..].copy_from_slice(&buf[0..20*65]);
656
657                         if i == 0 {
658                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
659                         }
660
661                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
662                         hmac.input(&packet_data);
663                         hmac.input(&associated_data[..]);
664                         hmac.raw_result(&mut hmac_res);
665                 }
666
667                 Ok(msgs::OnionPacket{
668                         version: 0,
669                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
670                         hop_data: packet_data,
671                         hmac: hmac_res,
672                 })
673         }
674
675         /// Encrypts a failure packet. raw_packet can either be a
676         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
677         fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
678                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
679
680                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
681                 packet_crypted.resize(raw_packet.len(), 0);
682                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
683                 chacha.process(&raw_packet, &mut packet_crypted[..]);
684                 msgs::OnionErrorPacket {
685                         data: packet_crypted,
686                 }
687         }
688
689         fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
690                 assert!(failure_data.len() <= 256 - 2);
691
692                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
693
694                 let failuremsg = {
695                         let mut res = Vec::with_capacity(2 + failure_data.len());
696                         res.push(((failure_type >> 8) & 0xff) as u8);
697                         res.push(((failure_type >> 0) & 0xff) as u8);
698                         res.extend_from_slice(&failure_data[..]);
699                         res
700                 };
701                 let pad = {
702                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
703                         res.resize(256 - 2 - failure_data.len(), 0);
704                         res
705                 };
706                 let mut packet = msgs::DecodedOnionErrorPacket {
707                         hmac: [0; 32],
708                         failuremsg: failuremsg,
709                         pad: pad,
710                 };
711
712                 let mut hmac = Hmac::new(Sha256::new(), &um);
713                 hmac.input(&packet.encode()[32..]);
714                 hmac.raw_result(&mut packet.hmac);
715
716                 packet
717         }
718
719         #[inline]
720         fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
721                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
722                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
723         }
724
725         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, Option<SharedSecret>, MutexGuard<ChannelHolder>) {
726                 macro_rules! get_onion_hash {
727                         () => {
728                                 {
729                                         let mut sha = Sha256::new();
730                                         sha.input(&msg.onion_routing_packet.hop_data);
731                                         let mut onion_hash = [0; 32];
732                                         sha.result(&mut onion_hash);
733                                         onion_hash
734                                 }
735                         }
736                 }
737
738                 if let Err(_) = msg.onion_routing_packet.public_key {
739                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
740                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
741                                 channel_id: msg.channel_id,
742                                 htlc_id: msg.htlc_id,
743                                 sha256_of_onion: get_onion_hash!(),
744                                 failure_code: 0x8000 | 0x4000 | 6,
745                         })), None, self.channel_state.lock().unwrap());
746                 }
747
748                 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
749                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
750
751                 let mut channel_state = None;
752                 macro_rules! return_err {
753                         ($msg: expr, $err_code: expr, $data: expr) => {
754                                 {
755                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
756                                         if channel_state.is_none() {
757                                                 channel_state = Some(self.channel_state.lock().unwrap());
758                                         }
759                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
760                                                 channel_id: msg.channel_id,
761                                                 htlc_id: msg.htlc_id,
762                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
763                                         })), Some(shared_secret), channel_state.unwrap());
764                                 }
765                         }
766                 }
767
768                 if msg.onion_routing_packet.version != 0 {
769                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
770                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
771                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
772                         //receiving node would have to brute force to figure out which version was put in the
773                         //packet by the node that send us the message, in the case of hashing the hop_data, the
774                         //node knows the HMAC matched, so they already know what is there...
775                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
776                 }
777
778                 let mut hmac = Hmac::new(Sha256::new(), &mu);
779                 hmac.input(&msg.onion_routing_packet.hop_data);
780                 hmac.input(&msg.payment_hash);
781                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
782                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
783                 }
784
785                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
786                 let next_hop_data = {
787                         let mut decoded = [0; 65];
788                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
789                         match msgs::OnionHopData::decode(&decoded[..]) {
790                                 Err(err) => {
791                                         let error_code = match err {
792                                                 msgs::DecodeError::UnknownRealmByte => 0x4000 | 1,
793                                                 _ => 0x2000 | 2, // Should never happen
794                                         };
795                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
796                                 },
797                                 Ok(msg) => msg
798                         }
799                 };
800
801                 //TODO: Check that msg.cltv_expiry is within acceptable bounds!
802
803                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
804                                 // OUR PAYMENT!
805                                 if next_hop_data.data.amt_to_forward != msg.amount_msat {
806                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
807                                 }
808                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
809                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
810                                 }
811
812                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
813                                 // message, however that would leak that we are the recipient of this payment, so
814                                 // instead we stay symmetric with the forwarding case, only responding (after a
815                                 // delay) once they've send us a commitment_signed!
816
817                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
818                                         onion_packet: None,
819                                         payment_hash: msg.payment_hash.clone(),
820                                         short_channel_id: 0,
821                                         prev_short_channel_id: 0,
822                                         amt_to_forward: next_hop_data.data.amt_to_forward,
823                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
824                                 })
825                         } else {
826                                 let mut new_packet_data = [0; 20*65];
827                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
828                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
829
830                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
831
832                                 let blinding_factor = {
833                                         let mut sha = Sha256::new();
834                                         sha.input(&new_pubkey.serialize()[..]);
835                                         sha.input(&shared_secret[..]);
836                                         let mut res = [0u8; 32];
837                                         sha.result(&mut res);
838                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
839                                                 Err(_) => {
840                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
841                                                 },
842                                                 Ok(key) => key
843                                         }
844                                 };
845
846                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
847                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
848                                 }
849
850                                 let outgoing_packet = msgs::OnionPacket {
851                                         version: 0,
852                                         public_key: Ok(new_pubkey),
853                                         hop_data: new_packet_data,
854                                         hmac: next_hop_data.hmac.clone(),
855                                 };
856
857                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
858                                         onion_packet: Some(outgoing_packet),
859                                         payment_hash: msg.payment_hash.clone(),
860                                         short_channel_id: next_hop_data.data.short_channel_id,
861                                         prev_short_channel_id: 0,
862                                         amt_to_forward: next_hop_data.data.amt_to_forward,
863                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
864                                 })
865                         };
866
867                 channel_state = Some(self.channel_state.lock().unwrap());
868                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
869                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
870                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
871                                 let forwarding_id = match id_option {
872                                         None => {
873                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
874                                         },
875                                         Some(id) => id.clone(),
876                                 };
877                                 if let Some((err, code, chan_update)) = {
878                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
879                                         if !chan.is_live() {
880                                                 Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, self.get_channel_update(chan).unwrap()))
881                                         } else {
882                                                 let fee = amt_to_forward.checked_mul(self.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
883                                                 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward {
884                                                         Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, self.get_channel_update(chan).unwrap()))
885                                                 } else {
886                                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 {
887                                                                 Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, self.get_channel_update(chan).unwrap()))
888                                                         } else {
889                                                                 None
890                                                         }
891                                                 }
892                                         }
893                                 } {
894                                         return_err!(err, code, &chan_update.encode_with_len()[..]);
895                                 }
896                         }
897                 }
898
899                 (pending_forward_info, Some(shared_secret), channel_state.unwrap())
900         }
901
902         /// only fails if the channel does not yet have an assigned short_id
903         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
904                 let short_channel_id = match chan.get_short_channel_id() {
905                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
906                         Some(id) => id,
907                 };
908
909                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
910
911                 let unsigned = msgs::UnsignedChannelUpdate {
912                         chain_hash: self.genesis_hash,
913                         short_channel_id: short_channel_id,
914                         timestamp: chan.get_channel_update_count(),
915                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
916                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
917                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
918                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
919                         fee_proportional_millionths: self.fee_proportional_millionths,
920                         excess_data: Vec::new(),
921                 };
922
923                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
924                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key); //TODO Can we unwrap here?
925
926                 Ok(msgs::ChannelUpdate {
927                         signature: sig,
928                         contents: unsigned
929                 })
930         }
931
932         /// Sends a payment along a given route.
933         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
934         /// fields for more info.
935         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
936         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
937         /// next hop knows the preimage to payment_hash they can claim an additional amount as
938         /// specified in the last hop in the route! Thus, you should probably do your own
939         /// payment_preimage tracking (which you should already be doing as they represent "proof of
940         /// payment") and prevent double-sends yourself.
941         /// See-also docs on Channel::send_htlc_and_commit.
942         /// May generate a SendHTLCs event on success, which should be relayed.
943         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), HandleError> {
944                 if route.hops.len() < 1 || route.hops.len() > 20 {
945                         return Err(HandleError{err: "Route didn't go anywhere/had bogus size", action: None});
946                 }
947                 let our_node_id = self.get_our_node_id();
948                 for (idx, hop) in route.hops.iter().enumerate() {
949                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
950                                 return Err(HandleError{err: "Route went through us but wasn't a simple rebalance loop to us", action: None});
951                         }
952                 }
953
954                 let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
955                         let mut session_key = [0; 32];
956                         rng::fill_bytes(&mut session_key);
957                         session_key
958                 }).expect("RNG is bad!");
959
960                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
961
962                 //TODO: This should return something other than HandleError, that's really intended for
963                 //p2p-returns only.
964                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
965                                 HandleError{err: "Pubkey along hop was maliciously selected", action: Some(msgs::ErrorAction::IgnoreError)});
966                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
967                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash)?;
968
969                 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
970                         let mut channel_state_lock = self.channel_state.lock().unwrap();
971                         let channel_state = channel_state_lock.borrow_parts();
972
973                         let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
974                                 None => return Err(HandleError{err: "No channel available with first hop!", action: None}),
975                                 Some(id) => id.clone()
976                         };
977
978                         let claimable_htlc_entry = channel_state.claimable_htlcs.entry(payment_hash.clone());
979                         if let hash_map::Entry::Occupied(_) = claimable_htlc_entry {
980                                 return Err(HandleError{err: "Already had pending HTLC with the same payment_hash", action: None});
981                         }
982
983                         let res = {
984                                 let chan = channel_state.by_id.get_mut(&id).unwrap();
985                                 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
986                                         return Err(HandleError{err: "Node ID mismatch on first hop!", action: None});
987                                 }
988                                 chan.send_htlc_and_commit(htlc_msat, payment_hash, htlc_cltv, onion_packet)?
989                         };
990
991                         let first_hop_node_id = route.hops.first().unwrap().pubkey;
992
993                         claimable_htlc_entry.or_insert(PendingOutboundHTLC::OutboundRoute {
994                                 route,
995                                 session_priv,
996                         });
997
998                         match res {
999                                 Some(msgs) => (first_hop_node_id, msgs),
1000                                 None => return Ok(()),
1001                         }
1002                 };
1003
1004                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1005                         unimplemented!(); // maybe remove from claimable_htlcs?
1006                 }
1007
1008                 let mut events = self.pending_events.lock().unwrap();
1009                 events.push(events::Event::UpdateHTLCs {
1010                         node_id: first_hop_node_id,
1011                         updates: msgs::CommitmentUpdate {
1012                                 update_add_htlcs: vec![update_add],
1013                                 update_fulfill_htlcs: Vec::new(),
1014                                 update_fail_htlcs: Vec::new(),
1015                                 update_fail_malformed_htlcs: Vec::new(),
1016                                 commitment_signed,
1017                         },
1018                 });
1019                 Ok(())
1020         }
1021
1022         /// Call this upon creation of a funding transaction for the given channel.
1023         /// Panics if a funding transaction has already been provided for this channel.
1024         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1025         /// be trivially prevented by using unique funding transaction keys per-channel).
1026         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1027
1028                 macro_rules! add_pending_event {
1029                         ($event: expr) => {
1030                                 {
1031                                         let mut pending_events = self.pending_events.lock().unwrap();
1032                                         pending_events.push($event);
1033                                 }
1034                         }
1035                 }
1036
1037                 let (chan, msg, chan_monitor) = {
1038                         let mut channel_state = self.channel_state.lock().unwrap();
1039                         match channel_state.by_id.remove(temporary_channel_id) {
1040                                 Some(mut chan) => {
1041                                         match chan.get_outbound_funding_created(funding_txo) {
1042                                                 Ok(funding_msg) => {
1043                                                         (chan, funding_msg.0, funding_msg.1)
1044                                                 },
1045                                                 Err(e) => {
1046                                                         log_error!(self, "Got bad signatures: {}!", e.err);
1047                                                         mem::drop(channel_state);
1048                                                         add_pending_event!(events::Event::HandleError {
1049                                                                 node_id: chan.get_their_node_id(),
1050                                                                 action: e.action,
1051                                                         });
1052                                                         return;
1053                                                 },
1054                                         }
1055                                 },
1056                                 None => return
1057                         }
1058                 }; // Release channel lock for install_watch_outpoint call,
1059                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1060                         unimplemented!(); // maybe remove from claimable_htlcs?
1061                 }
1062                 add_pending_event!(events::Event::SendFundingCreated {
1063                         node_id: chan.get_their_node_id(),
1064                         msg: msg,
1065                 });
1066
1067                 let mut channel_state = self.channel_state.lock().unwrap();
1068                 match channel_state.by_id.entry(chan.channel_id()) {
1069                         hash_map::Entry::Occupied(_) => {
1070                                 panic!("Generated duplicate funding txid?");
1071                         },
1072                         hash_map::Entry::Vacant(e) => {
1073                                 e.insert(chan);
1074                         }
1075                 }
1076         }
1077
1078         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1079                 if !chan.should_announce() { return None }
1080
1081                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1082                         Ok(res) => res,
1083                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1084                 };
1085                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1086                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1087
1088                 Some(msgs::AnnouncementSignatures {
1089                         channel_id: chan.channel_id(),
1090                         short_channel_id: chan.get_short_channel_id().unwrap(),
1091                         node_signature: our_node_sig,
1092                         bitcoin_signature: our_bitcoin_sig,
1093                 })
1094         }
1095
1096         /// Processes HTLCs which are pending waiting on random forward delay.
1097         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1098         /// Will likely generate further events.
1099         pub fn process_pending_htlc_forwards(&self) {
1100                 let mut new_events = Vec::new();
1101                 let mut failed_forwards = Vec::new();
1102                 {
1103                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1104                         let channel_state = channel_state_lock.borrow_parts();
1105
1106                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1107                                 return;
1108                         }
1109
1110                         for (short_chan_id, pending_forwards) in channel_state.forward_htlcs.drain() {
1111                                 if short_chan_id != 0 {
1112                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1113                                                 Some(chan_id) => chan_id.clone(),
1114                                                 None => {
1115                                                         failed_forwards.reserve(pending_forwards.len());
1116                                                         for forward_info in pending_forwards {
1117                                                                 failed_forwards.push((forward_info.payment_hash, 0x4000 | 10, None));
1118                                                         }
1119                                                         continue;
1120                                                 }
1121                                         };
1122                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1123
1124                                         let mut add_htlc_msgs = Vec::new();
1125                                         for forward_info in pending_forwards {
1126                                                 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, forward_info.onion_packet.unwrap()) {
1127                                                         Err(_e) => {
1128                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1129                                                                 failed_forwards.push((forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1130                                                                 continue;
1131                                                         },
1132                                                         Ok(update_add) => {
1133                                                                 match update_add {
1134                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1135                                                                         None => {
1136                                                                                 // Nothing to do here...we're waiting on a remote
1137                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1138                                                                                 // will automatically handle building the update_add_htlc and
1139                                                                                 // commitment_signed messages when we can.
1140                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1141                                                                                 // as we don't really want others relying on us relaying through
1142                                                                                 // this channel currently :/.
1143                                                                         }
1144                                                                 }
1145                                                         }
1146                                                 }
1147                                         }
1148
1149                                         if !add_htlc_msgs.is_empty() {
1150                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1151                                                         Ok(res) => res,
1152                                                         Err(e) => {
1153                                                                 if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1154                                                                 } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1155                                                                 } else {
1156                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1157                                                                 }
1158                                                                 //TODO: Handle...this is bad!
1159                                                                 continue;
1160                                                         },
1161                                                 };
1162                                                 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1163                                                         node_id: forward_chan.get_their_node_id(),
1164                                                         updates: msgs::CommitmentUpdate {
1165                                                                 update_add_htlcs: add_htlc_msgs,
1166                                                                 update_fulfill_htlcs: Vec::new(),
1167                                                                 update_fail_htlcs: Vec::new(),
1168                                                                 update_fail_malformed_htlcs: Vec::new(),
1169                                                                 commitment_signed: commitment_msg,
1170                                                         },
1171                                                 }));
1172                                         }
1173                                 } else {
1174                                         for forward_info in pending_forwards {
1175                                                 new_events.push((None, events::Event::PaymentReceived {
1176                                                         payment_hash: forward_info.payment_hash,
1177                                                         amt: forward_info.amt_to_forward,
1178                                                 }));
1179                                         }
1180                                 }
1181                         }
1182                 }
1183
1184                 for failed_forward in failed_forwards.drain(..) {
1185                         match failed_forward.2 {
1186                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: Vec::new() }),
1187                                 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failed_forward.0, HTLCFailReason::Reason { failure_code: failed_forward.1, data: chan_update.encode_with_len() }),
1188                         };
1189                 }
1190
1191                 if new_events.is_empty() { return }
1192
1193                 new_events.retain(|event| {
1194                         if let &Some(ref monitor) = &event.0 {
1195                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1196                                         unimplemented!();// but def dont push the event...
1197                                 }
1198                         }
1199                         true
1200                 });
1201
1202                 let mut events = self.pending_events.lock().unwrap();
1203                 events.reserve(new_events.len());
1204                 for event in new_events.drain(..) {
1205                         events.push(event.1);
1206                 }
1207         }
1208
1209         /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1210         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1211                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() })
1212         }
1213
1214         /// Fails an HTLC backwards to the sender of it to us.
1215         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1216         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1217         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1218         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1219         /// still-available channels.
1220         fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, payment_hash: &[u8; 32], onion_error: HTLCFailReason) -> bool {
1221                 let mut pending_htlc = {
1222                         match channel_state.claimable_htlcs.remove(payment_hash) {
1223                                 Some(pending_htlc) => pending_htlc,
1224                                 None => return false,
1225                         }
1226                 };
1227
1228                 match pending_htlc {
1229                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, route, session_priv } => {
1230                                 channel_state.claimable_htlcs.insert(payment_hash.clone(), PendingOutboundHTLC::OutboundRoute {
1231                                         route,
1232                                         session_priv,
1233                                 });
1234                                 pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
1235                         },
1236                         _ => {}
1237                 }
1238
1239                 match pending_htlc {
1240                         PendingOutboundHTLC::CycledRoute { .. } => unreachable!(),
1241                         PendingOutboundHTLC::OutboundRoute { .. } => {
1242                                 mem::drop(channel_state);
1243
1244                                 let mut pending_events = self.pending_events.lock().unwrap();
1245                                 pending_events.push(events::Event::PaymentFailed {
1246                                         payment_hash: payment_hash.clone()
1247                                 });
1248                                 false
1249                         },
1250                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret } => {
1251                                 let err_packet = match onion_error {
1252                                         HTLCFailReason::Reason { failure_code, data } => {
1253                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1254                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1255                                         },
1256                                         HTLCFailReason::ErrorPacket { err } => {
1257                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1258                                         }
1259                                 };
1260
1261                                 let (node_id, fail_msgs) = {
1262                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
1263                                                 Some(chan_id) => chan_id.clone(),
1264                                                 None => return false
1265                                         };
1266
1267                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1268                                         match chan.get_update_fail_htlc_and_commit(payment_hash, err_packet) {
1269                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1270                                                 Err(_e) => {
1271                                                         //TODO: Do something with e?
1272                                                         return false;
1273                                                 },
1274                                         }
1275                                 };
1276
1277                                 match fail_msgs {
1278                                         Some((msg, commitment_msg, chan_monitor)) => {
1279                                                 mem::drop(channel_state);
1280
1281                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1282                                                         unimplemented!();// but def dont push the event...
1283                                                 }
1284
1285                                                 let mut pending_events = self.pending_events.lock().unwrap();
1286                                                 pending_events.push(events::Event::UpdateHTLCs {
1287                                                         node_id,
1288                                                         updates: msgs::CommitmentUpdate {
1289                                                                 update_add_htlcs: Vec::new(),
1290                                                                 update_fulfill_htlcs: Vec::new(),
1291                                                                 update_fail_htlcs: vec![msg],
1292                                                                 update_fail_malformed_htlcs: Vec::new(),
1293                                                                 commitment_signed: commitment_msg,
1294                                                         },
1295                                                 });
1296                                         },
1297                                         None => {},
1298                                 }
1299
1300                                 true
1301                         },
1302                 }
1303         }
1304
1305         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1306         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1307         /// should probably kick the net layer to go send messages if this returns true!
1308         /// May panic if called except in response to a PaymentReceived event.
1309         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1310                 self.claim_funds_internal(payment_preimage, true)
1311         }
1312         fn claim_funds_internal(&self, payment_preimage: [u8; 32], from_user: bool) -> bool {
1313                 let mut sha = Sha256::new();
1314                 sha.input(&payment_preimage);
1315                 let mut payment_hash = [0; 32];
1316                 sha.result(&mut payment_hash);
1317
1318                 let mut channel_state = self.channel_state.lock().unwrap();
1319                 let mut pending_htlc = {
1320                         match channel_state.claimable_htlcs.remove(&payment_hash) {
1321                                 Some(pending_htlc) => pending_htlc,
1322                                 None => return false,
1323                         }
1324                 };
1325
1326                 match pending_htlc {
1327                         PendingOutboundHTLC::CycledRoute { source_short_channel_id, incoming_packet_shared_secret, route, session_priv } => {
1328                                 if from_user { // This was the end hop back to us
1329                                         pending_htlc = PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret };
1330                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::OutboundRoute { route, session_priv });
1331                                 } else { // This came from the first upstream node
1332                                         // Bank error in our favor! Maybe we should tell the user this somehow???
1333                                         pending_htlc = PendingOutboundHTLC::OutboundRoute { route, session_priv };
1334                                         channel_state.claimable_htlcs.insert(payment_hash, PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, incoming_packet_shared_secret });
1335                                 }
1336                         },
1337                         _ => {},
1338                 }
1339
1340                 match pending_htlc {
1341                         PendingOutboundHTLC::CycledRoute { .. } => unreachable!(),
1342                         PendingOutboundHTLC::OutboundRoute { .. } => {
1343                                 if from_user {
1344                                         panic!("Called claim_funds with a preimage for an outgoing payment. There is nothing we can do with this, and something is seriously wrong if you knew this...");
1345                                 }
1346                                 mem::drop(channel_state);
1347                                 let mut pending_events = self.pending_events.lock().unwrap();
1348                                 pending_events.push(events::Event::PaymentSent {
1349                                         payment_preimage
1350                                 });
1351                                 false
1352                         },
1353                         PendingOutboundHTLC::IntermediaryHopData { source_short_channel_id, .. } => {
1354                                 let (node_id, fulfill_msgs) = {
1355                                         let chan_id = match channel_state.short_to_id.get(&source_short_channel_id) {
1356                                                 Some(chan_id) => chan_id.clone(),
1357                                                 None => {
1358                                                         // TODO: There is probably a channel manager somewhere that needs to
1359                                                         // learn the preimage as the channel already hit the chain and that's
1360                                                         // why its missing.
1361                                                         return false
1362                                                 }
1363                                         };
1364
1365                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1366                                         match chan.get_update_fulfill_htlc_and_commit(payment_preimage) {
1367                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1368                                                 Err(_e) => {
1369                                                         // TODO: There is probably a channel manager somewhere that needs to
1370                                                         // learn the preimage as the channel may be about to hit the chain.
1371                                                         //TODO: Do something with e?
1372                                                         return false;
1373                                                 },
1374                                         }
1375                                 };
1376
1377                                 mem::drop(channel_state);
1378                                 if let Some(chan_monitor) = fulfill_msgs.1 {
1379                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1380                                                 unimplemented!();// but def dont push the event...
1381                                         }
1382                                 }
1383
1384                                 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1385                                         let mut pending_events = self.pending_events.lock().unwrap();
1386                                         pending_events.push(events::Event::UpdateHTLCs {
1387                                                 node_id: node_id,
1388                                                 updates: msgs::CommitmentUpdate {
1389                                                         update_add_htlcs: Vec::new(),
1390                                                         update_fulfill_htlcs: vec![msg],
1391                                                         update_fail_htlcs: Vec::new(),
1392                                                         update_fail_malformed_htlcs: Vec::new(),
1393                                                         commitment_signed: commitment_msg,
1394                                                 }
1395                                         });
1396                                 }
1397                                 true
1398                         },
1399                 }
1400         }
1401
1402         /// Gets the node_id held by this ChannelManager
1403         pub fn get_our_node_id(&self) -> PublicKey {
1404                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1405         }
1406
1407         /// Used to restore channels to normal operation after a
1408         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1409         /// operation.
1410         pub fn test_restore_channel_monitor(&self) {
1411                 unimplemented!();
1412         }
1413
1414         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1415                 if msg.chain_hash != self.genesis_hash {
1416                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1417                 }
1418                 let mut channel_state = self.channel_state.lock().unwrap();
1419                 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1420                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1421                 }
1422
1423                 let chan_keys = if cfg!(feature = "fuzztarget") {
1424                         ChannelKeys {
1425                                 funding_key:               SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]).unwrap(),
1426                                 revocation_base_key:       SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]).unwrap(),
1427                                 payment_base_key:          SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]).unwrap(),
1428                                 delayed_payment_base_key:  SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0]).unwrap(),
1429                                 htlc_base_key:             SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0]).unwrap(),
1430                                 channel_close_key:         SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0]).unwrap(),
1431                                 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0]).unwrap(),
1432                                 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1433                         }
1434                 } else {
1435                         let mut key_seed = [0u8; 32];
1436                         rng::fill_bytes(&mut key_seed);
1437                         match ChannelKeys::new_from_seed(&key_seed) {
1438                                 Ok(key) => key,
1439                                 Err(_) => panic!("RNG is busted!")
1440                         }
1441                 };
1442
1443                 let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, false, self.announce_channels_publicly, Arc::clone(&self.logger)).map_err(|e| MsgHandleErrInternal::from_no_close(e))?;
1444                 let accept_msg = channel.get_accept_channel();
1445                 channel_state.by_id.insert(channel.channel_id(), channel);
1446                 Ok(accept_msg)
1447         }
1448
1449         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1450                 let (value, output_script, user_id) = {
1451                         let mut channel_state = self.channel_state.lock().unwrap();
1452                         match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1453                                 Some(chan) => {
1454                                         if chan.get_their_node_id() != *their_node_id {
1455                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1456                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1457                                         }
1458                                         chan.accept_channel(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1459                                         (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1460                                 },
1461                                 //TODO: same as above
1462                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1463                         }
1464                 };
1465                 let mut pending_events = self.pending_events.lock().unwrap();
1466                 pending_events.push(events::Event::FundingGenerationReady {
1467                         temporary_channel_id: msg.temporary_channel_id,
1468                         channel_value_satoshis: value,
1469                         output_script: output_script,
1470                         user_channel_id: user_id,
1471                 });
1472                 Ok(())
1473         }
1474
1475         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1476                 let (chan, funding_msg, monitor_update) = {
1477                         let mut channel_state = self.channel_state.lock().unwrap();
1478                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1479                                 hash_map::Entry::Occupied(mut chan) => {
1480                                         if chan.get().get_their_node_id() != *their_node_id {
1481                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1482                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1483                                         }
1484                                         match chan.get_mut().funding_created(msg) {
1485                                                 Ok((funding_msg, monitor_update)) => {
1486                                                         (chan.remove(), funding_msg, monitor_update)
1487                                                 },
1488                                                 Err(e) => {
1489                                                         return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1490                                                 }
1491                                         }
1492                                 },
1493                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1494                         }
1495                 }; // Release channel lock for install_watch_outpoint call,
1496                    // note that this means if the remote end is misbehaving and sends a message for the same
1497                    // channel back-to-back with funding_created, we'll end up thinking they sent a message
1498                    // for a bogus channel.
1499                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1500                         unimplemented!();
1501                 }
1502                 let mut channel_state = self.channel_state.lock().unwrap();
1503                 match channel_state.by_id.entry(funding_msg.channel_id) {
1504                         hash_map::Entry::Occupied(_) => {
1505                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1506                         },
1507                         hash_map::Entry::Vacant(e) => {
1508                                 e.insert(chan);
1509                         }
1510                 }
1511                 Ok(funding_msg)
1512         }
1513
1514         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1515                 let (funding_txo, user_id, monitor) = {
1516                         let mut channel_state = self.channel_state.lock().unwrap();
1517                         match channel_state.by_id.get_mut(&msg.channel_id) {
1518                                 Some(chan) => {
1519                                         if chan.get_their_node_id() != *their_node_id {
1520                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1521                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1522                                         }
1523                                         let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1524                                         (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1525                                 },
1526                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1527                         }
1528                 };
1529                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1530                         unimplemented!();
1531                 }
1532                 let mut pending_events = self.pending_events.lock().unwrap();
1533                 pending_events.push(events::Event::FundingBroadcastSafe {
1534                         funding_txo: funding_txo,
1535                         user_channel_id: user_id,
1536                 });
1537                 Ok(())
1538         }
1539
1540         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1541                 let mut channel_state = self.channel_state.lock().unwrap();
1542                 match channel_state.by_id.get_mut(&msg.channel_id) {
1543                         Some(chan) => {
1544                                 if chan.get_their_node_id() != *their_node_id {
1545                                         //TODO: here and below MsgHandleErrInternal, #153 case
1546                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1547                                 }
1548                                 chan.funding_locked(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1549                                 return Ok(self.get_announcement_sigs(chan));
1550                         },
1551                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1552                 };
1553         }
1554
1555         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1556                 let (res, chan_option) = {
1557                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1558                         let channel_state = channel_state_lock.borrow_parts();
1559
1560                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1561                                 hash_map::Entry::Occupied(mut chan_entry) => {
1562                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1563                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1564                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1565                                         }
1566                                         let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1567                                         if chan_entry.get().is_shutdown() {
1568                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1569                                                         channel_state.short_to_id.remove(&short_id);
1570                                                 }
1571                                                 (res, Some(chan_entry.remove_entry().1))
1572                                         } else { (res, None) }
1573                                 },
1574                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1575                         }
1576                 };
1577                 for payment_hash in res.2 {
1578                         // unknown_next_peer...I dunno who that is anymore....
1579                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1580                 }
1581                 if let Some(chan) = chan_option {
1582                         if let Ok(update) = self.get_channel_update(&chan) {
1583                                 let mut events = self.pending_events.lock().unwrap();
1584                                 events.push(events::Event::BroadcastChannelUpdate {
1585                                         msg: update
1586                                 });
1587                         }
1588                 }
1589                 Ok((res.0, res.1))
1590         }
1591
1592         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1593                 let (res, chan_option) = {
1594                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1595                         let channel_state = channel_state_lock.borrow_parts();
1596                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1597                                 hash_map::Entry::Occupied(mut chan_entry) => {
1598                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1599                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1600                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1601                                         }
1602                                         let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1603                                         if res.1.is_some() {
1604                                                 // We're done with this channel, we've got a signed closing transaction and
1605                                                 // will send the closing_signed back to the remote peer upon return. This
1606                                                 // also implies there are no pending HTLCs left on the channel, so we can
1607                                                 // fully delete it from tracking (the channel monitor is still around to
1608                                                 // watch for old state broadcasts)!
1609                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1610                                                         channel_state.short_to_id.remove(&short_id);
1611                                                 }
1612                                                 (res, Some(chan_entry.remove_entry().1))
1613                                         } else { (res, None) }
1614                                 },
1615                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1616                         }
1617                 };
1618                 if let Some(broadcast_tx) = res.1 {
1619                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1620                 }
1621                 if let Some(chan) = chan_option {
1622                         if let Ok(update) = self.get_channel_update(&chan) {
1623                                 let mut events = self.pending_events.lock().unwrap();
1624                                 events.push(events::Event::BroadcastChannelUpdate {
1625                                         msg: update
1626                                 });
1627                         }
1628                 }
1629                 Ok(res.0)
1630         }
1631
1632         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1633                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1634                 //determine the state of the payment based on our response/if we forward anything/the time
1635                 //we take to respond. We should take care to avoid allowing such an attack.
1636                 //
1637                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1638                 //us repeatedly garbled in different ways, and compare our error messages, which are
1639                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1640                 //but we should prevent it anyway.
1641
1642                 let (mut pending_forward_info, shared_secret, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1643                 let channel_state = channel_state_lock.borrow_parts();
1644
1645                 let claimable_htlcs_entry = channel_state.claimable_htlcs.entry(msg.payment_hash.clone());
1646
1647                 // We dont correctly handle payments that route through us twice on their way to their
1648                 // destination. That's OK since those nodes are probably busted or trying to do network
1649                 // mapping through repeated loops. In either case, we want them to stop talking to us, so
1650                 // we send permanent_node_failure.
1651                 let mut will_forward = false;
1652                 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { short_channel_id, .. }) = pending_forward_info {
1653                         if let &hash_map::Entry::Occupied(ref e) = &claimable_htlcs_entry {
1654                                 let mut acceptable_cycle = false;
1655                                 if let &PendingOutboundHTLC::OutboundRoute { .. } = e.get() {
1656                                         acceptable_cycle = short_channel_id == 0;
1657                                 }
1658                                 if !acceptable_cycle {
1659                                         log_info!(self, "Failed to accept incoming HTLC: Payment looped through us twice");
1660                                         pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1661                                                 channel_id: msg.channel_id,
1662                                                 htlc_id: msg.htlc_id,
1663                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret.unwrap(), 0x4000 | 0x2000 | 2, &[0;0]),
1664                                         }));
1665                                 } else {
1666                                         will_forward = true;
1667                                 }
1668                         } else {
1669                                 will_forward = true;
1670                         }
1671                 }
1672
1673                 let (source_short_channel_id, res) = match channel_state.by_id.get_mut(&msg.channel_id) {
1674                         Some(chan) => {
1675                                 if chan.get_their_node_id() != *their_node_id {
1676                                         //TODO: here MsgHandleErrInternal, #153 case
1677                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1678                                 }
1679                                 if !chan.is_usable() {
1680                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1681                                 }
1682                                 let short_channel_id = chan.get_short_channel_id().unwrap();
1683                                 if let PendingHTLCStatus::Forward(ref mut forward_info) = pending_forward_info {
1684                                         forward_info.prev_short_channel_id = short_channel_id;
1685                                 }
1686                                 (short_channel_id, chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?)
1687                         },
1688                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1689                 };
1690
1691                 if will_forward {
1692                         match claimable_htlcs_entry {
1693                                 hash_map::Entry::Occupied(mut e) => {
1694                                         let outbound_route = e.get_mut();
1695                                         let (route, session_priv) = match outbound_route {
1696                                                 &mut PendingOutboundHTLC::OutboundRoute { ref route, ref session_priv } => {
1697                                                         (route.clone(), session_priv.clone())
1698                                                 },
1699                                                 _ => unreachable!(),
1700                                         };
1701                                         *outbound_route = PendingOutboundHTLC::CycledRoute {
1702                                                 source_short_channel_id,
1703                                                 incoming_packet_shared_secret: shared_secret.unwrap(),
1704                                                 route,
1705                                                 session_priv,
1706                                         };
1707                                 },
1708                                 hash_map::Entry::Vacant(e) => {
1709                                         e.insert(PendingOutboundHTLC::IntermediaryHopData {
1710                                                 source_short_channel_id,
1711                                                 incoming_packet_shared_secret: shared_secret.unwrap(),
1712                                         });
1713                                 }
1714                         }
1715                 }
1716
1717                 Ok(res)
1718         }
1719
1720         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1721                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1722                 // Claim funds first, cause we don't really care if the channel we received the message on
1723                 // is broken, we may have enough info to get our own money!
1724                 self.claim_funds_internal(msg.payment_preimage.clone(), false);
1725
1726                 let mut channel_state = self.channel_state.lock().unwrap();
1727                 match channel_state.by_id.get_mut(&msg.channel_id) {
1728                         Some(chan) => {
1729                                 if chan.get_their_node_id() != *their_node_id {
1730                                         //TODO: here and below MsgHandleErrInternal, #153 case
1731                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1732                                 }
1733                                 chan.update_fulfill_htlc(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1734                         },
1735                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1736                 }
1737         }
1738
1739         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, MsgHandleErrInternal> {
1740                 let mut channel_state = self.channel_state.lock().unwrap();
1741                 let payment_hash = match channel_state.by_id.get_mut(&msg.channel_id) {
1742                         Some(chan) => {
1743                                 if chan.get_their_node_id() != *their_node_id {
1744                                         //TODO: here and below MsgHandleErrInternal, #153 case
1745                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1746                                 }
1747                                 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1748                         },
1749                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1750                 }?;
1751
1752                 if let Some(pending_htlc) = channel_state.claimable_htlcs.get(&payment_hash) {
1753                         match pending_htlc {
1754                                 &PendingOutboundHTLC::OutboundRoute { ref route, ref session_priv } => {
1755                                         // Handle packed channel/node updates for passing back for the route handler
1756                                         let mut packet_decrypted = msg.reason.data.clone();
1757                                         let mut res = None;
1758                                         Self::construct_onion_keys_callback(&self.secp_ctx, &route, &session_priv, |shared_secret, _, _, route_hop| {
1759                                                 if res.is_some() { return; }
1760
1761                                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1762
1763                                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1764                                                 decryption_tmp.resize(packet_decrypted.len(), 0);
1765                                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1766                                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1767                                                 packet_decrypted = decryption_tmp;
1768
1769                                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::decode(&packet_decrypted) {
1770                                                         if err_packet.failuremsg.len() >= 2 {
1771                                                                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1772
1773                                                                 let mut hmac = Hmac::new(Sha256::new(), &um);
1774                                                                 hmac.input(&err_packet.encode()[32..]);
1775                                                                 let mut calc_tag = [0u8; 32];
1776                                                                 hmac.raw_result(&mut calc_tag);
1777                                                                 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1778                                                                         const UNKNOWN_CHAN: u16 = 0x4000|10;
1779                                                                         const TEMP_CHAN_FAILURE: u16 = 0x4000|7;
1780                                                                         match byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]) {
1781                                                                                 TEMP_CHAN_FAILURE => {
1782                                                                                         if err_packet.failuremsg.len() >= 4 {
1783                                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[2..4]) as usize;
1784                                                                                                 if err_packet.failuremsg.len() >= 4 + update_len {
1785                                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::decode(&err_packet.failuremsg[4..4 + update_len]) {
1786                                                                                                                 res = Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1787                                                                                                                         msg: chan_update,
1788                                                                                                                 });
1789                                                                                                         }
1790                                                                                                 }
1791                                                                                         }
1792                                                                                 },
1793                                                                                 UNKNOWN_CHAN => {
1794                                                                                         // No such next-hop. We know this came from the
1795                                                                                         // current node as the HMAC validated.
1796                                                                                         res = Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1797                                                                                                 short_channel_id: route_hop.short_channel_id
1798                                                                                         });
1799                                                                                 },
1800                                                                                 _ => {}, //TODO: Enumerate all of these!
1801                                                                         }
1802                                                                 }
1803                                                         }
1804                                                 }
1805                                         }).unwrap();
1806                                         Ok(res)
1807                                 },
1808                                 _ => { Ok(None) },
1809                         }
1810                 } else {
1811                         Ok(None)
1812                 }
1813         }
1814
1815         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
1816                 let mut channel_state = self.channel_state.lock().unwrap();
1817                 match channel_state.by_id.get_mut(&msg.channel_id) {
1818                         Some(chan) => {
1819                                 if chan.get_their_node_id() != *their_node_id {
1820                                         //TODO: here and below MsgHandleErrInternal, #153 case
1821                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1822                                 }
1823                                 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1824                         },
1825                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1826                 }
1827         }
1828
1829         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
1830                 let (chan_announcement, chan_update) = {
1831                         let mut channel_state = self.channel_state.lock().unwrap();
1832                         match channel_state.by_id.get_mut(&msg.channel_id) {
1833                                 Some(chan) => {
1834                                         if chan.get_their_node_id() != *their_node_id {
1835                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1836                                         }
1837                                         if !chan.is_usable() {
1838                                                 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
1839                                         }
1840
1841                                         let our_node_id = self.get_our_node_id();
1842                                         let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())
1843                                                 .map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1844
1845                                         let were_node_one = announcement.node_id_1 == our_node_id;
1846                                         let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1847                                         let bad_sig_action = MsgHandleErrInternal::send_err_msg_close_chan("Bad announcement_signatures node_signature", msg.channel_id);
1848                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }), bad_sig_action);
1849                                         secp_call!(self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }), bad_sig_action);
1850
1851                                         let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1852
1853                                         (msgs::ChannelAnnouncement {
1854                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
1855                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
1856                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
1857                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
1858                                                 contents: announcement,
1859                                         }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
1860                                 },
1861                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1862                         }
1863                 };
1864                 let mut pending_events = self.pending_events.lock().unwrap();
1865                 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
1866                 Ok(())
1867         }
1868
1869
1870 }
1871
1872 impl events::EventsProvider for ChannelManager {
1873         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
1874                 let mut pending_events = self.pending_events.lock().unwrap();
1875                 let mut ret = Vec::new();
1876                 mem::swap(&mut ret, &mut *pending_events);
1877                 ret
1878         }
1879 }
1880
1881 impl ChainListener for ChannelManager {
1882         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
1883                 let mut new_events = Vec::new();
1884                 let mut failed_channels = Vec::new();
1885                 {
1886                         let mut channel_lock = self.channel_state.lock().unwrap();
1887                         let channel_state = channel_lock.borrow_parts();
1888                         let short_to_id = channel_state.short_to_id;
1889                         channel_state.by_id.retain(|_, channel| {
1890                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
1891                                 if let Ok(Some(funding_locked)) = chan_res {
1892                                         let announcement_sigs = self.get_announcement_sigs(channel);
1893                                         new_events.push(events::Event::SendFundingLocked {
1894                                                 node_id: channel.get_their_node_id(),
1895                                                 msg: funding_locked,
1896                                                 announcement_sigs: announcement_sigs
1897                                         });
1898                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1899                                 } else if let Err(e) = chan_res {
1900                                         new_events.push(events::Event::HandleError {
1901                                                 node_id: channel.get_their_node_id(),
1902                                                 action: e.action,
1903                                         });
1904                                         if channel.is_shutdown() {
1905                                                 return false;
1906                                         }
1907                                 }
1908                                 if let Some(funding_txo) = channel.get_funding_txo() {
1909                                         for tx in txn_matched {
1910                                                 for inp in tx.input.iter() {
1911                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
1912                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1913                                                                         short_to_id.remove(&short_id);
1914                                                                 }
1915                                                                 // It looks like our counterparty went on-chain. We go ahead and
1916                                                                 // broadcast our latest local state as well here, just in case its
1917                                                                 // some kind of SPV attack, though we expect these to be dropped.
1918                                                                 failed_channels.push(channel.force_shutdown());
1919                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1920                                                                         new_events.push(events::Event::BroadcastChannelUpdate {
1921                                                                                 msg: update
1922                                                                         });
1923                                                                 }
1924                                                                 return false;
1925                                                         }
1926                                                 }
1927                                         }
1928                                 }
1929                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
1930                                         if let Some(short_id) = channel.get_short_channel_id() {
1931                                                 short_to_id.remove(&short_id);
1932                                         }
1933                                         failed_channels.push(channel.force_shutdown());
1934                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
1935                                         // the latest local tx for us, so we should skip that here (it doesn't really
1936                                         // hurt anything, but does make tests a bit simpler).
1937                                         failed_channels.last_mut().unwrap().0 = Vec::new();
1938                                         if let Ok(update) = self.get_channel_update(&channel) {
1939                                                 new_events.push(events::Event::BroadcastChannelUpdate {
1940                                                         msg: update
1941                                                 });
1942                                         }
1943                                         return false;
1944                                 }
1945                                 true
1946                         });
1947                 }
1948                 for failure in failed_channels.drain(..) {
1949                         self.finish_force_close_channel(failure);
1950                 }
1951                 let mut pending_events = self.pending_events.lock().unwrap();
1952                 for funding_locked in new_events.drain(..) {
1953                         pending_events.push(funding_locked);
1954                 }
1955                 self.latest_block_height.store(height as usize, Ordering::Release);
1956         }
1957
1958         /// We force-close the channel without letting our counterparty participate in the shutdown
1959         fn block_disconnected(&self, header: &BlockHeader) {
1960                 let mut new_events = Vec::new();
1961                 let mut failed_channels = Vec::new();
1962                 {
1963                         let mut channel_lock = self.channel_state.lock().unwrap();
1964                         let channel_state = channel_lock.borrow_parts();
1965                         let short_to_id = channel_state.short_to_id;
1966                         channel_state.by_id.retain(|_,  v| {
1967                                 if v.block_disconnected(header) {
1968                                         if let Some(short_id) = v.get_short_channel_id() {
1969                                                 short_to_id.remove(&short_id);
1970                                         }
1971                                         failed_channels.push(v.force_shutdown());
1972                                         if let Ok(update) = self.get_channel_update(&v) {
1973                                                 new_events.push(events::Event::BroadcastChannelUpdate {
1974                                                         msg: update
1975                                                 });
1976                                         }
1977                                         false
1978                                 } else {
1979                                         true
1980                                 }
1981                         });
1982                 }
1983                 for failure in failed_channels.drain(..) {
1984                         self.finish_force_close_channel(failure);
1985                 }
1986                 if !new_events.is_empty() {
1987                         let mut pending_events = self.pending_events.lock().unwrap();
1988                         for funding_locked in new_events.drain(..) {
1989                                 pending_events.push(funding_locked);
1990                         }
1991                 }
1992                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
1993         }
1994 }
1995
1996 macro_rules! handle_error {
1997         ($self: ident, $internal: expr, $their_node_id: expr) => {
1998                 match $internal {
1999                         Ok(msg) => Ok(msg),
2000                         Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
2001                                 if needs_channel_force_close {
2002                                         match &err.action {
2003                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
2004                                                         if msg.channel_id == [0; 32] {
2005                                                                 $self.peer_disconnected(&$their_node_id, true);
2006                                                         } else {
2007                                                                 $self.force_close_channel(&msg.channel_id);
2008                                                         }
2009                                                 },
2010                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
2011                                                 &Some(msgs::ErrorAction::IgnoreError) => {},
2012                                                 &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
2013                                                         if msg.channel_id == [0; 32] {
2014                                                                 $self.peer_disconnected(&$their_node_id, true);
2015                                                         } else {
2016                                                                 $self.force_close_channel(&msg.channel_id);
2017                                                         }
2018                                                 },
2019                                                 &None => {},
2020                                         }
2021                                 }
2022                                 Err(err)
2023                         },
2024                 }
2025         }
2026 }
2027
2028 impl ChannelMessageHandler for ChannelManager {
2029         //TODO: Handle errors and close channel (or so)
2030         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
2031                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2032         }
2033
2034         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2035                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2036         }
2037
2038         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
2039                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2040         }
2041
2042         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2043                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2044         }
2045
2046         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
2047                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2048         }
2049
2050         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
2051                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2052         }
2053
2054         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
2055                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2056         }
2057
2058         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2059                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2060         }
2061
2062         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2063                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2064         }
2065
2066         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, HandleError> {
2067                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2068         }
2069
2070         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2071                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2072         }
2073
2074         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
2075                 let (revoke_and_ack, commitment_signed, chan_monitor) = {
2076                         let mut channel_state = self.channel_state.lock().unwrap();
2077                         match channel_state.by_id.get_mut(&msg.channel_id) {
2078                                 Some(chan) => {
2079                                         if chan.get_their_node_id() != *their_node_id {
2080                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
2081                                         }
2082                                         chan.commitment_signed(&msg)?
2083                                 },
2084                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
2085                         }
2086                 };
2087                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2088                         unimplemented!();
2089                 }
2090
2091                 Ok((revoke_and_ack, commitment_signed))
2092         }
2093
2094         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
2095                 let (res, mut pending_forwards, mut pending_failures, chan_monitor) = {
2096                         let mut channel_state = self.channel_state.lock().unwrap();
2097                         match channel_state.by_id.get_mut(&msg.channel_id) {
2098                                 Some(chan) => {
2099                                         if chan.get_their_node_id() != *their_node_id {
2100                                                 return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
2101                                         }
2102                                         chan.revoke_and_ack(&msg)?
2103                                 },
2104                                 None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
2105                         }
2106                 };
2107                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2108                         unimplemented!();
2109                 }
2110                 for failure in pending_failures.drain(..) {
2111                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &failure.0, failure.1);
2112                 }
2113
2114                 let mut forward_event = None;
2115                 if !pending_forwards.is_empty() {
2116                         let mut channel_state = self.channel_state.lock().unwrap();
2117                         if channel_state.forward_htlcs.is_empty() {
2118                                 forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
2119                                 channel_state.next_forward = forward_event.unwrap();
2120                         }
2121                         for forward_info in pending_forwards.drain(..) {
2122                                 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2123                                         hash_map::Entry::Occupied(mut entry) => {
2124                                                 entry.get_mut().push(forward_info);
2125                                         },
2126                                         hash_map::Entry::Vacant(entry) => {
2127                                                 entry.insert(vec!(forward_info));
2128                                         }
2129                                 }
2130                         }
2131                 }
2132                 match forward_event {
2133                         Some(time) => {
2134                                 let mut pending_events = self.pending_events.lock().unwrap();
2135                                 pending_events.push(events::Event::PendingHTLCsForwardable {
2136                                         time_forwardable: time
2137                                 });
2138                         }
2139                         None => {},
2140                 }
2141
2142                 Ok(res)
2143         }
2144
2145         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2146                 let mut channel_state = self.channel_state.lock().unwrap();
2147                 match channel_state.by_id.get_mut(&msg.channel_id) {
2148                         Some(chan) => {
2149                                 if chan.get_their_node_id() != *their_node_id {
2150                                         return Err(HandleError{err: "Got a message for a channel from the wrong node!", action: None})
2151                                 }
2152                                 chan.update_fee(&*self.fee_estimator, &msg)
2153                         },
2154                         None => return Err(HandleError{err: "Failed to find corresponding channel", action: None})
2155                 }
2156         }
2157
2158         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2159                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2160         }
2161
2162         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2163                 let mut new_events = Vec::new();
2164                 let mut failed_channels = Vec::new();
2165                 {
2166                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2167                         let channel_state = channel_state_lock.borrow_parts();
2168                         let short_to_id = channel_state.short_to_id;
2169                         if no_connection_possible {
2170                                 channel_state.by_id.retain(|_, chan| {
2171                                         if chan.get_their_node_id() == *their_node_id {
2172                                                 if let Some(short_id) = chan.get_short_channel_id() {
2173                                                         short_to_id.remove(&short_id);
2174                                                 }
2175                                                 failed_channels.push(chan.force_shutdown());
2176                                                 if let Ok(update) = self.get_channel_update(&chan) {
2177                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2178                                                                 msg: update
2179                                                         });
2180                                                 }
2181                                                 false
2182                                         } else {
2183                                                 true
2184                                         }
2185                                 });
2186                         } else {
2187                                 for chan in channel_state.by_id {
2188                                         if chan.1.get_their_node_id() == *their_node_id {
2189                                                 //TODO: mark channel disabled (and maybe announce such after a timeout). Also
2190                                                 //fail and wipe any uncommitted outbound HTLCs as those are considered after
2191                                                 //reconnect.
2192                                         }
2193                                 }
2194                         }
2195                 }
2196                 for failure in failed_channels.drain(..) {
2197                         self.finish_force_close_channel(failure);
2198                 }
2199                 if !new_events.is_empty() {
2200                         let mut pending_events = self.pending_events.lock().unwrap();
2201                         for event in new_events.drain(..) {
2202                                 pending_events.push(event);
2203                         }
2204                 }
2205         }
2206
2207         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2208                 if msg.channel_id == [0; 32] {
2209                         for chan in self.list_channels() {
2210                                 if chan.remote_network_id == *their_node_id {
2211                                         self.force_close_channel(&chan.channel_id);
2212                                 }
2213                         }
2214                 } else {
2215                         self.force_close_channel(&msg.channel_id);
2216                 }
2217         }
2218 }
2219
2220 #[cfg(test)]
2221 mod tests {
2222         use chain::chaininterface;
2223         use chain::transaction::OutPoint;
2224         use chain::chaininterface::ChainListener;
2225         use ln::channelmanager::{ChannelManager,OnionKeys};
2226         use ln::router::{Route, RouteHop, Router};
2227         use ln::msgs;
2228         use ln::msgs::{MsgEncodable,ChannelMessageHandler,RoutingMessageHandler};
2229         use util::test_utils;
2230         use util::events::{Event, EventsProvider};
2231         use util::logger::Logger;
2232
2233         use bitcoin::util::hash::Sha256dHash;
2234         use bitcoin::blockdata::block::{Block, BlockHeader};
2235         use bitcoin::blockdata::transaction::{Transaction, TxOut};
2236         use bitcoin::blockdata::constants::genesis_block;
2237         use bitcoin::network::constants::Network;
2238         use bitcoin::network::serialize::serialize;
2239         use bitcoin::network::serialize::BitcoinHash;
2240
2241         use hex;
2242
2243         use secp256k1::{Secp256k1, Message};
2244         use secp256k1::key::{PublicKey,SecretKey};
2245
2246         use crypto::sha2::Sha256;
2247         use crypto::digest::Digest;
2248
2249         use rand::{thread_rng,Rng};
2250
2251         use std::collections::HashMap;
2252         use std::default::Default;
2253         use std::sync::{Arc, Mutex};
2254         use std::time::Instant;
2255         use std::mem;
2256
2257         fn build_test_onion_keys() -> Vec<OnionKeys> {
2258                 // Keys from BOLT 4, used in both test vector tests
2259                 let secp_ctx = Secp256k1::new();
2260
2261                 let route = Route {
2262                         hops: vec!(
2263                                         RouteHop {
2264                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2265                                                 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
2266                                         },
2267                                         RouteHop {
2268                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2269                                                 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
2270                                         },
2271                                         RouteHop {
2272                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2273                                                 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
2274                                         },
2275                                         RouteHop {
2276                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2277                                                 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
2278                                         },
2279                                         RouteHop {
2280                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2281                                                 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
2282                                         },
2283                         ),
2284                 };
2285
2286                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2287
2288                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2289                 assert_eq!(onion_keys.len(), route.hops.len());
2290                 onion_keys
2291         }
2292
2293         #[test]
2294         fn onion_vectors() {
2295                 // Packet creation test vectors from BOLT 4
2296                 let onion_keys = build_test_onion_keys();
2297
2298                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2299                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2300                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2301                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2302                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2303
2304                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2305                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2306                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2307                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2308                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2309
2310                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2311                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2312                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2313                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2314                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2315
2316                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2317                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2318                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2319                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2320                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2321
2322                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2323                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2324                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2325                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2326                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2327
2328                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2329                 let payloads = vec!(
2330                         msgs::OnionHopData {
2331                                 realm: 0,
2332                                 data: msgs::OnionRealm0HopData {
2333                                         short_channel_id: 0,
2334                                         amt_to_forward: 0,
2335                                         outgoing_cltv_value: 0,
2336                                 },
2337                                 hmac: [0; 32],
2338                         },
2339                         msgs::OnionHopData {
2340                                 realm: 0,
2341                                 data: msgs::OnionRealm0HopData {
2342                                         short_channel_id: 0x0101010101010101,
2343                                         amt_to_forward: 0x0100000001,
2344                                         outgoing_cltv_value: 0,
2345                                 },
2346                                 hmac: [0; 32],
2347                         },
2348                         msgs::OnionHopData {
2349                                 realm: 0,
2350                                 data: msgs::OnionRealm0HopData {
2351                                         short_channel_id: 0x0202020202020202,
2352                                         amt_to_forward: 0x0200000002,
2353                                         outgoing_cltv_value: 0,
2354                                 },
2355                                 hmac: [0; 32],
2356                         },
2357                         msgs::OnionHopData {
2358                                 realm: 0,
2359                                 data: msgs::OnionRealm0HopData {
2360                                         short_channel_id: 0x0303030303030303,
2361                                         amt_to_forward: 0x0300000003,
2362                                         outgoing_cltv_value: 0,
2363                                 },
2364                                 hmac: [0; 32],
2365                         },
2366                         msgs::OnionHopData {
2367                                 realm: 0,
2368                                 data: msgs::OnionRealm0HopData {
2369                                         short_channel_id: 0x0404040404040404,
2370                                         amt_to_forward: 0x0400000004,
2371                                         outgoing_cltv_value: 0,
2372                                 },
2373                                 hmac: [0; 32],
2374                         },
2375                 );
2376
2377                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]).unwrap();
2378                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2379                 // anyway...
2380                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2381         }
2382
2383         #[test]
2384         fn test_failure_packet_onion() {
2385                 // Returning Errors test vectors from BOLT 4
2386
2387                 let onion_keys = build_test_onion_keys();
2388                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2389                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2390
2391                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2392                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2393
2394                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2395                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2396
2397                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2398                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2399
2400                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2401                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2402
2403                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2404                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2405         }
2406
2407         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2408                 assert!(chain.does_match_tx(tx));
2409                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2410                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2411                 for i in 2..100 {
2412                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2413                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2414                 }
2415         }
2416
2417         struct Node {
2418                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2419                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2420                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2421                 node: Arc<ChannelManager>,
2422                 router: Router,
2423         }
2424
2425         static mut CHAN_COUNT: u32 = 0;
2426         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2427                 node_a.node.create_channel(node_b.node.get_our_node_id(), 100000, 10001, 42).unwrap();
2428
2429                 let events_1 = node_a.node.get_and_clear_pending_events();
2430                 assert_eq!(events_1.len(), 1);
2431                 let accept_chan = match events_1[0] {
2432                         Event::SendOpenChannel { ref node_id, ref msg } => {
2433                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2434                                 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2435                         },
2436                         _ => panic!("Unexpected event"),
2437                 };
2438
2439                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2440
2441                 let chan_id = unsafe { CHAN_COUNT };
2442                 let tx;
2443                 let funding_output;
2444
2445                 let events_2 = node_a.node.get_and_clear_pending_events();
2446                 assert_eq!(events_2.len(), 1);
2447                 match events_2[0] {
2448                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2449                                 assert_eq!(*channel_value_satoshis, 100000);
2450                                 assert_eq!(user_channel_id, 42);
2451
2452                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2453                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2454                                 }]};
2455                                 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2456
2457                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2458                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2459                                 assert_eq!(added_monitors.len(), 1);
2460                                 assert_eq!(added_monitors[0].0, funding_output);
2461                                 added_monitors.clear();
2462                         },
2463                         _ => panic!("Unexpected event"),
2464                 }
2465
2466                 let events_3 = node_a.node.get_and_clear_pending_events();
2467                 assert_eq!(events_3.len(), 1);
2468                 let funding_signed = match events_3[0] {
2469                         Event::SendFundingCreated { ref node_id, ref msg } => {
2470                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2471                                 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2472                                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2473                                 assert_eq!(added_monitors.len(), 1);
2474                                 assert_eq!(added_monitors[0].0, funding_output);
2475                                 added_monitors.clear();
2476                                 res
2477                         },
2478                         _ => panic!("Unexpected event"),
2479                 };
2480
2481                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2482                 {
2483                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2484                         assert_eq!(added_monitors.len(), 1);
2485                         assert_eq!(added_monitors[0].0, funding_output);
2486                         added_monitors.clear();
2487                 }
2488
2489                 let events_4 = node_a.node.get_and_clear_pending_events();
2490                 assert_eq!(events_4.len(), 1);
2491                 match events_4[0] {
2492                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2493                                 assert_eq!(user_channel_id, 42);
2494                                 assert_eq!(*funding_txo, funding_output);
2495                         },
2496                         _ => panic!("Unexpected event"),
2497                 };
2498
2499                 confirm_transaction(&node_a.chain_monitor, &tx, chan_id);
2500                 let events_5 = node_a.node.get_and_clear_pending_events();
2501                 assert_eq!(events_5.len(), 1);
2502                 match events_5[0] {
2503                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2504                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2505                                 assert!(announcement_sigs.is_none());
2506                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), msg).unwrap()
2507                         },
2508                         _ => panic!("Unexpected event"),
2509                 };
2510
2511                 let channel_id;
2512
2513                 confirm_transaction(&node_b.chain_monitor, &tx, chan_id);
2514                 let events_6 = node_b.node.get_and_clear_pending_events();
2515                 assert_eq!(events_6.len(), 1);
2516                 let as_announcement_sigs = match events_6[0] {
2517                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2518                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
2519                                 channel_id = msg.channel_id.clone();
2520                                 let as_announcement_sigs = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap().unwrap();
2521                                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &(*announcement_sigs).clone().unwrap()).unwrap();
2522                                 as_announcement_sigs
2523                         },
2524                         _ => panic!("Unexpected event"),
2525                 };
2526
2527                 let events_7 = node_a.node.get_and_clear_pending_events();
2528                 assert_eq!(events_7.len(), 1);
2529                 let (announcement, as_update) = match events_7[0] {
2530                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2531                                 (msg, update_msg)
2532                         },
2533                         _ => panic!("Unexpected event"),
2534                 };
2535
2536                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_announcement_sigs).unwrap();
2537                 let events_8 = node_b.node.get_and_clear_pending_events();
2538                 assert_eq!(events_8.len(), 1);
2539                 let bs_update = match events_8[0] {
2540                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2541                                 assert!(*announcement == *msg);
2542                                 update_msg
2543                         },
2544                         _ => panic!("Unexpected event"),
2545                 };
2546
2547                 unsafe {
2548                         CHAN_COUNT += 1;
2549                 }
2550
2551                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone(), channel_id, tx)
2552         }
2553
2554         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2555                 let chan_announcement = create_chan_between_nodes(&nodes[a], &nodes[b]);
2556                 for node in nodes {
2557                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2558                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
2559                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
2560                 }
2561                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2562         }
2563
2564         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2565                 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2566                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2567                 let (tx_a, tx_b);
2568
2569                 node_a.close_channel(channel_id).unwrap();
2570                 let events_1 = node_a.get_and_clear_pending_events();
2571                 assert_eq!(events_1.len(), 1);
2572                 let shutdown_a = match events_1[0] {
2573                         Event::SendShutdown { ref node_id, ref msg } => {
2574                                 assert_eq!(node_id, &node_b.get_our_node_id());
2575                                 msg.clone()
2576                         },
2577                         _ => panic!("Unexpected event"),
2578                 };
2579
2580                 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2581                 if !close_inbound_first {
2582                         assert!(closing_signed_b.is_none());
2583                 }
2584                 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2585                 assert!(empty_a.is_none());
2586                 if close_inbound_first {
2587                         assert!(closing_signed_a.is_none());
2588                         closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2589                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2590                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2591
2592                         let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2593                         assert!(empty_b.is_none());
2594                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2595                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2596                 } else {
2597                         closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2598                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2599                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2600
2601                         let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2602                         assert!(empty_a2.is_none());
2603                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2604                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2605                 }
2606                 assert_eq!(tx_a, tx_b);
2607                 let mut funding_tx_map = HashMap::new();
2608                 funding_tx_map.insert(funding_tx.txid(), funding_tx);
2609                 tx_a.verify(&funding_tx_map).unwrap();
2610
2611                 let events_2 = node_a.get_and_clear_pending_events();
2612                 assert_eq!(events_2.len(), 1);
2613                 let as_update = match events_2[0] {
2614                         Event::BroadcastChannelUpdate { ref msg } => {
2615                                 msg.clone()
2616                         },
2617                         _ => panic!("Unexpected event"),
2618                 };
2619
2620                 let events_3 = node_b.get_and_clear_pending_events();
2621                 assert_eq!(events_3.len(), 1);
2622                 let bs_update = match events_3[0] {
2623                         Event::BroadcastChannelUpdate { ref msg } => {
2624                                 msg.clone()
2625                         },
2626                         _ => panic!("Unexpected event"),
2627                 };
2628
2629                 (as_update, bs_update)
2630         }
2631
2632         struct SendEvent {
2633                 node_id: PublicKey,
2634                 msgs: Vec<msgs::UpdateAddHTLC>,
2635                 commitment_msg: msgs::CommitmentSigned,
2636         }
2637         impl SendEvent {
2638                 fn from_event(event: Event) -> SendEvent {
2639                         match event {
2640                                 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, commitment_signed } } => {
2641                                         assert!(update_fulfill_htlcs.is_empty());
2642                                         assert!(update_fail_htlcs.is_empty());
2643                                         assert!(update_fail_malformed_htlcs.is_empty());
2644                                         SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
2645                                 },
2646                                 _ => panic!("Unexpected event type!"),
2647                         }
2648                 }
2649         }
2650
2651         static mut PAYMENT_COUNT: u8 = 0;
2652         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2653                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
2654                 unsafe { PAYMENT_COUNT += 1 };
2655                 let our_payment_hash = {
2656                         let mut sha = Sha256::new();
2657                         sha.input(&our_payment_preimage[..]);
2658                         let mut ret = [0; 32];
2659                         sha.result(&mut ret);
2660                         ret
2661                 };
2662
2663                 let mut payment_event = {
2664                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
2665                         {
2666                                 let mut added_monitors = origin_node.chan_monitor.added_monitors.lock().unwrap();
2667                                 assert_eq!(added_monitors.len(), 1);
2668                                 added_monitors.clear();
2669                         }
2670
2671                         let mut events = origin_node.node.get_and_clear_pending_events();
2672                         assert_eq!(events.len(), 1);
2673                         SendEvent::from_event(events.remove(0))
2674                 };
2675                 let mut prev_node = origin_node;
2676
2677                 for (idx, &node) in expected_route.iter().enumerate() {
2678                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2679
2680                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2681                         {
2682                                 let added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2683                                 assert_eq!(added_monitors.len(), 0);
2684                         }
2685
2686                         let revoke_and_ack = node.node.handle_commitment_signed(&prev_node.node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2687                         {
2688                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2689                                 assert_eq!(added_monitors.len(), 1);
2690                                 added_monitors.clear();
2691                         }
2692                         assert!(prev_node.node.handle_revoke_and_ack(&node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2693                         let prev_revoke_and_ack = prev_node.node.handle_commitment_signed(&node.node.get_our_node_id(), &revoke_and_ack.1.unwrap()).unwrap();
2694                         {
2695                                 let mut added_monitors = prev_node.chan_monitor.added_monitors.lock().unwrap();
2696                                 assert_eq!(added_monitors.len(), 2);
2697                                 added_monitors.clear();
2698                         }
2699                         assert!(node.node.handle_revoke_and_ack(&prev_node.node.get_our_node_id(), &prev_revoke_and_ack.0).unwrap().is_none());
2700                         assert!(prev_revoke_and_ack.1.is_none());
2701                         {
2702                                 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2703                                 assert_eq!(added_monitors.len(), 1);
2704                                 added_monitors.clear();
2705                         }
2706
2707                         let events_1 = node.node.get_and_clear_pending_events();
2708                         assert_eq!(events_1.len(), 1);
2709                         match events_1[0] {
2710                                 Event::PendingHTLCsForwardable { .. } => { },
2711                                 _ => panic!("Unexpected event"),
2712                         };
2713
2714                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
2715                         node.node.process_pending_htlc_forwards();
2716
2717                         let mut events_2 = node.node.get_and_clear_pending_events();
2718                         assert_eq!(events_2.len(), 1);
2719                         if idx == expected_route.len() - 1 {
2720                                 match events_2[0] {
2721                                         Event::PaymentReceived { ref payment_hash, amt } => {
2722                                                 assert_eq!(our_payment_hash, *payment_hash);
2723                                                 assert_eq!(amt, recv_value);
2724                                         },
2725                                         _ => panic!("Unexpected event"),
2726                                 }
2727                         } else {
2728                                 {
2729                                         let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2730                                         assert_eq!(added_monitors.len(), 1);
2731                                         added_monitors.clear();
2732                                 }
2733                                 payment_event = SendEvent::from_event(events_2.remove(0));
2734                                 assert_eq!(payment_event.msgs.len(), 1);
2735                         }
2736
2737                         prev_node = node;
2738                 }
2739
2740                 (our_payment_preimage, our_payment_hash)
2741         }
2742
2743         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
2744                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
2745                 {
2746                         let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2747                         assert_eq!(added_monitors.len(), 1);
2748                         added_monitors.clear();
2749                 }
2750
2751                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
2752                 macro_rules! update_fulfill_dance {
2753                         ($node: expr, $prev_node: expr, $last_node: expr) => {
2754                                 {
2755                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2756                                         {
2757                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2758                                                 if $last_node {
2759                                                         assert_eq!(added_monitors.len(), 0);
2760                                                 } else {
2761                                                         assert_eq!(added_monitors.len(), 1);
2762                                                 }
2763                                                 added_monitors.clear();
2764                                         }
2765                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2766                                         {
2767                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2768                                                 assert_eq!(added_monitors.len(), 1);
2769                                                 added_monitors.clear();
2770                                         }
2771                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2772                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2773                                         assert!(revoke_and_ack.1.is_none());
2774                                         {
2775                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2776                                                 assert_eq!(added_monitors.len(), 2);
2777                                                 added_monitors.clear();
2778                                         }
2779                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2780                                         {
2781                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2782                                                 assert_eq!(added_monitors.len(), 1);
2783                                                 added_monitors.clear();
2784                                         }
2785                                 }
2786                         }
2787                 }
2788
2789                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2790                 let mut prev_node = expected_route.last().unwrap();
2791                 for node in expected_route.iter().rev() {
2792                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2793                         if next_msgs.is_some() {
2794                                 update_fulfill_dance!(node, prev_node, false);
2795                         }
2796
2797                         let events = node.node.get_and_clear_pending_events();
2798                         assert_eq!(events.len(), 1);
2799                         match events[0] {
2800                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2801                                         assert!(update_add_htlcs.is_empty());
2802                                         assert_eq!(update_fulfill_htlcs.len(), 1);
2803                                         assert!(update_fail_htlcs.is_empty());
2804                                         assert!(update_fail_malformed_htlcs.is_empty());
2805                                         expected_next_node = node_id.clone();
2806                                         next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
2807                                 },
2808                                 _ => panic!("Unexpected event"),
2809                         };
2810
2811                         prev_node = node;
2812                 }
2813
2814                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2815                 update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
2816
2817                 let events = origin_node.node.get_and_clear_pending_events();
2818                 assert_eq!(events.len(), 1);
2819                 match events[0] {
2820                         Event::PaymentSent { payment_preimage } => {
2821                                 assert_eq!(payment_preimage, our_payment_preimage);
2822                         },
2823                         _ => panic!("Unexpected event"),
2824                 }
2825         }
2826
2827         const TEST_FINAL_CLTV: u32 = 32;
2828
2829         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2830                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
2831                 assert_eq!(route.hops.len(), expected_route.len());
2832                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2833                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2834                 }
2835
2836                 send_along_route(origin_node, route, expected_route, recv_value)
2837         }
2838
2839         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
2840                 let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
2841                 assert_eq!(route.hops.len(), expected_route.len());
2842                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2843                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
2844                 }
2845
2846                 let our_payment_preimage = unsafe { [PAYMENT_COUNT; 32] };
2847                 unsafe { PAYMENT_COUNT += 1 };
2848                 let our_payment_hash = {
2849                         let mut sha = Sha256::new();
2850                         sha.input(&our_payment_preimage[..]);
2851                         let mut ret = [0; 32];
2852                         sha.result(&mut ret);
2853                         ret
2854                 };
2855
2856                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
2857                 assert_eq!(err.err, "Cannot send value that would put us over our max HTLC value in flight");
2858         }
2859
2860         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
2861                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
2862                 claim_payment(&origin, expected_route, our_payment_preimage);
2863         }
2864
2865         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
2866                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
2867                 {
2868                         let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2869                         assert_eq!(added_monitors.len(), 1);
2870                         added_monitors.clear();
2871                 }
2872
2873                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
2874                 macro_rules! update_fail_dance {
2875                         ($node: expr, $prev_node: expr, $last_node: expr) => {
2876                                 {
2877                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2878                                         let revoke_and_commit = $node.node.handle_commitment_signed(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().1).unwrap();
2879
2880                                         {
2881                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2882                                                 assert_eq!(added_monitors.len(), 1);
2883                                                 added_monitors.clear();
2884                                         }
2885                                         assert!($prev_node.node.handle_revoke_and_ack(&$node.node.get_our_node_id(), &revoke_and_commit.0).unwrap().is_none());
2886                                         {
2887                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2888                                                 assert_eq!(added_monitors.len(), 1);
2889                                                 added_monitors.clear();
2890                                         }
2891                                         let revoke_and_ack = $prev_node.node.handle_commitment_signed(&$node.node.get_our_node_id(), &revoke_and_commit.1.unwrap()).unwrap();
2892                                         {
2893                                                 let mut added_monitors = $prev_node.chan_monitor.added_monitors.lock().unwrap();
2894                                                 assert_eq!(added_monitors.len(), 1);
2895                                                 added_monitors.clear();
2896                                         }
2897                                         assert!(revoke_and_ack.1.is_none());
2898                                         assert!($node.node.get_and_clear_pending_events().is_empty());
2899                                         assert!($node.node.handle_revoke_and_ack(&$prev_node.node.get_our_node_id(), &revoke_and_ack.0).unwrap().is_none());
2900                                         {
2901                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2902                                                 if $last_node {
2903                                                         assert_eq!(added_monitors.len(), 1);
2904                                                 } else {
2905                                                         assert_eq!(added_monitors.len(), 2);
2906                                                         assert!(added_monitors[0].0 != added_monitors[1].0);
2907                                                 }
2908                                                 added_monitors.clear();
2909                                         }
2910                                 }
2911                         }
2912                 }
2913
2914                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2915                 let mut prev_node = expected_route.last().unwrap();
2916                 for node in expected_route.iter().rev() {
2917                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2918                         if next_msgs.is_some() {
2919                                 update_fail_dance!(node, prev_node, false);
2920                         }
2921
2922                         let events = node.node.get_and_clear_pending_events();
2923                         assert_eq!(events.len(), 1);
2924                         match events[0] {
2925                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2926                                         assert!(update_add_htlcs.is_empty());
2927                                         assert!(update_fulfill_htlcs.is_empty());
2928                                         assert_eq!(update_fail_htlcs.len(), 1);
2929                                         assert!(update_fail_malformed_htlcs.is_empty());
2930                                         expected_next_node = node_id.clone();
2931                                         next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2932                                 },
2933                                 _ => panic!("Unexpected event"),
2934                         };
2935
2936                         prev_node = node;
2937                 }
2938
2939                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2940                 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
2941
2942                 let events = origin_node.node.get_and_clear_pending_events();
2943                 assert_eq!(events.len(), 1);
2944                 match events[0] {
2945                         Event::PaymentFailed { payment_hash } => {
2946                                 assert_eq!(payment_hash, our_payment_hash);
2947                         },
2948                         _ => panic!("Unexpected event"),
2949                 }
2950         }
2951
2952         fn create_network(node_count: usize) -> Vec<Node> {
2953                 let mut nodes = Vec::new();
2954                 let mut rng = thread_rng();
2955                 let secp_ctx = Secp256k1::new();
2956                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
2957
2958                 for _ in 0..node_count {
2959                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
2960                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
2961                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
2962                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
2963                         let node_id = {
2964                                 let mut key_slice = [0; 32];
2965                                 rng.fill_bytes(&mut key_slice);
2966                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
2967                         };
2968                         let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger)).unwrap();
2969                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
2970                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router });
2971                 }
2972
2973                 nodes
2974         }
2975
2976         #[test]
2977         fn fake_network_test() {
2978                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2979                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
2980                 let nodes = create_network(4);
2981
2982                 // Create some initial channels
2983                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2984                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2985                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2986
2987                 // Rebalance the network a bit by relaying one payment through all the channels...
2988                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2989                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2990                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2991                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2992
2993                 // Send some more payments
2994                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
2995                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
2996                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
2997
2998                 // Test failure packets
2999                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
3000                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
3001
3002                 // Add a new channel that skips 3
3003                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
3004
3005                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
3006                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
3007                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3008                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3009                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3010                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3011                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3012
3013                 // Do some rebalance loop payments, simultaneously
3014                 let mut hops = Vec::with_capacity(3);
3015                 hops.push(RouteHop {
3016                         pubkey: nodes[2].node.get_our_node_id(),
3017                         short_channel_id: chan_2.0.contents.short_channel_id,
3018                         fee_msat: 0,
3019                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3020                 });
3021                 hops.push(RouteHop {
3022                         pubkey: nodes[3].node.get_our_node_id(),
3023                         short_channel_id: chan_3.0.contents.short_channel_id,
3024                         fee_msat: 0,
3025                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3026                 });
3027                 hops.push(RouteHop {
3028                         pubkey: nodes[1].node.get_our_node_id(),
3029                         short_channel_id: chan_4.0.contents.short_channel_id,
3030                         fee_msat: 1000000,
3031                         cltv_expiry_delta: TEST_FINAL_CLTV,
3032                 });
3033                 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
3034                 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
3035                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3036
3037                 let mut hops = Vec::with_capacity(3);
3038                 hops.push(RouteHop {
3039                         pubkey: nodes[3].node.get_our_node_id(),
3040                         short_channel_id: chan_4.0.contents.short_channel_id,
3041                         fee_msat: 0,
3042                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3043                 });
3044                 hops.push(RouteHop {
3045                         pubkey: nodes[2].node.get_our_node_id(),
3046                         short_channel_id: chan_3.0.contents.short_channel_id,
3047                         fee_msat: 0,
3048                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3049                 });
3050                 hops.push(RouteHop {
3051                         pubkey: nodes[1].node.get_our_node_id(),
3052                         short_channel_id: chan_2.0.contents.short_channel_id,
3053                         fee_msat: 1000000,
3054                         cltv_expiry_delta: TEST_FINAL_CLTV,
3055                 });
3056                 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
3057                 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
3058                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3059
3060                 // Claim the rebalances...
3061                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3062                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3063
3064                 // Add a duplicate new channel from 2 to 4
3065                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3066
3067                 // Send some payments across both channels
3068                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3069                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3070                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3071
3072                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3073
3074                 //TODO: Test that routes work again here as we've been notified that the channel is full
3075
3076                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3077                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3078                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3079
3080                 // Close down the channels...
3081                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3082                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3083                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3084                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3085                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3086
3087                 // Check that we processed all pending events
3088                 for node in nodes {
3089                         assert_eq!(node.node.get_and_clear_pending_events().len(), 0);
3090                         assert_eq!(node.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3091                 }
3092         }
3093
3094         #[derive(PartialEq)]
3095         enum HTLCType { NONE, TIMEOUT, SUCCESS }
3096         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
3097                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3098                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
3099
3100                 let mut res = Vec::with_capacity(2);
3101
3102                 if let Some(explicit_tx) = commitment_tx {
3103                         res.push(explicit_tx.clone());
3104                 } else {
3105                         for tx in node_txn.iter() {
3106                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
3107                                         let mut funding_tx_map = HashMap::new();
3108                                         funding_tx_map.insert(chan.3.txid(), chan.3.clone());
3109                                         tx.verify(&funding_tx_map).unwrap();
3110                                         res.push(tx.clone());
3111                                 }
3112                         }
3113                 }
3114                 assert_eq!(res.len(), 1);
3115
3116                 if has_htlc_tx != HTLCType::NONE {
3117                         for tx in node_txn.iter() {
3118                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
3119                                         let mut funding_tx_map = HashMap::new();
3120                                         funding_tx_map.insert(res[0].txid(), res[0].clone());
3121                                         tx.verify(&funding_tx_map).unwrap();
3122                                         if has_htlc_tx == HTLCType::TIMEOUT {
3123                                                 assert!(tx.lock_time != 0);
3124                                         } else {
3125                                                 assert!(tx.lock_time == 0);
3126                                         }
3127                                         res.push(tx.clone());
3128                                         break;
3129                                 }
3130                         }
3131                         assert_eq!(res.len(), 2);
3132                 }
3133                 node_txn.clear();
3134                 res
3135         }
3136
3137         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
3138                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3139
3140                 assert!(node_txn.len() >= 1);
3141                 assert_eq!(node_txn[0].input.len(), 1);
3142                 let mut found_prev = false;
3143
3144                 for tx in prev_txn {
3145                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
3146                                 let mut funding_tx_map = HashMap::new();
3147                                 funding_tx_map.insert(tx.txid(), tx.clone());
3148                                 node_txn[0].verify(&funding_tx_map).unwrap();
3149
3150                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
3151                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
3152
3153                                 found_prev = true;
3154                                 break;
3155                         }
3156                 }
3157                 assert!(found_prev);
3158
3159                 let mut res = Vec::new();
3160                 mem::swap(&mut *node_txn, &mut res);
3161                 res
3162         }
3163
3164         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
3165                 let events_1 = nodes[a].node.get_and_clear_pending_events();
3166                 assert_eq!(events_1.len(), 1);
3167                 let as_update = match events_1[0] {
3168                         Event::BroadcastChannelUpdate { ref msg } => {
3169                                 msg.clone()
3170                         },
3171                         _ => panic!("Unexpected event"),
3172                 };
3173
3174                 let events_2 = nodes[b].node.get_and_clear_pending_events();
3175                 assert_eq!(events_2.len(), 1);
3176                 let bs_update = match events_2[0] {
3177                         Event::BroadcastChannelUpdate { ref msg } => {
3178                                 msg.clone()
3179                         },
3180                         _ => panic!("Unexpected event"),
3181                 };
3182
3183                 for node in nodes {
3184                         node.router.handle_channel_update(&as_update).unwrap();
3185                         node.router.handle_channel_update(&bs_update).unwrap();
3186                 }
3187         }
3188
3189         #[test]
3190         fn channel_monitor_network_test() {
3191                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3192                 // tests that ChannelMonitor is able to recover from various states.
3193                 let nodes = create_network(5);
3194
3195                 // Create some initial channels
3196                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3197                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3198                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3199                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
3200
3201                 // Rebalance the network a bit by relaying one payment through all the channels...
3202                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3203                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3204                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3205                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3206
3207                 // Simple case with no pending HTLCs:
3208                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
3209                 {
3210                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
3211                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3212                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3213                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
3214                 }
3215                 get_announce_close_broadcast_events(&nodes, 0, 1);
3216                 assert_eq!(nodes[0].node.list_channels().len(), 0);
3217                 assert_eq!(nodes[1].node.list_channels().len(), 1);
3218
3219                 // One pending HTLC is discarded by the force-close:
3220                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
3221
3222                 // Simple case of one pending HTLC to HTLC-Timeout
3223                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
3224                 {
3225                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
3226                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3227                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3228                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
3229                 }
3230                 get_announce_close_broadcast_events(&nodes, 1, 2);
3231                 assert_eq!(nodes[1].node.list_channels().len(), 0);
3232                 assert_eq!(nodes[2].node.list_channels().len(), 1);
3233
3234                 macro_rules! claim_funds {
3235                         ($node: expr, $prev_node: expr, $preimage: expr) => {
3236                                 {
3237                                         assert!($node.node.claim_funds($preimage));
3238                                         {
3239                                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3240                                                 assert_eq!(added_monitors.len(), 1);
3241                                                 added_monitors.clear();
3242                                         }
3243
3244                                         let events = $node.node.get_and_clear_pending_events();
3245                                         assert_eq!(events.len(), 1);
3246                                         match events[0] {
3247                                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
3248                                                         assert!(update_add_htlcs.is_empty());
3249                                                         assert!(update_fail_htlcs.is_empty());
3250                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
3251                                                 },
3252                                                 _ => panic!("Unexpected event"),
3253                                         };
3254                                 }
3255                         }
3256                 }
3257
3258                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
3259                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
3260                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
3261                 {
3262                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
3263
3264                         // Claim the payment on nodes[3], giving it knowledge of the preimage
3265                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
3266
3267                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3268                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
3269
3270                         check_preimage_claim(&nodes[3], &node_txn);
3271                 }
3272                 get_announce_close_broadcast_events(&nodes, 2, 3);
3273                 assert_eq!(nodes[2].node.list_channels().len(), 0);
3274                 assert_eq!(nodes[3].node.list_channels().len(), 1);
3275
3276                 // One pending HTLC to time out:
3277                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
3278
3279                 {
3280                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3281                         nodes[3].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3282                         for i in 2..TEST_FINAL_CLTV - 3 {
3283                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3284                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3285                         }
3286
3287                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
3288
3289                         // Claim the payment on nodes[3], giving it knowledge of the preimage
3290                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
3291
3292                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3293                         nodes[4].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3294                         for i in 2..TEST_FINAL_CLTV - 3 {
3295                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3296                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3297                         }
3298
3299                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
3300
3301                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3302                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
3303
3304                         check_preimage_claim(&nodes[4], &node_txn);
3305                 }
3306                 get_announce_close_broadcast_events(&nodes, 3, 4);
3307                 assert_eq!(nodes[3].node.list_channels().len(), 0);
3308                 assert_eq!(nodes[4].node.list_channels().len(), 0);
3309
3310                 // Create some new channels:
3311                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
3312
3313                 // A pending HTLC which will be revoked:
3314                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3315                 // Get the will-be-revoked local txn from nodes[0]
3316                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3317                 // Revoke the old state
3318                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
3319
3320                 {
3321                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3322                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3323                         {
3324                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3325                                 assert_eq!(node_txn.len(), 2);
3326                                 assert_eq!(node_txn[0].input.len(), 1);
3327
3328                                 let mut funding_tx_map = HashMap::new();
3329                                 funding_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
3330                                 node_txn[0].verify(&funding_tx_map).unwrap();
3331                                 node_txn.swap_remove(0);
3332                         }
3333                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
3334
3335                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3336                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
3337                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3338                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
3339
3340                         //TODO: At this point nodes[1] should claim the revoked HTLC-Timeout output, but that's
3341                         //not yet implemented in ChannelMonitor
3342                 }
3343                 get_announce_close_broadcast_events(&nodes, 0, 1);
3344                 assert_eq!(nodes[0].node.list_channels().len(), 0);
3345                 assert_eq!(nodes[1].node.list_channels().len(), 0);
3346
3347                 // Check that we processed all pending events
3348                 for node in nodes {
3349                         assert_eq!(node.node.get_and_clear_pending_events().len(), 0);
3350                         assert_eq!(node.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3351                 }
3352         }
3353
3354         #[test]
3355         fn test_unconf_chan() {
3356                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3357                 let nodes = create_network(2);
3358                 create_announced_chan_between_nodes(&nodes, 0, 1);
3359
3360                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3361                 assert_eq!(channel_state.by_id.len(), 1);
3362                 assert_eq!(channel_state.short_to_id.len(), 1);
3363                 mem::drop(channel_state);
3364
3365                 let mut headers = Vec::new();
3366                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3367                 headers.push(header.clone());
3368                 for _i in 2..100 {
3369                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3370                         headers.push(header.clone());
3371                 }
3372                 while !headers.is_empty() {
3373                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
3374                 }
3375                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3376                 assert_eq!(channel_state.by_id.len(), 0);
3377                 assert_eq!(channel_state.short_to_id.len(), 0);
3378         }
3379
3380         #[test]
3381         fn test_invalid_channel_announcement() {
3382                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3383                 let secp_ctx = Secp256k1::new();
3384                 let nodes = create_network(2);
3385
3386                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
3387
3388                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3389                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3390                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3391                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3392
3393                 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap() } );
3394
3395                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3396                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3397
3398                 let as_network_key = nodes[0].node.get_our_node_id();
3399                 let bs_network_key = nodes[1].node.get_our_node_id();
3400
3401                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3402
3403                 let mut chan_announcement;
3404
3405                 macro_rules! dummy_unsigned_msg {
3406                         () => {
3407                                 msgs::UnsignedChannelAnnouncement {
3408                                         features: msgs::GlobalFeatures::new(),
3409                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3410                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
3411                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3412                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3413                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3414                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3415                                         excess_data: Vec::new(),
3416                                 };
3417                         }
3418                 }
3419
3420                 macro_rules! sign_msg {
3421                         ($unsigned_msg: expr) => {
3422                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
3423                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3424                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3425                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
3426                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
3427                                 chan_announcement = msgs::ChannelAnnouncement {
3428                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3429                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3430                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3431                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3432                                         contents: $unsigned_msg
3433                                 }
3434                         }
3435                 }
3436
3437                 let unsigned_msg = dummy_unsigned_msg!();
3438                 sign_msg!(unsigned_msg);
3439                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3440                 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap() } );
3441
3442                 // Configured with Network::Testnet
3443                 let mut unsigned_msg = dummy_unsigned_msg!();
3444                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3445                 sign_msg!(unsigned_msg);
3446                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3447
3448                 let mut unsigned_msg = dummy_unsigned_msg!();
3449                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
3450                 sign_msg!(unsigned_msg);
3451                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3452         }
3453 }