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