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