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