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