Error handling in decoding onion
[rust-lightning] / src / ln / channelmanager.rs
1 //! The top-level channel management and payment tracking stuff lives here.
2 //!
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
6 //!
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
10
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::network::serialize::BitcoinHash;
16 use bitcoin::util::hash::Sha256dHash;
17
18 use secp256k1::key::{SecretKey,PublicKey};
19 use secp256k1::{Secp256k1,Message};
20 use secp256k1::ecdh::SharedSecret;
21 use secp256k1;
22
23 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
24 use chain::transaction::OutPoint;
25 use ln::channel::{Channel, ChannelError, ChannelKeys};
26 use ln::channelmonitor::{ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
27 use ln::router::{Route,RouteHop};
28 use ln::msgs;
29 use ln::msgs::{HandleError,ChannelMessageHandler};
30 use util::{byte_utils, events, internal_traits, rng};
31 use util::sha2::Sha256;
32 use util::ser::{Readable, Writeable};
33 use util::chacha20poly1305rfc::ChaCha20;
34 use util::logger::Logger;
35 use util::errors::APIError;
36
37 use crypto;
38 use crypto::mac::{Mac,MacResult};
39 use crypto::hmac::Hmac;
40 use crypto::digest::Digest;
41 use crypto::symmetriccipher::SynchronousStreamCipher;
42
43 use std::{ptr, mem};
44 use std::collections::HashMap;
45 use std::collections::hash_map;
46 use std::io::Cursor;
47 use std::sync::{Mutex,MutexGuard,Arc};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use secp256k1::key::SecretKey;
67         use secp256k1::ecdh::SharedSecret;
68
69         /// Stores the info we will need to send when we want to forward an HTLC onwards
70         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71         pub struct PendingForwardHTLCInfo {
72                 pub(super) onion_packet: Option<msgs::OnionPacket>,
73                 pub(super) incoming_shared_secret: SharedSecret,
74                 pub(super) payment_hash: [u8; 32],
75                 pub(super) short_channel_id: u64,
76                 pub(super) amt_to_forward: u64,
77                 pub(super) outgoing_cltv_value: u32,
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailureMsg {
82                 Relay(msgs::UpdateFailHTLC),
83                 Malformed(msgs::UpdateFailMalformedHTLC),
84         }
85
86         /// Stores whether we can't forward an HTLC or relevant forwarding info
87         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88         pub enum PendingHTLCStatus {
89                 Forward(PendingForwardHTLCInfo),
90                 Fail(HTLCFailureMsg),
91         }
92
93         /// Tracks the inbound corresponding to an outbound HTLC
94         #[derive(Clone)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: SharedSecret,
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                 },
109         }
110         #[cfg(test)]
111         impl HTLCSource {
112                 pub fn dummy() -> Self {
113                         HTLCSource::OutboundRoute {
114                                 route: Route { hops: Vec::new() },
115                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
116                         }
117                 }
118         }
119
120         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
121         pub(crate) enum HTLCFailReason {
122                 ErrorPacket {
123                         err: msgs::OnionErrorPacket,
124                 },
125                 Reason {
126                         failure_code: u16,
127                         data: Vec<u8>,
128                 }
129         }
130 }
131 pub(super) use self::channel_held_info::*;
132
133 struct MsgHandleErrInternal {
134         err: msgs::HandleError,
135         needs_channel_force_close: bool,
136 }
137 impl MsgHandleErrInternal {
138         #[inline]
139         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
140                 Self {
141                         err: HandleError {
142                                 err,
143                                 action: Some(msgs::ErrorAction::SendErrorMessage {
144                                         msg: msgs::ErrorMessage {
145                                                 channel_id,
146                                                 data: err.to_string()
147                                         },
148                                 }),
149                         },
150                         needs_channel_force_close: false,
151                 }
152         }
153         #[inline]
154         fn send_err_msg_close_chan(err: &'static str, channel_id: [u8; 32]) -> Self {
155                 Self {
156                         err: HandleError {
157                                 err,
158                                 action: Some(msgs::ErrorAction::SendErrorMessage {
159                                         msg: msgs::ErrorMessage {
160                                                 channel_id,
161                                                 data: err.to_string()
162                                         },
163                                 }),
164                         },
165                         needs_channel_force_close: true,
166                 }
167         }
168         #[inline]
169         fn from_maybe_close(err: msgs::HandleError) -> Self {
170                 Self { err, needs_channel_force_close: true }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, needs_channel_force_close: false }
175         }
176         #[inline]
177         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
178                 Self {
179                         err: match err {
180                                 ChannelError::Ignore(msg) => HandleError {
181                                         err: msg,
182                                         action: Some(msgs::ErrorAction::IgnoreError),
183                                 },
184                                 ChannelError::Close(msg) => HandleError {
185                                         err: msg,
186                                         action: Some(msgs::ErrorAction::SendErrorMessage {
187                                                 msg: msgs::ErrorMessage {
188                                                         channel_id,
189                                                         data: msg.to_string()
190                                                 },
191                                         }),
192                                 },
193                         },
194                         needs_channel_force_close: false,
195                 }
196         }
197         #[inline]
198         fn from_chan_maybe_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
199                 Self {
200                         err: match err {
201                                 ChannelError::Ignore(msg) => HandleError {
202                                         err: msg,
203                                         action: Some(msgs::ErrorAction::IgnoreError),
204                                 },
205                                 ChannelError::Close(msg) => HandleError {
206                                         err: msg,
207                                         action: Some(msgs::ErrorAction::SendErrorMessage {
208                                                 msg: msgs::ErrorMessage {
209                                                         channel_id,
210                                                         data: msg.to_string()
211                                                 },
212                                         }),
213                                 },
214                         },
215                         needs_channel_force_close: true,
216                 }
217         }
218 }
219
220 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
221 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
222 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
223 /// probably increase this significantly.
224 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
225
226 struct HTLCForwardInfo {
227         prev_short_channel_id: u64,
228         prev_htlc_id: u64,
229         forward_info: PendingForwardHTLCInfo,
230 }
231
232 struct ChannelHolder {
233         by_id: HashMap<[u8; 32], Channel>,
234         short_to_id: HashMap<u64, [u8; 32]>,
235         next_forward: Instant,
236         /// short channel id -> forward infos. Key of 0 means payments received
237         /// Note that while this is held in the same mutex as the channels themselves, no consistency
238         /// guarantees are made about there existing a channel with the short id here, nor the short
239         /// ids in the PendingForwardHTLCInfo!
240         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
241         /// Note that while this is held in the same mutex as the channels themselves, no consistency
242         /// guarantees are made about the channels given here actually existing anymore by the time you
243         /// go to read them!
244         claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
245 }
246 struct MutChannelHolder<'a> {
247         by_id: &'a mut HashMap<[u8; 32], Channel>,
248         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
249         next_forward: &'a mut Instant,
250         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
251         claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
252 }
253 impl ChannelHolder {
254         fn borrow_parts(&mut self) -> MutChannelHolder {
255                 MutChannelHolder {
256                         by_id: &mut self.by_id,
257                         short_to_id: &mut self.short_to_id,
258                         next_forward: &mut self.next_forward,
259                         forward_htlcs: &mut self.forward_htlcs,
260                         claimable_htlcs: &mut self.claimable_htlcs,
261                 }
262         }
263 }
264
265 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
266 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
267
268 /// Manager which keeps track of a number of channels and sends messages to the appropriate
269 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
270 ///
271 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
272 /// to individual Channels.
273 pub struct ChannelManager {
274         genesis_hash: Sha256dHash,
275         fee_estimator: Arc<FeeEstimator>,
276         monitor: Arc<ManyChannelMonitor>,
277         chain_monitor: Arc<ChainWatchInterface>,
278         tx_broadcaster: Arc<BroadcasterInterface>,
279
280         announce_channels_publicly: bool,
281         fee_proportional_millionths: u32,
282         latest_block_height: AtomicUsize,
283         secp_ctx: Secp256k1<secp256k1::All>,
284
285         channel_state: Mutex<ChannelHolder>,
286         our_network_key: SecretKey,
287
288         pending_events: Mutex<Vec<events::Event>>,
289
290         logger: Arc<Logger>,
291 }
292
293 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
294 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
295 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
296 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
297 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
298 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
299 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
300
301 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
302 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
303 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
304 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
305 #[deny(const_err)]
306 #[allow(dead_code)]
307 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
308
309 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
310 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
311 #[deny(const_err)]
312 #[allow(dead_code)]
313 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
314
315 macro_rules! secp_call {
316         ( $res: expr, $err: expr ) => {
317                 match $res {
318                         Ok(key) => key,
319                         Err(_) => return Err($err),
320                 }
321         };
322 }
323
324 struct OnionKeys {
325         #[cfg(test)]
326         shared_secret: SharedSecret,
327         #[cfg(test)]
328         blinding_factor: [u8; 32],
329         ephemeral_pubkey: PublicKey,
330         rho: [u8; 32],
331         mu: [u8; 32],
332 }
333
334 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
335 pub struct ChannelDetails {
336         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
337         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
338         /// Note that this means this value is *not* persistent - it can change once during the
339         /// lifetime of the channel.
340         pub channel_id: [u8; 32],
341         /// The position of the funding transaction in the chain. None if the funding transaction has
342         /// not yet been confirmed and the channel fully opened.
343         pub short_channel_id: Option<u64>,
344         /// The node_id of our counterparty
345         pub remote_network_id: PublicKey,
346         /// The value, in satoshis, of this channel as appears in the funding output
347         pub channel_value_satoshis: u64,
348         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
349         pub user_id: u64,
350 }
351
352 impl ChannelManager {
353         /// Constructs a new ChannelManager to hold several channels and route between them.
354         ///
355         /// This is the main "logic hub" for all channel-related actions, and implements
356         /// ChannelMessageHandler.
357         ///
358         /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
359         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
360         ///
361         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
362         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> {
363                 let secp_ctx = Secp256k1::new();
364
365                 let res = Arc::new(ChannelManager {
366                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
367                         fee_estimator: feeest.clone(),
368                         monitor: monitor.clone(),
369                         chain_monitor,
370                         tx_broadcaster,
371
372                         announce_channels_publicly,
373                         fee_proportional_millionths,
374                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
375                         secp_ctx,
376
377                         channel_state: Mutex::new(ChannelHolder{
378                                 by_id: HashMap::new(),
379                                 short_to_id: HashMap::new(),
380                                 next_forward: Instant::now(),
381                                 forward_htlcs: HashMap::new(),
382                                 claimable_htlcs: HashMap::new(),
383                         }),
384                         our_network_key,
385
386                         pending_events: Mutex::new(Vec::new()),
387
388                         logger,
389                 });
390                 let weak_res = Arc::downgrade(&res);
391                 res.chain_monitor.register_listener(weak_res);
392                 Ok(res)
393         }
394
395         /// Creates a new outbound channel to the given remote node and with the given value.
396         ///
397         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
398         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
399         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
400         /// may wish to avoid using 0 for user_id here.
401         ///
402         /// If successful, will generate a SendOpenChannel event, so you should probably poll
403         /// PeerManager::process_events afterwards.
404         ///
405         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
406         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
407                 let chan_keys = if cfg!(feature = "fuzztarget") {
408                         ChannelKeys {
409                                 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(),
410                                 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(),
411                                 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(),
412                                 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(),
413                                 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(),
414                                 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(),
415                                 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(),
416                                 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],
417                         }
418                 } else {
419                         let mut key_seed = [0u8; 32];
420                         rng::fill_bytes(&mut key_seed);
421                         match ChannelKeys::new_from_seed(&key_seed) {
422                                 Ok(key) => key,
423                                 Err(_) => panic!("RNG is busted!")
424                         }
425                 };
426
427                 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))?;
428                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
429                 let mut channel_state = self.channel_state.lock().unwrap();
430                 match channel_state.by_id.entry(channel.channel_id()) {
431                         hash_map::Entry::Occupied(_) => {
432                                 if cfg!(feature = "fuzztarget") {
433                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
434                                 } else {
435                                         panic!("RNG is bad???");
436                                 }
437                         },
438                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
439                 }
440
441                 let mut events = self.pending_events.lock().unwrap();
442                 events.push(events::Event::SendOpenChannel {
443                         node_id: their_network_key,
444                         msg: res,
445                 });
446                 Ok(())
447         }
448
449         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
450         /// more information.
451         pub fn list_channels(&self) -> Vec<ChannelDetails> {
452                 let channel_state = self.channel_state.lock().unwrap();
453                 let mut res = Vec::with_capacity(channel_state.by_id.len());
454                 for (channel_id, channel) in channel_state.by_id.iter() {
455                         res.push(ChannelDetails {
456                                 channel_id: (*channel_id).clone(),
457                                 short_channel_id: channel.get_short_channel_id(),
458                                 remote_network_id: channel.get_their_node_id(),
459                                 channel_value_satoshis: channel.get_value_satoshis(),
460                                 user_id: channel.get_user_id(),
461                         });
462                 }
463                 res
464         }
465
466         /// Gets the list of usable channels, in random order. Useful as an argument to
467         /// Router::get_route to ensure non-announced channels are used.
468         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
469                 let channel_state = self.channel_state.lock().unwrap();
470                 let mut res = Vec::with_capacity(channel_state.by_id.len());
471                 for (channel_id, channel) in channel_state.by_id.iter() {
472                         // Note we use is_live here instead of usable which leads to somewhat confused
473                         // internal/external nomenclature, but that's ok cause that's probably what the user
474                         // really wanted anyway.
475                         if channel.is_live() {
476                                 res.push(ChannelDetails {
477                                         channel_id: (*channel_id).clone(),
478                                         short_channel_id: channel.get_short_channel_id(),
479                                         remote_network_id: channel.get_their_node_id(),
480                                         channel_value_satoshis: channel.get_value_satoshis(),
481                                         user_id: channel.get_user_id(),
482                                 });
483                         }
484                 }
485                 res
486         }
487
488         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
489         /// will be accepted on the given channel, and after additional timeout/the closing of all
490         /// pending HTLCs, the channel will be closed on chain.
491         ///
492         /// May generate a SendShutdown event on success, which should be relayed.
493         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
494                 let (mut res, node_id, chan_option) = {
495                         let mut channel_state_lock = self.channel_state.lock().unwrap();
496                         let channel_state = channel_state_lock.borrow_parts();
497                         match channel_state.by_id.entry(channel_id.clone()) {
498                                 hash_map::Entry::Occupied(mut chan_entry) => {
499                                         let res = chan_entry.get_mut().get_shutdown()?;
500                                         if chan_entry.get().is_shutdown() {
501                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
502                                                         channel_state.short_to_id.remove(&short_id);
503                                                 }
504                                                 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
505                                         } else { (res, chan_entry.get().get_their_node_id(), None) }
506                                 },
507                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
508                         }
509                 };
510                 for htlc_source in res.1.drain(..) {
511                         // unknown_next_peer...I dunno who that is anymore....
512                         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() });
513                 }
514                 let chan_update = if let Some(chan) = chan_option {
515                         if let Ok(update) = self.get_channel_update(&chan) {
516                                 Some(update)
517                         } else { None }
518                 } else { None };
519
520                 let mut events = self.pending_events.lock().unwrap();
521                 if let Some(update) = chan_update {
522                         events.push(events::Event::BroadcastChannelUpdate {
523                                 msg: update
524                         });
525                 }
526                 events.push(events::Event::SendShutdown {
527                         node_id,
528                         msg: res.0
529                 });
530
531                 Ok(())
532         }
533
534         #[inline]
535         fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>)) {
536                 let (local_txn, mut failed_htlcs) = shutdown_res;
537                 for htlc_source in failed_htlcs.drain(..) {
538                         // unknown_next_peer...I dunno who that is anymore....
539                         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() });
540                 }
541                 for tx in local_txn {
542                         self.tx_broadcaster.broadcast_transaction(&tx);
543                 }
544                 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
545                 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
546                 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
547                 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
548                 //timeouts are hit and our claims confirm).
549                 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
550                 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
551         }
552
553         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
554         /// the chain and rejecting new HTLCs on the given channel.
555         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
556                 let mut chan = {
557                         let mut channel_state_lock = self.channel_state.lock().unwrap();
558                         let channel_state = channel_state_lock.borrow_parts();
559                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
560                                 if let Some(short_id) = chan.get_short_channel_id() {
561                                         channel_state.short_to_id.remove(&short_id);
562                                 }
563                                 chan
564                         } else {
565                                 return;
566                         }
567                 };
568                 self.finish_force_close_channel(chan.force_shutdown());
569                 let mut events = self.pending_events.lock().unwrap();
570                 if let Ok(update) = self.get_channel_update(&chan) {
571                         events.push(events::Event::BroadcastChannelUpdate {
572                                 msg: update
573                         });
574                 }
575         }
576
577         /// Force close all channels, immediately broadcasting the latest local commitment transaction
578         /// for each to the chain and rejecting new HTLCs on each.
579         pub fn force_close_all_channels(&self) {
580                 for chan in self.list_channels() {
581                         self.force_close_channel(&chan.channel_id);
582                 }
583         }
584
585         #[inline]
586         fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
587                 ({
588                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
589                         hmac.input(&shared_secret[..]);
590                         let mut res = [0; 32];
591                         hmac.raw_result(&mut res);
592                         res
593                 },
594                 {
595                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
596                         hmac.input(&shared_secret[..]);
597                         let mut res = [0; 32];
598                         hmac.raw_result(&mut res);
599                         res
600                 })
601         }
602
603         #[inline]
604         fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
605                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
606                 hmac.input(&shared_secret[..]);
607                 let mut res = [0; 32];
608                 hmac.raw_result(&mut res);
609                 res
610         }
611
612         #[inline]
613         fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
614                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
615                 hmac.input(&shared_secret[..]);
616                 let mut res = [0; 32];
617                 hmac.raw_result(&mut res);
618                 res
619         }
620
621         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
622         #[inline]
623         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> {
624                 let mut blinded_priv = session_priv.clone();
625                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
626
627                 for hop in route.hops.iter() {
628                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
629
630                         let mut sha = Sha256::new();
631                         sha.input(&blinded_pub.serialize()[..]);
632                         sha.input(&shared_secret[..]);
633                         let mut blinding_factor = [0u8; 32];
634                         sha.result(&mut blinding_factor);
635
636                         let ephemeral_pubkey = blinded_pub;
637
638                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
639                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
640
641                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
642                 }
643
644                 Ok(())
645         }
646
647         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
648         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
649                 let mut res = Vec::with_capacity(route.hops.len());
650
651                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
652                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
653
654                         res.push(OnionKeys {
655                                 #[cfg(test)]
656                                 shared_secret,
657                                 #[cfg(test)]
658                                 blinding_factor: _blinding_factor,
659                                 ephemeral_pubkey,
660                                 rho,
661                                 mu,
662                         });
663                 })?;
664
665                 Ok(res)
666         }
667
668         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
669         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
670                 let mut cur_value_msat = 0u64;
671                 let mut cur_cltv = starting_htlc_offset;
672                 let mut last_short_channel_id = 0;
673                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
674                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
675                 unsafe { res.set_len(route.hops.len()); }
676
677                 for (idx, hop) in route.hops.iter().enumerate().rev() {
678                         // First hop gets special values so that it can check, on receipt, that everything is
679                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
680                         // the intended recipient).
681                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
682                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
683                         res[idx] = msgs::OnionHopData {
684                                 realm: 0,
685                                 data: msgs::OnionRealm0HopData {
686                                         short_channel_id: last_short_channel_id,
687                                         amt_to_forward: value_msat,
688                                         outgoing_cltv_value: cltv,
689                                 },
690                                 hmac: [0; 32],
691                         };
692                         cur_value_msat += hop.fee_msat;
693                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
694                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
695                         }
696                         cur_cltv += hop.cltv_expiry_delta as u32;
697                         if cur_cltv >= 500000000 {
698                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
699                         }
700                         last_short_channel_id = hop.short_channel_id;
701                 }
702                 Ok((res, cur_value_msat, cur_cltv))
703         }
704
705         #[inline]
706         fn shift_arr_right(arr: &mut [u8; 20*65]) {
707                 unsafe {
708                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
709                 }
710                 for i in 0..65 {
711                         arr[i] = 0;
712                 }
713         }
714
715         #[inline]
716         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
717                 assert_eq!(dst.len(), src.len());
718
719                 for i in 0..dst.len() {
720                         dst[i] ^= src[i];
721                 }
722         }
723
724         const ZERO:[u8; 21*65] = [0; 21*65];
725         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
726                 let mut buf = Vec::with_capacity(21*65);
727                 buf.resize(21*65, 0);
728
729                 let filler = {
730                         let iters = payloads.len() - 1;
731                         let end_len = iters * 65;
732                         let mut res = Vec::with_capacity(end_len);
733                         res.resize(end_len, 0);
734
735                         for (i, keys) in onion_keys.iter().enumerate() {
736                                 if i == payloads.len() - 1 { continue; }
737                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
738                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
739                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
740                         }
741                         res
742                 };
743
744                 let mut packet_data = [0; 20*65];
745                 let mut hmac_res = [0; 32];
746
747                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
748                         ChannelManager::shift_arr_right(&mut packet_data);
749                         payload.hmac = hmac_res;
750                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
751
752                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
753                         chacha.process(&packet_data, &mut buf[0..20*65]);
754                         packet_data[..].copy_from_slice(&buf[0..20*65]);
755
756                         if i == 0 {
757                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
758                         }
759
760                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
761                         hmac.input(&packet_data);
762                         hmac.input(&associated_data[..]);
763                         hmac.raw_result(&mut hmac_res);
764                 }
765
766                 msgs::OnionPacket{
767                         version: 0,
768                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
769                         hop_data: packet_data,
770                         hmac: hmac_res,
771                 }
772         }
773
774         /// Encrypts a failure packet. raw_packet can either be a
775         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
776         fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
777                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
778
779                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
780                 packet_crypted.resize(raw_packet.len(), 0);
781                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
782                 chacha.process(&raw_packet, &mut packet_crypted[..]);
783                 msgs::OnionErrorPacket {
784                         data: packet_crypted,
785                 }
786         }
787
788         fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
789                 assert!(failure_data.len() <= 256 - 2);
790
791                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
792
793                 let failuremsg = {
794                         let mut res = Vec::with_capacity(2 + failure_data.len());
795                         res.push(((failure_type >> 8) & 0xff) as u8);
796                         res.push(((failure_type >> 0) & 0xff) as u8);
797                         res.extend_from_slice(&failure_data[..]);
798                         res
799                 };
800                 let pad = {
801                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
802                         res.resize(256 - 2 - failure_data.len(), 0);
803                         res
804                 };
805                 let mut packet = msgs::DecodedOnionErrorPacket {
806                         hmac: [0; 32],
807                         failuremsg: failuremsg,
808                         pad: pad,
809                 };
810
811                 let mut hmac = Hmac::new(Sha256::new(), &um);
812                 hmac.input(&packet.encode()[32..]);
813                 hmac.raw_result(&mut packet.hmac);
814
815                 packet
816         }
817
818         #[inline]
819         fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
820                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
821                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
822         }
823
824         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
825                 macro_rules! get_onion_hash {
826                         () => {
827                                 {
828                                         let mut sha = Sha256::new();
829                                         sha.input(&msg.onion_routing_packet.hop_data);
830                                         let mut onion_hash = [0; 32];
831                                         sha.result(&mut onion_hash);
832                                         onion_hash
833                                 }
834                         }
835                 }
836
837                 if let Err(_) = msg.onion_routing_packet.public_key {
838                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
839                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
840                                 channel_id: msg.channel_id,
841                                 htlc_id: msg.htlc_id,
842                                 sha256_of_onion: get_onion_hash!(),
843                                 failure_code: 0x8000 | 0x4000 | 6,
844                         })), self.channel_state.lock().unwrap());
845                 }
846
847                 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
848                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
849
850                 let mut channel_state = None;
851                 macro_rules! return_err {
852                         ($msg: expr, $err_code: expr, $data: expr) => {
853                                 {
854                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
855                                         if channel_state.is_none() {
856                                                 channel_state = Some(self.channel_state.lock().unwrap());
857                                         }
858                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
859                                                 channel_id: msg.channel_id,
860                                                 htlc_id: msg.htlc_id,
861                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
862                                         })), channel_state.unwrap());
863                                 }
864                         }
865                 }
866
867                 if msg.onion_routing_packet.version != 0 {
868                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
869                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
870                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
871                         //receiving node would have to brute force to figure out which version was put in the
872                         //packet by the node that send us the message, in the case of hashing the hop_data, the
873                         //node knows the HMAC matched, so they already know what is there...
874                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
875                 }
876
877                 let mut hmac = Hmac::new(Sha256::new(), &mu);
878                 hmac.input(&msg.onion_routing_packet.hop_data);
879                 hmac.input(&msg.payment_hash);
880                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
881                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
882                 }
883
884                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
885                 let next_hop_data = {
886                         let mut decoded = [0; 65];
887                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
888                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
889                                 Err(err) => {
890                                         let error_code = match err {
891                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
892                                                 _ => 0x2000 | 2, // Should never happen
893                                         };
894                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
895                                 },
896                                 Ok(msg) => msg
897                         }
898                 };
899
900                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
901                                 // OUR PAYMENT!
902                                 // final_expiry_too_soon
903                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
904                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
905                                 }
906                                 // final_incorrect_htlc_amount
907                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
908                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
909                                 }
910                                 // final_incorrect_cltv_expiry
911                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
912                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
913                                 }
914
915                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
916                                 // message, however that would leak that we are the recipient of this payment, so
917                                 // instead we stay symmetric with the forwarding case, only responding (after a
918                                 // delay) once they've send us a commitment_signed!
919
920                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
921                                         onion_packet: None,
922                                         payment_hash: msg.payment_hash.clone(),
923                                         short_channel_id: 0,
924                                         incoming_shared_secret: shared_secret.clone(),
925                                         amt_to_forward: next_hop_data.data.amt_to_forward,
926                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
927                                 })
928                         } else {
929                                 let mut new_packet_data = [0; 20*65];
930                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
931                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
932
933                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
934
935                                 let blinding_factor = {
936                                         let mut sha = Sha256::new();
937                                         sha.input(&new_pubkey.serialize()[..]);
938                                         sha.input(&shared_secret[..]);
939                                         let mut res = [0u8; 32];
940                                         sha.result(&mut res);
941                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
942                                                 Err(_) => {
943                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
944                                                 },
945                                                 Ok(key) => key
946                                         }
947                                 };
948
949                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
950                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
951                                 }
952
953                                 let outgoing_packet = msgs::OnionPacket {
954                                         version: 0,
955                                         public_key: Ok(new_pubkey),
956                                         hop_data: new_packet_data,
957                                         hmac: next_hop_data.hmac.clone(),
958                                 };
959
960                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
961                                         onion_packet: Some(outgoing_packet),
962                                         payment_hash: msg.payment_hash.clone(),
963                                         short_channel_id: next_hop_data.data.short_channel_id,
964                                         incoming_shared_secret: shared_secret.clone(),
965                                         amt_to_forward: next_hop_data.data.amt_to_forward,
966                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
967                                 })
968                         };
969
970                 channel_state = Some(self.channel_state.lock().unwrap());
971                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
972                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
973                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
974                                 let forwarding_id = match id_option {
975                                         None => { // unknown_next_peer
976                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
977                                         },
978                                         Some(id) => id.clone(),
979                                 };
980                                 if let Some((err, code, chan_update)) = loop {
981                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
982
983                                         if !chan.is_live() { // channel_disabled
984                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
985                                         }
986                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
987                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
988                                         }
989                                         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) });
990                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
991                                                 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
992                                         }
993                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
994                                                 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
995                                         }
996                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
997                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
998                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
999                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1000                                         }
1001                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1002                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1003                                         }
1004                                         break None;
1005                                 }
1006                                 {
1007                                         let mut res = Vec::with_capacity(8 + 128);
1008                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1009                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1010                                         }
1011                                         else if code == 0x1000 | 13 {
1012                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1013                                         }
1014                                         if let Some(chan_update) = chan_update {
1015                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1016                                         }
1017                                         return_err!(err, code, &res[..]);
1018                                 }
1019                         }
1020                 }
1021
1022                 (pending_forward_info, channel_state.unwrap())
1023         }
1024
1025         /// only fails if the channel does not yet have an assigned short_id
1026         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1027                 let short_channel_id = match chan.get_short_channel_id() {
1028                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1029                         Some(id) => id,
1030                 };
1031
1032                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1033
1034                 let unsigned = msgs::UnsignedChannelUpdate {
1035                         chain_hash: self.genesis_hash,
1036                         short_channel_id: short_channel_id,
1037                         timestamp: chan.get_channel_update_count(),
1038                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1039                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1040                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1041                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1042                         fee_proportional_millionths: self.fee_proportional_millionths,
1043                         excess_data: Vec::new(),
1044                 };
1045
1046                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1047                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1048
1049                 Ok(msgs::ChannelUpdate {
1050                         signature: sig,
1051                         contents: unsigned
1052                 })
1053         }
1054
1055         /// Sends a payment along a given route.
1056         ///
1057         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1058         /// fields for more info.
1059         ///
1060         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1061         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1062         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1063         /// specified in the last hop in the route! Thus, you should probably do your own
1064         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1065         /// payment") and prevent double-sends yourself.
1066         ///
1067         /// May generate a SendHTLCs event on success, which should be relayed.
1068         ///
1069         /// Raises APIError::RoutError when invalid route or forward parameter
1070         /// (cltv_delta, fee, node public key) is specified
1071         pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1072                 if route.hops.len() < 1 || route.hops.len() > 20 {
1073                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1074                 }
1075                 let our_node_id = self.get_our_node_id();
1076                 for (idx, hop) in route.hops.iter().enumerate() {
1077                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1078                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1079                         }
1080                 }
1081
1082                 let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
1083                         let mut session_key = [0; 32];
1084                         rng::fill_bytes(&mut session_key);
1085                         session_key
1086                 }).expect("RNG is bad!");
1087
1088                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1089
1090                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1091                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1092                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1093                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1094
1095                 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
1096                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1097                         let channel_state = channel_state_lock.borrow_parts();
1098
1099                         let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1100                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1101                                 Some(id) => id.clone(),
1102                         };
1103
1104                         let res = {
1105                                 let chan = channel_state.by_id.get_mut(&id).unwrap();
1106                                 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
1107                                         return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1108                                 }
1109                                 if !chan.is_live() {
1110                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected!"});
1111                                 }
1112                                 chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1113                                         route: route.clone(),
1114                                         session_priv: session_priv.clone(),
1115                                 }, onion_packet).map_err(|he| APIError::ChannelUnavailable{err: he.err})?
1116                         };
1117
1118                         let first_hop_node_id = route.hops.first().unwrap().pubkey;
1119
1120                         match res {
1121                                 Some(msgs) => (first_hop_node_id, msgs),
1122                                 None => return Ok(()),
1123                         }
1124                 };
1125
1126                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1127                         unimplemented!();
1128                 }
1129
1130                 let mut events = self.pending_events.lock().unwrap();
1131                 events.push(events::Event::UpdateHTLCs {
1132                         node_id: first_hop_node_id,
1133                         updates: msgs::CommitmentUpdate {
1134                                 update_add_htlcs: vec![update_add],
1135                                 update_fulfill_htlcs: Vec::new(),
1136                                 update_fail_htlcs: Vec::new(),
1137                                 update_fail_malformed_htlcs: Vec::new(),
1138                                 update_fee: None,
1139                                 commitment_signed,
1140                         },
1141                 });
1142                 Ok(())
1143         }
1144
1145         /// Call this upon creation of a funding transaction for the given channel.
1146         ///
1147         /// Panics if a funding transaction has already been provided for this channel.
1148         ///
1149         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1150         /// be trivially prevented by using unique funding transaction keys per-channel).
1151         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1152                 macro_rules! add_pending_event {
1153                         ($event: expr) => {
1154                                 {
1155                                         let mut pending_events = self.pending_events.lock().unwrap();
1156                                         pending_events.push($event);
1157                                 }
1158                         }
1159                 }
1160
1161                 let (chan, msg, chan_monitor) = {
1162                         let mut channel_state = self.channel_state.lock().unwrap();
1163                         match channel_state.by_id.remove(temporary_channel_id) {
1164                                 Some(mut chan) => {
1165                                         match chan.get_outbound_funding_created(funding_txo) {
1166                                                 Ok(funding_msg) => {
1167                                                         (chan, funding_msg.0, funding_msg.1)
1168                                                 },
1169                                                 Err(e) => {
1170                                                         log_error!(self, "Got bad signatures: {}!", e.err);
1171                                                         mem::drop(channel_state);
1172                                                         add_pending_event!(events::Event::HandleError {
1173                                                                 node_id: chan.get_their_node_id(),
1174                                                                 action: e.action,
1175                                                         });
1176                                                         return;
1177                                                 },
1178                                         }
1179                                 },
1180                                 None => return
1181                         }
1182                 }; // Release channel lock for install_watch_outpoint call,
1183                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1184                         unimplemented!();
1185                 }
1186                 add_pending_event!(events::Event::SendFundingCreated {
1187                         node_id: chan.get_their_node_id(),
1188                         msg: msg,
1189                 });
1190
1191                 let mut channel_state = self.channel_state.lock().unwrap();
1192                 match channel_state.by_id.entry(chan.channel_id()) {
1193                         hash_map::Entry::Occupied(_) => {
1194                                 panic!("Generated duplicate funding txid?");
1195                         },
1196                         hash_map::Entry::Vacant(e) => {
1197                                 e.insert(chan);
1198                         }
1199                 }
1200         }
1201
1202         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1203                 if !chan.should_announce() { return None }
1204
1205                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1206                         Ok(res) => res,
1207                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1208                 };
1209                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1210                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1211
1212                 Some(msgs::AnnouncementSignatures {
1213                         channel_id: chan.channel_id(),
1214                         short_channel_id: chan.get_short_channel_id().unwrap(),
1215                         node_signature: our_node_sig,
1216                         bitcoin_signature: our_bitcoin_sig,
1217                 })
1218         }
1219
1220         /// Processes HTLCs which are pending waiting on random forward delay.
1221         ///
1222         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1223         /// Will likely generate further events.
1224         pub fn process_pending_htlc_forwards(&self) {
1225                 let mut new_events = Vec::new();
1226                 let mut failed_forwards = Vec::new();
1227                 {
1228                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1229                         let channel_state = channel_state_lock.borrow_parts();
1230
1231                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1232                                 return;
1233                         }
1234
1235                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1236                                 if short_chan_id != 0 {
1237                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1238                                                 Some(chan_id) => chan_id.clone(),
1239                                                 None => {
1240                                                         failed_forwards.reserve(pending_forwards.len());
1241                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1242                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1243                                                                         short_channel_id: prev_short_channel_id,
1244                                                                         htlc_id: prev_htlc_id,
1245                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1246                                                                 });
1247                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1248                                                         }
1249                                                         continue;
1250                                                 }
1251                                         };
1252                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1253
1254                                         let mut add_htlc_msgs = Vec::new();
1255                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1256                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1257                                                         short_channel_id: prev_short_channel_id,
1258                                                         htlc_id: prev_htlc_id,
1259                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1260                                                 });
1261                                                 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()) {
1262                                                         Err(_e) => {
1263                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1264                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1265                                                                 continue;
1266                                                         },
1267                                                         Ok(update_add) => {
1268                                                                 match update_add {
1269                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1270                                                                         None => {
1271                                                                                 // Nothing to do here...we're waiting on a remote
1272                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1273                                                                                 // will automatically handle building the update_add_htlc and
1274                                                                                 // commitment_signed messages when we can.
1275                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1276                                                                                 // as we don't really want others relying on us relaying through
1277                                                                                 // this channel currently :/.
1278                                                                         }
1279                                                                 }
1280                                                         }
1281                                                 }
1282                                         }
1283
1284                                         if !add_htlc_msgs.is_empty() {
1285                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1286                                                         Ok(res) => res,
1287                                                         Err(e) => {
1288                                                                 if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1289                                                                 } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1290                                                                 } else {
1291                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1292                                                                 }
1293                                                                 //TODO: Handle...this is bad!
1294                                                                 continue;
1295                                                         },
1296                                                 };
1297                                                 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1298                                                         node_id: forward_chan.get_their_node_id(),
1299                                                         updates: msgs::CommitmentUpdate {
1300                                                                 update_add_htlcs: add_htlc_msgs,
1301                                                                 update_fulfill_htlcs: Vec::new(),
1302                                                                 update_fail_htlcs: Vec::new(),
1303                                                                 update_fail_malformed_htlcs: Vec::new(),
1304                                                                 update_fee: None,
1305                                                                 commitment_signed: commitment_msg,
1306                                                         },
1307                                                 }));
1308                                         }
1309                                 } else {
1310                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1311                                                 let prev_hop_data = HTLCPreviousHopData {
1312                                                         short_channel_id: prev_short_channel_id,
1313                                                         htlc_id: prev_htlc_id,
1314                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1315                                                 };
1316                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1317                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1318                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1319                                                 };
1320                                                 new_events.push((None, events::Event::PaymentReceived {
1321                                                         payment_hash: forward_info.payment_hash,
1322                                                         amt: forward_info.amt_to_forward,
1323                                                 }));
1324                                         }
1325                                 }
1326                         }
1327                 }
1328
1329                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1330                         match update {
1331                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1332                                 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() }),
1333                         };
1334                 }
1335
1336                 if new_events.is_empty() { return }
1337
1338                 new_events.retain(|event| {
1339                         if let &Some(ref monitor) = &event.0 {
1340                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1341                                         unimplemented!();// but def dont push the event...
1342                                 }
1343                         }
1344                         true
1345                 });
1346
1347                 let mut events = self.pending_events.lock().unwrap();
1348                 events.reserve(new_events.len());
1349                 for event in new_events.drain(..) {
1350                         events.push(event.1);
1351                 }
1352         }
1353
1354         /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1355         pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1356                 // TODO: Add ability to return 0x4000|16 (incorrect_payment_amount) if the amount we
1357                 // received is < expected or > 2*expected
1358                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1359                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1360                 if let Some(mut sources) = removed_source {
1361                         for htlc_with_hash in sources.drain(..) {
1362                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1363                                 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() });
1364                         }
1365                         true
1366                 } else { false }
1367         }
1368
1369         /// Fails an HTLC backwards to the sender of it to us.
1370         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1371         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1372         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1373         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1374         /// still-available channels.
1375         fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1376                 match source {
1377                         HTLCSource::OutboundRoute { .. } => {
1378                                 mem::drop(channel_state);
1379
1380                                 let mut pending_events = self.pending_events.lock().unwrap();
1381                                 pending_events.push(events::Event::PaymentFailed {
1382                                         payment_hash: payment_hash.clone()
1383                                 });
1384                         },
1385                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1386                                 let err_packet = match onion_error {
1387                                         HTLCFailReason::Reason { failure_code, data } => {
1388                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1389                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1390                                         },
1391                                         HTLCFailReason::ErrorPacket { err } => {
1392                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1393                                         }
1394                                 };
1395
1396                                 let (node_id, fail_msgs) = {
1397                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1398                                                 Some(chan_id) => chan_id.clone(),
1399                                                 None => return
1400                                         };
1401
1402                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1403                                         match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1404                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1405                                                 Err(_e) => {
1406                                                         //TODO: Do something with e?
1407                                                         return;
1408                                                 },
1409                                         }
1410                                 };
1411
1412                                 match fail_msgs {
1413                                         Some((msg, commitment_msg, chan_monitor)) => {
1414                                                 mem::drop(channel_state);
1415
1416                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1417                                                         unimplemented!();// but def dont push the event...
1418                                                 }
1419
1420                                                 let mut pending_events = self.pending_events.lock().unwrap();
1421                                                 pending_events.push(events::Event::UpdateHTLCs {
1422                                                         node_id,
1423                                                         updates: msgs::CommitmentUpdate {
1424                                                                 update_add_htlcs: Vec::new(),
1425                                                                 update_fulfill_htlcs: Vec::new(),
1426                                                                 update_fail_htlcs: vec![msg],
1427                                                                 update_fail_malformed_htlcs: Vec::new(),
1428                                                                 update_fee: None,
1429                                                                 commitment_signed: commitment_msg,
1430                                                         },
1431                                                 });
1432                                         },
1433                                         None => {},
1434                                 }
1435                         },
1436                 }
1437         }
1438
1439         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1440         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1441         /// should probably kick the net layer to go send messages if this returns true!
1442         ///
1443         /// May panic if called except in response to a PaymentReceived event.
1444         pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1445                 let mut sha = Sha256::new();
1446                 sha.input(&payment_preimage);
1447                 let mut payment_hash = [0; 32];
1448                 sha.result(&mut payment_hash);
1449
1450                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1451                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1452                 if let Some(mut sources) = removed_source {
1453                         for htlc_with_hash in sources.drain(..) {
1454                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1455                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1456                         }
1457                         true
1458                 } else { false }
1459         }
1460         fn claim_funds_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1461                 match source {
1462                         HTLCSource::OutboundRoute { .. } => {
1463                                 mem::drop(channel_state);
1464                                 let mut pending_events = self.pending_events.lock().unwrap();
1465                                 pending_events.push(events::Event::PaymentSent {
1466                                         payment_preimage
1467                                 });
1468                         },
1469                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1470                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1471                                 let (node_id, fulfill_msgs) = {
1472                                         let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1473                                                 Some(chan_id) => chan_id.clone(),
1474                                                 None => {
1475                                                         // TODO: There is probably a channel manager somewhere that needs to
1476                                                         // learn the preimage as the channel already hit the chain and that's
1477                                                         // why its missing.
1478                                                         return
1479                                                 }
1480                                         };
1481
1482                                         let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1483                                         match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1484                                                 Ok(msg) => (chan.get_their_node_id(), msg),
1485                                                 Err(_e) => {
1486                                                         // TODO: There is probably a channel manager somewhere that needs to
1487                                                         // learn the preimage as the channel may be about to hit the chain.
1488                                                         //TODO: Do something with e?
1489                                                         return
1490                                                 },
1491                                         }
1492                                 };
1493
1494                                 mem::drop(channel_state);
1495                                 if let Some(chan_monitor) = fulfill_msgs.1 {
1496                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1497                                                 unimplemented!();// but def dont push the event...
1498                                         }
1499                                 }
1500
1501                                 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1502                                         let mut pending_events = self.pending_events.lock().unwrap();
1503                                         pending_events.push(events::Event::UpdateHTLCs {
1504                                                 node_id: node_id,
1505                                                 updates: msgs::CommitmentUpdate {
1506                                                         update_add_htlcs: Vec::new(),
1507                                                         update_fulfill_htlcs: vec![msg],
1508                                                         update_fail_htlcs: Vec::new(),
1509                                                         update_fail_malformed_htlcs: Vec::new(),
1510                                                         update_fee: None,
1511                                                         commitment_signed: commitment_msg,
1512                                                 }
1513                                         });
1514                                 }
1515                         },
1516                 }
1517         }
1518
1519         /// Gets the node_id held by this ChannelManager
1520         pub fn get_our_node_id(&self) -> PublicKey {
1521                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1522         }
1523
1524         /// Used to restore channels to normal operation after a
1525         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1526         /// operation.
1527         pub fn test_restore_channel_monitor(&self) {
1528                 unimplemented!();
1529         }
1530
1531         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1532                 if msg.chain_hash != self.genesis_hash {
1533                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1534                 }
1535                 let mut channel_state = self.channel_state.lock().unwrap();
1536                 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1537                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1538                 }
1539
1540                 let chan_keys = if cfg!(feature = "fuzztarget") {
1541                         ChannelKeys {
1542                                 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(),
1543                                 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(),
1544                                 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(),
1545                                 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(),
1546                                 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(),
1547                                 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(),
1548                                 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(),
1549                                 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],
1550                         }
1551                 } else {
1552                         let mut key_seed = [0u8; 32];
1553                         rng::fill_bytes(&mut key_seed);
1554                         match ChannelKeys::new_from_seed(&key_seed) {
1555                                 Ok(key) => key,
1556                                 Err(_) => panic!("RNG is busted!")
1557                         }
1558                 };
1559
1560                 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))
1561                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1562                 let accept_msg = channel.get_accept_channel();
1563                 channel_state.by_id.insert(channel.channel_id(), channel);
1564                 Ok(accept_msg)
1565         }
1566
1567         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1568                 let (value, output_script, user_id) = {
1569                         let mut channel_state = self.channel_state.lock().unwrap();
1570                         match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1571                                 Some(chan) => {
1572                                         if chan.get_their_node_id() != *their_node_id {
1573                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1574                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1575                                         }
1576                                         chan.accept_channel(&msg)
1577                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.temporary_channel_id))?;
1578                                         (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1579                                 },
1580                                 //TODO: same as above
1581                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1582                         }
1583                 };
1584                 let mut pending_events = self.pending_events.lock().unwrap();
1585                 pending_events.push(events::Event::FundingGenerationReady {
1586                         temporary_channel_id: msg.temporary_channel_id,
1587                         channel_value_satoshis: value,
1588                         output_script: output_script,
1589                         user_channel_id: user_id,
1590                 });
1591                 Ok(())
1592         }
1593
1594         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1595                 let (chan, funding_msg, monitor_update) = {
1596                         let mut channel_state = self.channel_state.lock().unwrap();
1597                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1598                                 hash_map::Entry::Occupied(mut chan) => {
1599                                         if chan.get().get_their_node_id() != *their_node_id {
1600                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1601                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1602                                         }
1603                                         match chan.get_mut().funding_created(msg) {
1604                                                 Ok((funding_msg, monitor_update)) => {
1605                                                         (chan.remove(), funding_msg, monitor_update)
1606                                                 },
1607                                                 Err(e) => {
1608                                                         return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1609                                                 }
1610                                         }
1611                                 },
1612                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1613                         }
1614                 }; // Release channel lock for install_watch_outpoint call,
1615                    // note that this means if the remote end is misbehaving and sends a message for the same
1616                    // channel back-to-back with funding_created, we'll end up thinking they sent a message
1617                    // for a bogus channel.
1618                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1619                         unimplemented!();
1620                 }
1621                 let mut channel_state = self.channel_state.lock().unwrap();
1622                 match channel_state.by_id.entry(funding_msg.channel_id) {
1623                         hash_map::Entry::Occupied(_) => {
1624                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1625                         },
1626                         hash_map::Entry::Vacant(e) => {
1627                                 e.insert(chan);
1628                         }
1629                 }
1630                 Ok(funding_msg)
1631         }
1632
1633         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1634                 let (funding_txo, user_id, monitor) = {
1635                         let mut channel_state = self.channel_state.lock().unwrap();
1636                         match channel_state.by_id.get_mut(&msg.channel_id) {
1637                                 Some(chan) => {
1638                                         if chan.get_their_node_id() != *their_node_id {
1639                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1640                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1641                                         }
1642                                         let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1643                                         (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1644                                 },
1645                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1646                         }
1647                 };
1648                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1649                         unimplemented!();
1650                 }
1651                 let mut pending_events = self.pending_events.lock().unwrap();
1652                 pending_events.push(events::Event::FundingBroadcastSafe {
1653                         funding_txo: funding_txo,
1654                         user_channel_id: user_id,
1655                 });
1656                 Ok(())
1657         }
1658
1659         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1660                 let mut channel_state = self.channel_state.lock().unwrap();
1661                 match channel_state.by_id.get_mut(&msg.channel_id) {
1662                         Some(chan) => {
1663                                 if chan.get_their_node_id() != *their_node_id {
1664                                         //TODO: here and below MsgHandleErrInternal, #153 case
1665                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1666                                 }
1667                                 chan.funding_locked(&msg)
1668                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1669                                 return Ok(self.get_announcement_sigs(chan));
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_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1676                 let (mut res, chan_option) = {
1677                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1678                         let channel_state = channel_state_lock.borrow_parts();
1679
1680                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1681                                 hash_map::Entry::Occupied(mut chan_entry) => {
1682                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1683                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1684                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1685                                         }
1686                                         let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1687                                         if chan_entry.get().is_shutdown() {
1688                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1689                                                         channel_state.short_to_id.remove(&short_id);
1690                                                 }
1691                                                 (res, Some(chan_entry.remove_entry().1))
1692                                         } else { (res, None) }
1693                                 },
1694                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1695                         }
1696                 };
1697                 for htlc_source in res.2.drain(..) {
1698                         // unknown_next_peer...I dunno who that is anymore....
1699                         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() });
1700                 }
1701                 if let Some(chan) = chan_option {
1702                         if let Ok(update) = self.get_channel_update(&chan) {
1703                                 let mut events = self.pending_events.lock().unwrap();
1704                                 events.push(events::Event::BroadcastChannelUpdate {
1705                                         msg: update
1706                                 });
1707                         }
1708                 }
1709                 Ok((res.0, res.1))
1710         }
1711
1712         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1713                 let (res, chan_option) = {
1714                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1715                         let channel_state = channel_state_lock.borrow_parts();
1716                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1717                                 hash_map::Entry::Occupied(mut chan_entry) => {
1718                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1719                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1720                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1721                                         }
1722                                         let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1723                                         if res.1.is_some() {
1724                                                 // We're done with this channel, we've got a signed closing transaction and
1725                                                 // will send the closing_signed back to the remote peer upon return. This
1726                                                 // also implies there are no pending HTLCs left on the channel, so we can
1727                                                 // fully delete it from tracking (the channel monitor is still around to
1728                                                 // watch for old state broadcasts)!
1729                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1730                                                         channel_state.short_to_id.remove(&short_id);
1731                                                 }
1732                                                 (res, Some(chan_entry.remove_entry().1))
1733                                         } else { (res, None) }
1734                                 },
1735                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1736                         }
1737                 };
1738                 if let Some(broadcast_tx) = res.1 {
1739                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1740                 }
1741                 if let Some(chan) = chan_option {
1742                         if let Ok(update) = self.get_channel_update(&chan) {
1743                                 let mut events = self.pending_events.lock().unwrap();
1744                                 events.push(events::Event::BroadcastChannelUpdate {
1745                                         msg: update
1746                                 });
1747                         }
1748                 }
1749                 Ok(res.0)
1750         }
1751
1752         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1753                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1754                 //determine the state of the payment based on our response/if we forward anything/the time
1755                 //we take to respond. We should take care to avoid allowing such an attack.
1756                 //
1757                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1758                 //us repeatedly garbled in different ways, and compare our error messages, which are
1759                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1760                 //but we should prevent it anyway.
1761
1762                 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1763                 let channel_state = channel_state_lock.borrow_parts();
1764
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 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                                 if !chan.is_usable() {
1772                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1773                                 }
1774                                 chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1775                         },
1776                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1777                 }
1778         }
1779
1780         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1781                 let mut channel_state = self.channel_state.lock().unwrap();
1782                 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1783                         Some(chan) => {
1784                                 if chan.get_their_node_id() != *their_node_id {
1785                                         //TODO: here and below MsgHandleErrInternal, #153 case
1786                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1787                                 }
1788                                 chan.update_fulfill_htlc(&msg)
1789                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?.clone()
1790                         },
1791                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1792                 };
1793                 self.claim_funds_internal(channel_state, htlc_source, msg.payment_preimage.clone());
1794                 Ok(())
1795         }
1796
1797         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, MsgHandleErrInternal> {
1798                 let mut channel_state = self.channel_state.lock().unwrap();
1799                 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1800                         Some(chan) => {
1801                                 if chan.get_their_node_id() != *their_node_id {
1802                                         //TODO: here and below MsgHandleErrInternal, #153 case
1803                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1804                                 }
1805                                 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() })
1806                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
1807                         },
1808                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1809                 }?;
1810
1811                 match htlc_source {
1812                         &HTLCSource::OutboundRoute { ref route, ref session_priv, .. } => {
1813                                 // Handle packed channel/node updates for passing back for the route handler
1814                                 let mut packet_decrypted = msg.reason.data.clone();
1815                                 let mut res = None;
1816                                 Self::construct_onion_keys_callback(&self.secp_ctx, &route, &session_priv, |shared_secret, _, _, route_hop| {
1817                                         if res.is_some() { return; }
1818
1819                                         let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1820
1821                                         let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1822                                         decryption_tmp.resize(packet_decrypted.len(), 0);
1823                                         let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1824                                         chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1825                                         packet_decrypted = decryption_tmp;
1826
1827                                         if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
1828                                                 if err_packet.failuremsg.len() >= 2 {
1829                                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1830
1831                                                         let mut hmac = Hmac::new(Sha256::new(), &um);
1832                                                         hmac.input(&err_packet.encode()[32..]);
1833                                                         let mut calc_tag = [0u8; 32];
1834                                                         hmac.raw_result(&mut calc_tag);
1835                                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1836                                                                 const UNKNOWN_CHAN: u16 = 0x4000|10;
1837                                                                 const TEMP_CHAN_FAILURE: u16 = 0x4000|7;
1838                                                                 match byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]) {
1839                                                                         TEMP_CHAN_FAILURE => {
1840                                                                                 if err_packet.failuremsg.len() >= 4 {
1841                                                                                         let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[2..4]) as usize;
1842                                                                                         if err_packet.failuremsg.len() >= 4 + update_len {
1843                                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[4..4 + update_len])) {
1844                                                                                                         res = Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1845                                                                                                                 msg: chan_update,
1846                                                                                                         });
1847                                                                                                 }
1848                                                                                         }
1849                                                                                 }
1850                                                                         },
1851                                                                         UNKNOWN_CHAN => {
1852                                                                                 // No such next-hop. We know this came from the
1853                                                                                 // current node as the HMAC validated.
1854                                                                                 res = Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1855                                                                                         short_channel_id: route_hop.short_channel_id,
1856                                                                                         is_permanent: true,
1857                                                                                 });
1858                                                                         },
1859                                                                         _ => {}, //TODO: Enumerate all of these!
1860                                                                 }
1861                                                         }
1862                                                 }
1863                                         }
1864                                 }).unwrap();
1865                                 Ok(res)
1866                         },
1867                         _ => { Ok(None) },
1868                 }
1869         }
1870
1871         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
1872                 let mut channel_state = self.channel_state.lock().unwrap();
1873                 match channel_state.by_id.get_mut(&msg.channel_id) {
1874                         Some(chan) => {
1875                                 if chan.get_their_node_id() != *their_node_id {
1876                                         //TODO: here and below MsgHandleErrInternal, #153 case
1877                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1878                                 }
1879                                 if (msg.failure_code & 0x8000) != 0 {
1880                                         return Err(MsgHandleErrInternal::send_err_msg_close_chan("Got update_fail_malformed_htlc with BADONION set", msg.channel_id));
1881                                 }
1882                                 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() })
1883                                         .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1884                                 Ok(())
1885                         },
1886                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1887                 }
1888         }
1889
1890         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), MsgHandleErrInternal> {
1891                 let (revoke_and_ack, commitment_signed, chan_monitor) = {
1892                         let mut channel_state = self.channel_state.lock().unwrap();
1893                         match channel_state.by_id.get_mut(&msg.channel_id) {
1894                                 Some(chan) => {
1895                                         if chan.get_their_node_id() != *their_node_id {
1896                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1897                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1898                                         }
1899                                         chan.commitment_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?
1900                                 },
1901                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1902                         }
1903                 };
1904                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1905                         unimplemented!();
1906                 }
1907
1908                 Ok((revoke_and_ack, commitment_signed))
1909         }
1910
1911         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, MsgHandleErrInternal> {
1912                 let ((res, mut pending_forwards, mut pending_failures, chan_monitor), short_channel_id) = {
1913                         let mut channel_state = self.channel_state.lock().unwrap();
1914                         match channel_state.by_id.get_mut(&msg.channel_id) {
1915                                 Some(chan) => {
1916                                         if chan.get_their_node_id() != *their_node_id {
1917                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1918                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1919                                         }
1920                                         (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"))
1921                                 },
1922                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1923                         }
1924                 };
1925                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1926                         unimplemented!();
1927                 }
1928                 for failure in pending_failures.drain(..) {
1929                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1930                 }
1931
1932                 let mut forward_event = None;
1933                 if !pending_forwards.is_empty() {
1934                         let mut channel_state = self.channel_state.lock().unwrap();
1935                         if channel_state.forward_htlcs.is_empty() {
1936                                 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));
1937                                 channel_state.next_forward = forward_event.unwrap();
1938                         }
1939                         for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
1940                                 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
1941                                         hash_map::Entry::Occupied(mut entry) => {
1942                                                 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info });
1943                                         },
1944                                         hash_map::Entry::Vacant(entry) => {
1945                                                 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info }));
1946                                         }
1947                                 }
1948                         }
1949                 }
1950                 match forward_event {
1951                         Some(time) => {
1952                                 let mut pending_events = self.pending_events.lock().unwrap();
1953                                 pending_events.push(events::Event::PendingHTLCsForwardable {
1954                                         time_forwardable: time
1955                                 });
1956                         }
1957                         None => {},
1958                 }
1959
1960                 Ok(res)
1961         }
1962
1963         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
1964                 let mut channel_state = self.channel_state.lock().unwrap();
1965                 match channel_state.by_id.get_mut(&msg.channel_id) {
1966                         Some(chan) => {
1967                                 if chan.get_their_node_id() != *their_node_id {
1968                                         //TODO: here and below MsgHandleErrInternal, #153 case
1969                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1970                                 }
1971                                 chan.update_fee(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))
1972                         },
1973                         None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1974                 }
1975         }
1976
1977         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
1978                 let (chan_announcement, chan_update) = {
1979                         let mut channel_state = self.channel_state.lock().unwrap();
1980                         match channel_state.by_id.get_mut(&msg.channel_id) {
1981                                 Some(chan) => {
1982                                         if chan.get_their_node_id() != *their_node_id {
1983                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1984                                         }
1985                                         if !chan.is_usable() {
1986                                                 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
1987                                         }
1988
1989                                         let our_node_id = self.get_our_node_id();
1990                                         let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())
1991                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
1992
1993                                         let were_node_one = announcement.node_id_1 == our_node_id;
1994                                         let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1995                                         let bad_sig_action = MsgHandleErrInternal::send_err_msg_close_chan("Bad announcement_signatures node_signature", msg.channel_id);
1996                                         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);
1997                                         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);
1998
1999                                         let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2000
2001                                         (msgs::ChannelAnnouncement {
2002                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2003                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2004                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2005                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2006                                                 contents: announcement,
2007                                         }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
2008                                 },
2009                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2010                         }
2011                 };
2012                 let mut pending_events = self.pending_events.lock().unwrap();
2013                 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
2014                 Ok(())
2015         }
2016
2017         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), MsgHandleErrInternal> {
2018                 let (res, chan_monitor) = {
2019                         let mut channel_state = self.channel_state.lock().unwrap();
2020                         match channel_state.by_id.get_mut(&msg.channel_id) {
2021                                 Some(chan) => {
2022                                         if chan.get_their_node_id() != *their_node_id {
2023                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2024                                         }
2025                                         let (funding_locked, revoke_and_ack, commitment_update, channel_monitor) = chan.channel_reestablish(msg)
2026                                                 .map_err(|e| MsgHandleErrInternal::from_chan_maybe_close(e, msg.channel_id))?;
2027                                         (Ok((funding_locked, revoke_and_ack, commitment_update)), channel_monitor)
2028                                 },
2029                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2030                         }
2031                 };
2032                 if let Some(monitor) = chan_monitor {
2033                         if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2034                                 unimplemented!();
2035                         }
2036                 }
2037                 res
2038         }
2039
2040         /// Begin Update fee process. Allowed only on an outbound channel.
2041         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2042         /// PeerManager::process_events afterwards.
2043         /// Note: This API is likely to change!
2044         #[doc(hidden)]
2045         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2046                 let mut channel_state = self.channel_state.lock().unwrap();
2047                 match channel_state.by_id.get_mut(&channel_id) {
2048                         None => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2049                         Some(chan) => {
2050                                 if !chan.is_outbound() {
2051                                         return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2052                                 }
2053                                 if !chan.is_live() {
2054                                         return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2055                                 }
2056                                 if let Some((update_fee, commitment_signed, chan_monitor)) = chan.send_update_fee_and_commit(feerate_per_kw).map_err(|e| APIError::APIMisuseError{err: e.err})? {
2057                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2058                                                 unimplemented!();
2059                                         }
2060                                         let mut pending_events = self.pending_events.lock().unwrap();
2061                                         pending_events.push(events::Event::UpdateHTLCs {
2062                                                 node_id: chan.get_their_node_id(),
2063                                                 updates: msgs::CommitmentUpdate {
2064                                                         update_add_htlcs: Vec::new(),
2065                                                         update_fulfill_htlcs: Vec::new(),
2066                                                         update_fail_htlcs: Vec::new(),
2067                                                         update_fail_malformed_htlcs: Vec::new(),
2068                                                         update_fee: Some(update_fee),
2069                                                         commitment_signed,
2070                                                 },
2071                                         });
2072                                 }
2073                         },
2074                 }
2075                 Ok(())
2076         }
2077 }
2078
2079 impl events::EventsProvider for ChannelManager {
2080         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2081                 let mut pending_events = self.pending_events.lock().unwrap();
2082                 let mut ret = Vec::new();
2083                 mem::swap(&mut ret, &mut *pending_events);
2084                 ret
2085         }
2086 }
2087
2088 impl ChainListener for ChannelManager {
2089         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2090                 let mut new_events = Vec::new();
2091                 let mut failed_channels = Vec::new();
2092                 {
2093                         let mut channel_lock = self.channel_state.lock().unwrap();
2094                         let channel_state = channel_lock.borrow_parts();
2095                         let short_to_id = channel_state.short_to_id;
2096                         channel_state.by_id.retain(|_, channel| {
2097                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2098                                 if let Ok(Some(funding_locked)) = chan_res {
2099                                         let announcement_sigs = self.get_announcement_sigs(channel);
2100                                         new_events.push(events::Event::SendFundingLocked {
2101                                                 node_id: channel.get_their_node_id(),
2102                                                 msg: funding_locked,
2103                                                 announcement_sigs: announcement_sigs
2104                                         });
2105                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2106                                 } else if let Err(e) = chan_res {
2107                                         new_events.push(events::Event::HandleError {
2108                                                 node_id: channel.get_their_node_id(),
2109                                                 action: e.action,
2110                                         });
2111                                         if channel.is_shutdown() {
2112                                                 return false;
2113                                         }
2114                                 }
2115                                 if let Some(funding_txo) = channel.get_funding_txo() {
2116                                         for tx in txn_matched {
2117                                                 for inp in tx.input.iter() {
2118                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2119                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2120                                                                         short_to_id.remove(&short_id);
2121                                                                 }
2122                                                                 // It looks like our counterparty went on-chain. We go ahead and
2123                                                                 // broadcast our latest local state as well here, just in case its
2124                                                                 // some kind of SPV attack, though we expect these to be dropped.
2125                                                                 failed_channels.push(channel.force_shutdown());
2126                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2127                                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2128                                                                                 msg: update
2129                                                                         });
2130                                                                 }
2131                                                                 return false;
2132                                                         }
2133                                                 }
2134                                         }
2135                                 }
2136                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2137                                         if let Some(short_id) = channel.get_short_channel_id() {
2138                                                 short_to_id.remove(&short_id);
2139                                         }
2140                                         failed_channels.push(channel.force_shutdown());
2141                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2142                                         // the latest local tx for us, so we should skip that here (it doesn't really
2143                                         // hurt anything, but does make tests a bit simpler).
2144                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2145                                         if let Ok(update) = self.get_channel_update(&channel) {
2146                                                 new_events.push(events::Event::BroadcastChannelUpdate {
2147                                                         msg: update
2148                                                 });
2149                                         }
2150                                         return false;
2151                                 }
2152                                 true
2153                         });
2154                 }
2155                 for failure in failed_channels.drain(..) {
2156                         self.finish_force_close_channel(failure);
2157                 }
2158                 let mut pending_events = self.pending_events.lock().unwrap();
2159                 for funding_locked in new_events.drain(..) {
2160                         pending_events.push(funding_locked);
2161                 }
2162                 self.latest_block_height.store(height as usize, Ordering::Release);
2163         }
2164
2165         /// We force-close the channel without letting our counterparty participate in the shutdown
2166         fn block_disconnected(&self, header: &BlockHeader) {
2167                 let mut new_events = Vec::new();
2168                 let mut failed_channels = Vec::new();
2169                 {
2170                         let mut channel_lock = self.channel_state.lock().unwrap();
2171                         let channel_state = channel_lock.borrow_parts();
2172                         let short_to_id = channel_state.short_to_id;
2173                         channel_state.by_id.retain(|_,  v| {
2174                                 if v.block_disconnected(header) {
2175                                         if let Some(short_id) = v.get_short_channel_id() {
2176                                                 short_to_id.remove(&short_id);
2177                                         }
2178                                         failed_channels.push(v.force_shutdown());
2179                                         if let Ok(update) = self.get_channel_update(&v) {
2180                                                 new_events.push(events::Event::BroadcastChannelUpdate {
2181                                                         msg: update
2182                                                 });
2183                                         }
2184                                         false
2185                                 } else {
2186                                         true
2187                                 }
2188                         });
2189                 }
2190                 for failure in failed_channels.drain(..) {
2191                         self.finish_force_close_channel(failure);
2192                 }
2193                 if !new_events.is_empty() {
2194                         let mut pending_events = self.pending_events.lock().unwrap();
2195                         for funding_locked in new_events.drain(..) {
2196                                 pending_events.push(funding_locked);
2197                         }
2198                 }
2199                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2200         }
2201 }
2202
2203 macro_rules! handle_error {
2204         ($self: ident, $internal: expr, $their_node_id: expr) => {
2205                 match $internal {
2206                         Ok(msg) => Ok(msg),
2207                         Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
2208                                 if needs_channel_force_close {
2209                                         match &err.action {
2210                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
2211                                                         if msg.channel_id == [0; 32] {
2212                                                                 $self.peer_disconnected(&$their_node_id, true);
2213                                                         } else {
2214                                                                 $self.force_close_channel(&msg.channel_id);
2215                                                         }
2216                                                 },
2217                                                 &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
2218                                                 &Some(msgs::ErrorAction::IgnoreError) => {},
2219                                                 &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
2220                                                         if msg.channel_id == [0; 32] {
2221                                                                 $self.peer_disconnected(&$their_node_id, true);
2222                                                         } else {
2223                                                                 $self.force_close_channel(&msg.channel_id);
2224                                                         }
2225                                                 },
2226                                                 &None => {},
2227                                         }
2228                                 }
2229                                 Err(err)
2230                         },
2231                 }
2232         }
2233 }
2234
2235 impl ChannelMessageHandler for ChannelManager {
2236         //TODO: Handle errors and close channel (or so)
2237         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
2238                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2239         }
2240
2241         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2242                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2243         }
2244
2245         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
2246                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2247         }
2248
2249         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2250                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2251         }
2252
2253         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
2254                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2255         }
2256
2257         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
2258                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2259         }
2260
2261         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
2262                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2263         }
2264
2265         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2266                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2267         }
2268
2269         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2270                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2271         }
2272
2273         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, HandleError> {
2274                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2275         }
2276
2277         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2278                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2279         }
2280
2281         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
2282                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2283         }
2284
2285         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
2286                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2287         }
2288
2289         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2290                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2291         }
2292
2293         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2294                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2295         }
2296
2297         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(Option<msgs::FundingLocked>, Option<msgs::RevokeAndACK>, Option<msgs::CommitmentUpdate>), HandleError> {
2298                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2299         }
2300
2301         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2302                 let mut new_events = Vec::new();
2303                 let mut failed_channels = Vec::new();
2304                 let mut failed_payments = Vec::new();
2305                 {
2306                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2307                         let channel_state = channel_state_lock.borrow_parts();
2308                         let short_to_id = channel_state.short_to_id;
2309                         if no_connection_possible {
2310                                 channel_state.by_id.retain(|_, chan| {
2311                                         if chan.get_their_node_id() == *their_node_id {
2312                                                 if let Some(short_id) = chan.get_short_channel_id() {
2313                                                         short_to_id.remove(&short_id);
2314                                                 }
2315                                                 failed_channels.push(chan.force_shutdown());
2316                                                 if let Ok(update) = self.get_channel_update(&chan) {
2317                                                         new_events.push(events::Event::BroadcastChannelUpdate {
2318                                                                 msg: update
2319                                                         });
2320                                                 }
2321                                                 false
2322                                         } else {
2323                                                 true
2324                                         }
2325                                 });
2326                         } else {
2327                                 channel_state.by_id.retain(|_, chan| {
2328                                         if chan.get_their_node_id() == *their_node_id {
2329                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2330                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2331                                                 if !failed_adds.is_empty() {
2332                                                         let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
2333                                                         failed_payments.push((chan_update, failed_adds));
2334                                                 }
2335                                                 if chan.is_shutdown() {
2336                                                         if let Some(short_id) = chan.get_short_channel_id() {
2337                                                                 short_to_id.remove(&short_id);
2338                                                         }
2339                                                         return false;
2340                                                 }
2341                                         }
2342                                         true
2343                                 })
2344                         }
2345                 }
2346                 for failure in failed_channels.drain(..) {
2347                         self.finish_force_close_channel(failure);
2348                 }
2349                 if !new_events.is_empty() {
2350                         let mut pending_events = self.pending_events.lock().unwrap();
2351                         for event in new_events.drain(..) {
2352                                 pending_events.push(event);
2353                         }
2354                 }
2355                 for (chan_update, mut htlc_sources) in failed_payments {
2356                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2357                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2358                         }
2359                 }
2360         }
2361
2362         fn peer_connected(&self, their_node_id: &PublicKey) -> Vec<msgs::ChannelReestablish> {
2363                 let mut res = Vec::new();
2364                 let mut channel_state = self.channel_state.lock().unwrap();
2365                 channel_state.by_id.retain(|_, chan| {
2366                         if chan.get_their_node_id() == *their_node_id {
2367                                 if !chan.have_received_message() {
2368                                         // If we created this (outbound) channel while we were disconnected from the
2369                                         // peer we probably failed to send the open_channel message, which is now
2370                                         // lost. We can't have had anything pending related to this channel, so we just
2371                                         // drop it.
2372                                         false
2373                                 } else {
2374                                         res.push(chan.get_channel_reestablish());
2375                                         true
2376                                 }
2377                         } else { true }
2378                 });
2379                 //TODO: Also re-broadcast announcement_signatures
2380                 res
2381         }
2382
2383         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2384                 if msg.channel_id == [0; 32] {
2385                         for chan in self.list_channels() {
2386                                 if chan.remote_network_id == *their_node_id {
2387                                         self.force_close_channel(&chan.channel_id);
2388                                 }
2389                         }
2390                 } else {
2391                         self.force_close_channel(&msg.channel_id);
2392                 }
2393         }
2394 }
2395
2396 #[cfg(test)]
2397 mod tests {
2398         use chain::chaininterface;
2399         use chain::transaction::OutPoint;
2400         use chain::chaininterface::ChainListener;
2401         use ln::channelmanager::{ChannelManager,OnionKeys};
2402         use ln::channelmonitor::{CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
2403         use ln::router::{Route, RouteHop, Router};
2404         use ln::msgs;
2405         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
2406         use util::test_utils;
2407         use util::events::{Event, EventsProvider};
2408         use util::errors::APIError;
2409         use util::logger::Logger;
2410         use util::ser::Writeable;
2411
2412         use bitcoin::util::hash::Sha256dHash;
2413         use bitcoin::blockdata::block::{Block, BlockHeader};
2414         use bitcoin::blockdata::transaction::{Transaction, TxOut};
2415         use bitcoin::blockdata::constants::genesis_block;
2416         use bitcoin::network::constants::Network;
2417         use bitcoin::network::serialize::serialize;
2418         use bitcoin::network::serialize::BitcoinHash;
2419
2420         use hex;
2421
2422         use secp256k1::{Secp256k1, Message};
2423         use secp256k1::key::{PublicKey,SecretKey};
2424
2425         use crypto::sha2::Sha256;
2426         use crypto::digest::Digest;
2427
2428         use rand::{thread_rng,Rng};
2429
2430         use std::cell::RefCell;
2431         use std::collections::{BTreeSet, HashMap};
2432         use std::default::Default;
2433         use std::rc::Rc;
2434         use std::sync::{Arc, Mutex};
2435         use std::sync::atomic::Ordering;
2436         use std::time::Instant;
2437         use std::mem;
2438
2439         fn build_test_onion_keys() -> Vec<OnionKeys> {
2440                 // Keys from BOLT 4, used in both test vector tests
2441                 let secp_ctx = Secp256k1::new();
2442
2443                 let route = Route {
2444                         hops: vec!(
2445                                         RouteHop {
2446                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2447                                                 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
2448                                         },
2449                                         RouteHop {
2450                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2451                                                 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
2452                                         },
2453                                         RouteHop {
2454                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2455                                                 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
2456                                         },
2457                                         RouteHop {
2458                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2459                                                 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
2460                                         },
2461                                         RouteHop {
2462                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2463                                                 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
2464                                         },
2465                         ),
2466                 };
2467
2468                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2469
2470                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2471                 assert_eq!(onion_keys.len(), route.hops.len());
2472                 onion_keys
2473         }
2474
2475         #[test]
2476         fn onion_vectors() {
2477                 // Packet creation test vectors from BOLT 4
2478                 let onion_keys = build_test_onion_keys();
2479
2480                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2481                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2482                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2483                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2484                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2485
2486                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2487                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2488                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2489                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2490                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2491
2492                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2493                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2494                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2495                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2496                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2497
2498                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2499                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2500                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2501                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2502                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2503
2504                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2505                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2506                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2507                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2508                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2509
2510                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2511                 let payloads = vec!(
2512                         msgs::OnionHopData {
2513                                 realm: 0,
2514                                 data: msgs::OnionRealm0HopData {
2515                                         short_channel_id: 0,
2516                                         amt_to_forward: 0,
2517                                         outgoing_cltv_value: 0,
2518                                 },
2519                                 hmac: [0; 32],
2520                         },
2521                         msgs::OnionHopData {
2522                                 realm: 0,
2523                                 data: msgs::OnionRealm0HopData {
2524                                         short_channel_id: 0x0101010101010101,
2525                                         amt_to_forward: 0x0100000001,
2526                                         outgoing_cltv_value: 0,
2527                                 },
2528                                 hmac: [0; 32],
2529                         },
2530                         msgs::OnionHopData {
2531                                 realm: 0,
2532                                 data: msgs::OnionRealm0HopData {
2533                                         short_channel_id: 0x0202020202020202,
2534                                         amt_to_forward: 0x0200000002,
2535                                         outgoing_cltv_value: 0,
2536                                 },
2537                                 hmac: [0; 32],
2538                         },
2539                         msgs::OnionHopData {
2540                                 realm: 0,
2541                                 data: msgs::OnionRealm0HopData {
2542                                         short_channel_id: 0x0303030303030303,
2543                                         amt_to_forward: 0x0300000003,
2544                                         outgoing_cltv_value: 0,
2545                                 },
2546                                 hmac: [0; 32],
2547                         },
2548                         msgs::OnionHopData {
2549                                 realm: 0,
2550                                 data: msgs::OnionRealm0HopData {
2551                                         short_channel_id: 0x0404040404040404,
2552                                         amt_to_forward: 0x0400000004,
2553                                         outgoing_cltv_value: 0,
2554                                 },
2555                                 hmac: [0; 32],
2556                         },
2557                 );
2558
2559                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
2560                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2561                 // anyway...
2562                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2563         }
2564
2565         #[test]
2566         fn test_failure_packet_onion() {
2567                 // Returning Errors test vectors from BOLT 4
2568
2569                 let onion_keys = build_test_onion_keys();
2570                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2571                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2572
2573                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2574                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2575
2576                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2577                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2578
2579                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2580                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2581
2582                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2583                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2584
2585                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2586                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2587         }
2588
2589         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2590                 assert!(chain.does_match_tx(tx));
2591                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2592                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2593                 for i in 2..100 {
2594                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2595                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2596                 }
2597         }
2598
2599         struct Node {
2600                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2601                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2602                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2603                 node: Arc<ChannelManager>,
2604                 router: Router,
2605                 network_payment_count: Rc<RefCell<u8>>,
2606                 network_chan_count: Rc<RefCell<u32>>,
2607         }
2608         impl Drop for Node {
2609                 fn drop(&mut self) {
2610                         if !::std::thread::panicking() {
2611                                 // Check that we processed all pending events
2612                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
2613                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2614                         }
2615                 }
2616         }
2617
2618         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2619                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
2620         }
2621
2622         fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2623                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
2624                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
2625                 (announcement, as_update, bs_update, channel_id, tx)
2626         }
2627
2628         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
2629                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
2630
2631                 let events_1 = node_a.node.get_and_clear_pending_events();
2632                 assert_eq!(events_1.len(), 1);
2633                 let accept_chan = match events_1[0] {
2634                         Event::SendOpenChannel { ref node_id, ref msg } => {
2635                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2636                                 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2637                         },
2638                         _ => panic!("Unexpected event"),
2639                 };
2640
2641                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2642
2643                 let chan_id = *node_a.network_chan_count.borrow();
2644                 let tx;
2645                 let funding_output;
2646
2647                 let events_2 = node_a.node.get_and_clear_pending_events();
2648                 assert_eq!(events_2.len(), 1);
2649                 match events_2[0] {
2650                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2651                                 assert_eq!(*channel_value_satoshis, channel_value);
2652                                 assert_eq!(user_channel_id, 42);
2653
2654                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2655                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2656                                 }]};
2657                                 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2658
2659                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2660                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2661                                 assert_eq!(added_monitors.len(), 1);
2662                                 assert_eq!(added_monitors[0].0, funding_output);
2663                                 added_monitors.clear();
2664                         },
2665                         _ => panic!("Unexpected event"),
2666                 }
2667
2668                 let events_3 = node_a.node.get_and_clear_pending_events();
2669                 assert_eq!(events_3.len(), 1);
2670                 let funding_signed = match events_3[0] {
2671                         Event::SendFundingCreated { ref node_id, ref msg } => {
2672                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2673                                 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2674                                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2675                                 assert_eq!(added_monitors.len(), 1);
2676                                 assert_eq!(added_monitors[0].0, funding_output);
2677                                 added_monitors.clear();
2678                                 res
2679                         },
2680                         _ => panic!("Unexpected event"),
2681                 };
2682
2683                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2684                 {
2685                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2686                         assert_eq!(added_monitors.len(), 1);
2687                         assert_eq!(added_monitors[0].0, funding_output);
2688                         added_monitors.clear();
2689                 }
2690
2691                 let events_4 = node_a.node.get_and_clear_pending_events();
2692                 assert_eq!(events_4.len(), 1);
2693                 match events_4[0] {
2694                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2695                                 assert_eq!(user_channel_id, 42);
2696                                 assert_eq!(*funding_txo, funding_output);
2697                         },
2698                         _ => panic!("Unexpected event"),
2699                 };
2700
2701                 tx
2702         }
2703
2704         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
2705                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
2706                 let events_5 = node_b.node.get_and_clear_pending_events();
2707                 assert_eq!(events_5.len(), 1);
2708                 match events_5[0] {
2709                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2710                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
2711                                 assert!(announcement_sigs.is_none());
2712                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap()
2713                         },
2714                         _ => panic!("Unexpected event"),
2715                 };
2716
2717                 let channel_id;
2718
2719                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
2720                 let events_6 = node_a.node.get_and_clear_pending_events();
2721                 assert_eq!(events_6.len(), 1);
2722                 (match events_6[0] {
2723                         Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2724                                 channel_id = msg.channel_id.clone();
2725                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
2726                                 (msg.clone(), announcement_sigs.clone().unwrap())
2727                         },
2728                         _ => panic!("Unexpected event"),
2729                 }, channel_id)
2730         }
2731
2732         fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
2733                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
2734                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
2735                 (msgs, chan_id, tx)
2736         }
2737
2738         fn create_chan_between_nodes_with_value_b(node_a: &Node, node_b: &Node, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
2739                 let bs_announcement_sigs = {
2740                         let bs_announcement_sigs = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap().unwrap();
2741                         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
2742                         bs_announcement_sigs
2743                 };
2744
2745                 let events_7 = node_b.node.get_and_clear_pending_events();
2746                 assert_eq!(events_7.len(), 1);
2747                 let (announcement, bs_update) = match events_7[0] {
2748                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2749                                 (msg, update_msg)
2750                         },
2751                         _ => panic!("Unexpected event"),
2752                 };
2753
2754                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
2755                 let events_8 = node_a.node.get_and_clear_pending_events();
2756                 assert_eq!(events_8.len(), 1);
2757                 let as_update = match events_8[0] {
2758                         Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2759                                 assert!(*announcement == *msg);
2760                                 update_msg
2761                         },
2762                         _ => panic!("Unexpected event"),
2763                 };
2764
2765                 *node_a.network_chan_count.borrow_mut() += 1;
2766
2767                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
2768         }
2769
2770         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2771                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
2772         }
2773
2774         fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2775                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
2776                 for node in nodes {
2777                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2778                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
2779                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
2780                 }
2781                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2782         }
2783
2784         macro_rules! check_spends {
2785                 ($tx: expr, $spends_tx: expr) => {
2786                         {
2787                                 let mut funding_tx_map = HashMap::new();
2788                                 let spends_tx = $spends_tx;
2789                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
2790                                 $tx.verify(&funding_tx_map).unwrap();
2791                         }
2792                 }
2793         }
2794
2795         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2796                 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2797                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2798                 let (tx_a, tx_b);
2799
2800                 node_a.close_channel(channel_id).unwrap();
2801                 let events_1 = node_a.get_and_clear_pending_events();
2802                 assert_eq!(events_1.len(), 1);
2803                 let shutdown_a = match events_1[0] {
2804                         Event::SendShutdown { ref node_id, ref msg } => {
2805                                 assert_eq!(node_id, &node_b.get_our_node_id());
2806                                 msg.clone()
2807                         },
2808                         _ => panic!("Unexpected event"),
2809                 };
2810
2811                 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2812                 if !close_inbound_first {
2813                         assert!(closing_signed_b.is_none());
2814                 }
2815                 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2816                 assert!(empty_a.is_none());
2817                 if close_inbound_first {
2818                         assert!(closing_signed_a.is_none());
2819                         closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2820                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2821                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2822
2823                         let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2824                         assert!(empty_b.is_none());
2825                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2826                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2827                 } else {
2828                         closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2829                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2830                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2831
2832                         let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2833                         assert!(empty_a2.is_none());
2834                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2835                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2836                 }
2837                 assert_eq!(tx_a, tx_b);
2838                 check_spends!(tx_a, funding_tx);
2839
2840                 let events_2 = node_a.get_and_clear_pending_events();
2841                 assert_eq!(events_2.len(), 1);
2842                 let as_update = match events_2[0] {
2843                         Event::BroadcastChannelUpdate { ref msg } => {
2844                                 msg.clone()
2845                         },
2846                         _ => panic!("Unexpected event"),
2847                 };
2848
2849                 let events_3 = node_b.get_and_clear_pending_events();
2850                 assert_eq!(events_3.len(), 1);
2851                 let bs_update = match events_3[0] {
2852                         Event::BroadcastChannelUpdate { ref msg } => {
2853                                 msg.clone()
2854                         },
2855                         _ => panic!("Unexpected event"),
2856                 };
2857
2858                 (as_update, bs_update)
2859         }
2860
2861         struct SendEvent {
2862                 node_id: PublicKey,
2863                 msgs: Vec<msgs::UpdateAddHTLC>,
2864                 commitment_msg: msgs::CommitmentSigned,
2865         }
2866         impl SendEvent {
2867                 fn from_event(event: Event) -> SendEvent {
2868                         match event {
2869                                 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, update_fee, commitment_signed } } => {
2870                                         assert!(update_fulfill_htlcs.is_empty());
2871                                         assert!(update_fail_htlcs.is_empty());
2872                                         assert!(update_fail_malformed_htlcs.is_empty());
2873                                         assert!(update_fee.is_none());
2874                                         SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
2875                                 },
2876                                 _ => panic!("Unexpected event type!"),
2877                         }
2878                 }
2879         }
2880
2881         macro_rules! check_added_monitors {
2882                 ($node: expr, $count: expr) => {
2883                         {
2884                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2885                                 assert_eq!(added_monitors.len(), $count);
2886                                 added_monitors.clear();
2887                         }
2888                 }
2889         }
2890
2891         macro_rules! commitment_signed_dance {
2892                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
2893                         {
2894                                 check_added_monitors!($node_a, 0);
2895                                 let (as_revoke_and_ack, as_commitment_signed) = $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
2896                                 check_added_monitors!($node_a, 1);
2897                                 check_added_monitors!($node_b, 0);
2898                                 assert!($node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
2899                                 check_added_monitors!($node_b, 1);
2900                                 let (bs_revoke_and_ack, bs_none) = $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
2901                                 assert!(bs_none.is_none());
2902                                 check_added_monitors!($node_b, 1);
2903                                 if $fail_backwards {
2904                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
2905                                 }
2906                                 assert!($node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
2907                                 {
2908                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
2909                                         if $fail_backwards {
2910                                                 assert_eq!(added_monitors.len(), 2);
2911                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
2912                                         } else {
2913                                                 assert_eq!(added_monitors.len(), 1);
2914                                         }
2915                                         added_monitors.clear();
2916                                 }
2917                         }
2918                 }
2919         }
2920
2921         macro_rules! get_payment_preimage_hash {
2922                 ($node: expr) => {
2923                         {
2924                                 let payment_preimage = [*$node.network_payment_count.borrow(); 32];
2925                                 *$node.network_payment_count.borrow_mut() += 1;
2926                                 let mut payment_hash = [0; 32];
2927                                 let mut sha = Sha256::new();
2928                                 sha.input(&payment_preimage[..]);
2929                                 sha.result(&mut payment_hash);
2930                                 (payment_preimage, payment_hash)
2931                         }
2932                 }
2933         }
2934
2935         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2936                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
2937
2938                 let mut payment_event = {
2939                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
2940                         check_added_monitors!(origin_node, 1);
2941
2942                         let mut events = origin_node.node.get_and_clear_pending_events();
2943                         assert_eq!(events.len(), 1);
2944                         SendEvent::from_event(events.remove(0))
2945                 };
2946                 let mut prev_node = origin_node;
2947
2948                 for (idx, &node) in expected_route.iter().enumerate() {
2949                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2950
2951                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2952                         check_added_monitors!(node, 0);
2953                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
2954
2955                         let events_1 = node.node.get_and_clear_pending_events();
2956                         assert_eq!(events_1.len(), 1);
2957                         match events_1[0] {
2958                                 Event::PendingHTLCsForwardable { .. } => { },
2959                                 _ => panic!("Unexpected event"),
2960                         };
2961
2962                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
2963                         node.node.process_pending_htlc_forwards();
2964
2965                         let mut events_2 = node.node.get_and_clear_pending_events();
2966                         assert_eq!(events_2.len(), 1);
2967                         if idx == expected_route.len() - 1 {
2968                                 match events_2[0] {
2969                                         Event::PaymentReceived { ref payment_hash, amt } => {
2970                                                 assert_eq!(our_payment_hash, *payment_hash);
2971                                                 assert_eq!(amt, recv_value);
2972                                         },
2973                                         _ => panic!("Unexpected event"),
2974                                 }
2975                         } else {
2976                                 check_added_monitors!(node, 1);
2977                                 payment_event = SendEvent::from_event(events_2.remove(0));
2978                                 assert_eq!(payment_event.msgs.len(), 1);
2979                         }
2980
2981                         prev_node = node;
2982                 }
2983
2984                 (our_payment_preimage, our_payment_hash)
2985         }
2986
2987         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
2988                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
2989                 check_added_monitors!(expected_route.last().unwrap(), 1);
2990
2991                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
2992                 macro_rules! update_fulfill_dance {
2993                         ($node: expr, $prev_node: expr, $last_node: expr) => {
2994                                 {
2995                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2996                                         if $last_node {
2997                                                 check_added_monitors!($node, 0);
2998                                         } else {
2999                                                 check_added_monitors!($node, 1);
3000                                         }
3001                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
3002                                 }
3003                         }
3004                 }
3005
3006                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3007                 let mut prev_node = expected_route.last().unwrap();
3008                 for (idx, node) in expected_route.iter().rev().enumerate() {
3009                         assert_eq!(expected_next_node, node.node.get_our_node_id());
3010                         if next_msgs.is_some() {
3011                                 update_fulfill_dance!(node, prev_node, false);
3012                         }
3013
3014                         let events = node.node.get_and_clear_pending_events();
3015                         if !skip_last || idx != expected_route.len() - 1 {
3016                                 assert_eq!(events.len(), 1);
3017                                 match events[0] {
3018                                         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 update_fee, ref commitment_signed } } => {
3019                                                 assert!(update_add_htlcs.is_empty());
3020                                                 assert_eq!(update_fulfill_htlcs.len(), 1);
3021                                                 assert!(update_fail_htlcs.is_empty());
3022                                                 assert!(update_fail_malformed_htlcs.is_empty());
3023                                                 assert!(update_fee.is_none());
3024                                                 expected_next_node = node_id.clone();
3025                                                 next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
3026                                         },
3027                                         _ => panic!("Unexpected event"),
3028                                 }
3029                         } else {
3030                                 assert!(events.is_empty());
3031                         }
3032                         if !skip_last && idx == expected_route.len() - 1 {
3033                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3034                         }
3035
3036                         prev_node = node;
3037                 }
3038
3039                 if !skip_last {
3040                         update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
3041                         let events = origin_node.node.get_and_clear_pending_events();
3042                         assert_eq!(events.len(), 1);
3043                         match events[0] {
3044                                 Event::PaymentSent { payment_preimage } => {
3045                                         assert_eq!(payment_preimage, our_payment_preimage);
3046                                 },
3047                                 _ => panic!("Unexpected event"),
3048                         }
3049                 }
3050         }
3051
3052         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
3053                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
3054         }
3055
3056         const TEST_FINAL_CLTV: u32 = 32;
3057
3058         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3059                 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();
3060                 assert_eq!(route.hops.len(), expected_route.len());
3061                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3062                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
3063                 }
3064
3065                 send_along_route(origin_node, route, expected_route, recv_value)
3066         }
3067
3068         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
3069                 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();
3070                 assert_eq!(route.hops.len(), expected_route.len());
3071                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
3072                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
3073                 }
3074
3075                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
3076
3077                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
3078                 match err {
3079                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
3080                         _ => panic!("Unknown error variants"),
3081                 };
3082         }
3083
3084         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
3085                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
3086                 claim_payment(&origin, expected_route, our_payment_preimage);
3087         }
3088
3089         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
3090                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
3091                 check_added_monitors!(expected_route.last().unwrap(), 1);
3092
3093                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
3094                 macro_rules! update_fail_dance {
3095                         ($node: expr, $prev_node: expr, $last_node: expr) => {
3096                                 {
3097                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
3098                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
3099                                 }
3100                         }
3101                 }
3102
3103                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
3104                 let mut prev_node = expected_route.last().unwrap();
3105                 for (idx, node) in expected_route.iter().rev().enumerate() {
3106                         assert_eq!(expected_next_node, node.node.get_our_node_id());
3107                         if next_msgs.is_some() {
3108                                 // We may be the "last node" for the purpose of the commitment dance if we're
3109                                 // skipping the last node (implying it is disconnected) and we're the
3110                                 // second-to-last node!
3111                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
3112                         }
3113
3114                         let events = node.node.get_and_clear_pending_events();
3115                         if !skip_last || idx != expected_route.len() - 1 {
3116                                 assert_eq!(events.len(), 1);
3117                                 match events[0] {
3118                                         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 update_fee, ref commitment_signed } } => {
3119                                                 assert!(update_add_htlcs.is_empty());
3120                                                 assert!(update_fulfill_htlcs.is_empty());
3121                                                 assert_eq!(update_fail_htlcs.len(), 1);
3122                                                 assert!(update_fail_malformed_htlcs.is_empty());
3123                                                 assert!(update_fee.is_none());
3124                                                 expected_next_node = node_id.clone();
3125                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
3126                                         },
3127                                         _ => panic!("Unexpected event"),
3128                                 }
3129                         } else {
3130                                 assert!(events.is_empty());
3131                         }
3132                         if !skip_last && idx == expected_route.len() - 1 {
3133                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
3134                         }
3135
3136                         prev_node = node;
3137                 }
3138
3139                 if !skip_last {
3140                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
3141
3142                         let events = origin_node.node.get_and_clear_pending_events();
3143                         assert_eq!(events.len(), 1);
3144                         match events[0] {
3145                                 Event::PaymentFailed { payment_hash } => {
3146                                         assert_eq!(payment_hash, our_payment_hash);
3147                                 },
3148                                 _ => panic!("Unexpected event"),
3149                         }
3150                 }
3151         }
3152
3153         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
3154                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
3155         }
3156
3157         fn create_network(node_count: usize) -> Vec<Node> {
3158                 let mut nodes = Vec::new();
3159                 let mut rng = thread_rng();
3160                 let secp_ctx = Secp256k1::new();
3161                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
3162
3163                 let chan_count = Rc::new(RefCell::new(0));
3164                 let payment_count = Rc::new(RefCell::new(0));
3165
3166                 for _ in 0..node_count {
3167                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
3168                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
3169                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
3170                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
3171                         let node_id = {
3172                                 let mut key_slice = [0; 32];
3173                                 rng.fill_bytes(&mut key_slice);
3174                                 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
3175                         };
3176                         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();
3177                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
3178                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
3179                                 network_payment_count: payment_count.clone(),
3180                                 network_chan_count: chan_count.clone(),
3181                         });
3182                 }
3183
3184                 nodes
3185         }
3186
3187         #[test]
3188         fn test_async_inbound_update_fee() {
3189                 let mut nodes = create_network(2);
3190                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3191                 let channel_id = chan.2;
3192
3193                 macro_rules! get_feerate {
3194                         ($node: expr) => {{
3195                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3196                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3197                                 chan.get_feerate()
3198                         }}
3199                 }
3200
3201                 // balancing
3202                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3203
3204                 // A                                        B
3205                 // update_fee                            ->
3206                 // send (1) commitment_signed            -.
3207                 //                                       <- update_add_htlc/commitment_signed
3208                 // send (2) RAA (awaiting remote revoke) -.
3209                 // (1) commitment_signed is delivered    ->
3210                 //                                       .- send (3) RAA (awaiting remote revoke)
3211                 // (2) RAA is delivered                  ->
3212                 //                                       .- send (4) commitment_signed
3213                 //                                       <- (3) RAA is delivered
3214                 // send (5) commitment_signed            -.
3215                 //                                       <- (4) commitment_signed is delivered
3216                 // send (6) RAA                          -.
3217                 // (5) commitment_signed is delivered    ->
3218                 //                                       <- RAA
3219                 // (6) RAA is delivered                  ->
3220
3221                 // First nodes[0] generates an update_fee
3222                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3223                 check_added_monitors!(nodes[0], 1);
3224
3225                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3226                 assert_eq!(events_0.len(), 1);
3227                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
3228                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3229                                 (update_fee.as_ref(), commitment_signed)
3230                         },
3231                         _ => panic!("Unexpected event"),
3232                 };
3233
3234                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3235
3236                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3237                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3238                 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
3239                 check_added_monitors!(nodes[1], 1);
3240
3241                 let payment_event = {
3242                         let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3243                         assert_eq!(events_1.len(), 1);
3244                         SendEvent::from_event(events_1.remove(0))
3245                 };
3246                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3247                 assert_eq!(payment_event.msgs.len(), 1);
3248
3249                 // ...now when the messages get delivered everyone should be happy
3250                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3251                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3252                 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3253                 check_added_monitors!(nodes[0], 1);
3254
3255                 // deliver(1), generate (3):
3256                 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3257                 assert!(bs_commitment_signed.is_none()); // nodes[1] is awaiting nodes[0] revoke_and_ack
3258                 check_added_monitors!(nodes[1], 1);
3259
3260                 let bs_update = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
3261                 assert!(bs_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (4)
3262                 assert!(bs_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (4)
3263                 assert!(bs_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (4)
3264                 assert!(bs_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (4)
3265                 assert!(bs_update.as_ref().unwrap().update_fee.is_none()); // (4)
3266                 check_added_monitors!(nodes[1], 1);
3267
3268                 let as_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap(); // deliver (3)
3269                 assert!(as_update.as_ref().unwrap().update_add_htlcs.is_empty()); // (5)
3270                 assert!(as_update.as_ref().unwrap().update_fulfill_htlcs.is_empty()); // (5)
3271                 assert!(as_update.as_ref().unwrap().update_fail_htlcs.is_empty()); // (5)
3272                 assert!(as_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty()); // (5)
3273                 assert!(as_update.as_ref().unwrap().update_fee.is_none()); // (5)
3274                 check_added_monitors!(nodes[0], 1);
3275
3276                 let (as_second_revoke, as_second_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.unwrap().commitment_signed).unwrap(); // deliver (4)
3277                 assert!(as_second_commitment_signed.is_none()); // only (6)
3278                 check_added_monitors!(nodes[0], 1);
3279
3280                 let (bs_second_revoke, bs_second_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.unwrap().commitment_signed).unwrap(); // deliver (5)
3281                 assert!(bs_second_commitment_signed.is_none());
3282                 check_added_monitors!(nodes[1], 1);
3283
3284                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3285                 check_added_monitors!(nodes[0], 1);
3286
3287                 let events_2 = nodes[0].node.get_and_clear_pending_events();
3288                 assert_eq!(events_2.len(), 1);
3289                 match events_2[0] {
3290                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
3291                         _ => panic!("Unexpected event"),
3292                 }
3293
3294                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none()); // deliver (6)
3295                 check_added_monitors!(nodes[1], 1);
3296         }
3297
3298         #[test]
3299         fn test_update_fee_unordered_raa() {
3300                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
3301                 // crash in an earlier version of the update_fee patch)
3302                 let mut nodes = create_network(2);
3303                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3304                 let channel_id = chan.2;
3305
3306                 macro_rules! get_feerate {
3307                         ($node: expr) => {{
3308                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3309                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3310                                 chan.get_feerate()
3311                         }}
3312                 }
3313
3314                 // balancing
3315                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3316
3317                 // First nodes[0] generates an update_fee
3318                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0]) + 20).unwrap();
3319                 check_added_monitors!(nodes[0], 1);
3320
3321                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3322                 assert_eq!(events_0.len(), 1);
3323                 let update_msg = match events_0[0] { // (1)
3324                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
3325                                 update_fee.as_ref()
3326                         },
3327                         _ => panic!("Unexpected event"),
3328                 };
3329
3330                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3331
3332                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
3333                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3334                 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
3335                 check_added_monitors!(nodes[1], 1);
3336
3337                 let payment_event = {
3338                         let mut events_1 = nodes[1].node.get_and_clear_pending_events();
3339                         assert_eq!(events_1.len(), 1);
3340                         SendEvent::from_event(events_1.remove(0))
3341                 };
3342                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
3343                 assert_eq!(payment_event.msgs.len(), 1);
3344
3345                 // ...now when the messages get delivered everyone should be happy
3346                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3347                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
3348                 assert!(as_commitment_signed.is_none()); // nodes[0] is awaiting nodes[1] revoke_and_ack
3349                 check_added_monitors!(nodes[0], 1);
3350
3351                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none()); // deliver (2)
3352                 check_added_monitors!(nodes[1], 1);
3353
3354                 // We can't continue, sadly, because our (1) now has a bogus signature
3355         }
3356
3357         #[test]
3358         fn test_multi_flight_update_fee() {
3359                 let nodes = create_network(2);
3360                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3361                 let channel_id = chan.2;
3362
3363                 macro_rules! get_feerate {
3364                         ($node: expr) => {{
3365                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3366                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3367                                 chan.get_feerate()
3368                         }}
3369                 }
3370
3371                 // A                                        B
3372                 // update_fee/commitment_signed          ->
3373                 //                                       .- send (1) RAA and (2) commitment_signed
3374                 // update_fee (never committed)          ->
3375                 // (3) update_fee                        ->
3376                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
3377                 // don't track which updates correspond to which revoke_and_ack responses so we're in
3378                 // AwaitingRAA mode and will not generate the update_fee yet.
3379                 //                                       <- (1) RAA delivered
3380                 // (3) is generated and send (4) CS      -.
3381                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
3382                 // know the per_commitment_point to use for it.
3383                 //                                       <- (2) commitment_signed delivered
3384                 // revoke_and_ack                        ->
3385                 //                                          B should send no response here
3386                 // (4) commitment_signed delivered       ->
3387                 //                                       <- RAA/commitment_signed delivered
3388                 // revoke_and_ack                        ->
3389
3390                 // First nodes[0] generates an update_fee
3391                 let initial_feerate = get_feerate!(nodes[0]);
3392                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
3393                 check_added_monitors!(nodes[0], 1);
3394
3395                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3396                 assert_eq!(events_0.len(), 1);
3397                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
3398                         Event::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
3399                                 (update_fee.as_ref().unwrap(), commitment_signed)
3400                         },
3401                         _ => panic!("Unexpected event"),
3402                 };
3403
3404                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
3405                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
3406                 let (bs_revoke_msg, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
3407                 check_added_monitors!(nodes[1], 1);
3408
3409                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
3410                 // transaction:
3411                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
3412                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3413
3414                 // Create the (3) update_fee message that nodes[0] will generate before it does...
3415                 let mut update_msg_2 = msgs::UpdateFee {
3416                         channel_id: update_msg_1.channel_id.clone(),
3417                         feerate_per_kw: (initial_feerate + 30) as u32,
3418                 };
3419
3420                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3421
3422                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
3423                 // Deliver (3)
3424                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
3425
3426                 // Deliver (1), generating (3) and (4)
3427                 let as_second_update = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
3428                 check_added_monitors!(nodes[0], 1);
3429                 assert!(as_second_update.as_ref().unwrap().update_add_htlcs.is_empty());
3430                 assert!(as_second_update.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3431                 assert!(as_second_update.as_ref().unwrap().update_fail_htlcs.is_empty());
3432                 assert!(as_second_update.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3433                 // Check that the update_fee newly generated matches what we delivered:
3434                 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
3435                 assert_eq!(as_second_update.as_ref().unwrap().update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
3436
3437                 // Deliver (2) commitment_signed
3438                 let (as_revoke_msg, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), bs_commitment_signed.as_ref().unwrap()).unwrap();
3439                 check_added_monitors!(nodes[0], 1);
3440                 assert!(as_commitment_signed.is_none());
3441
3442                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap().is_none());
3443                 check_added_monitors!(nodes[1], 1);
3444
3445                 // Delever (4)
3446                 let (bs_second_revoke, bs_second_commitment) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.unwrap().commitment_signed).unwrap();
3447                 check_added_monitors!(nodes[1], 1);
3448
3449                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap().is_none());
3450                 check_added_monitors!(nodes[0], 1);
3451
3452                 let (as_second_revoke, as_second_commitment) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment.unwrap()).unwrap();
3453                 assert!(as_second_commitment.is_none());
3454                 check_added_monitors!(nodes[0], 1);
3455
3456                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap().is_none());
3457                 check_added_monitors!(nodes[1], 1);
3458         }
3459
3460         #[test]
3461         fn test_update_fee_vanilla() {
3462                 let nodes = create_network(2);
3463                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3464                 let channel_id = chan.2;
3465
3466                 macro_rules! get_feerate {
3467                         ($node: expr) => {{
3468                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3469                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3470                                 chan.get_feerate()
3471                         }}
3472                 }
3473
3474                 let feerate = get_feerate!(nodes[0]);
3475                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3476
3477                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3478                 assert_eq!(events_0.len(), 1);
3479                 let (update_msg, commitment_signed) = match events_0[0] {
3480                                 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3481                                 (update_fee.as_ref(), commitment_signed)
3482                         },
3483                         _ => panic!("Unexpected event"),
3484                 };
3485                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3486
3487                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3488                 let commitment_signed = commitment_signed.unwrap();
3489                 check_added_monitors!(nodes[0], 1);
3490                 check_added_monitors!(nodes[1], 1);
3491
3492                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3493                 assert!(resp_option.is_none());
3494                 check_added_monitors!(nodes[0], 1);
3495
3496                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3497                 assert!(commitment_signed.is_none());
3498                 check_added_monitors!(nodes[0], 1);
3499
3500                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3501                 assert!(resp_option.is_none());
3502                 check_added_monitors!(nodes[1], 1);
3503         }
3504
3505         #[test]
3506         fn test_update_fee_with_fundee_update_add_htlc() {
3507                 let mut nodes = create_network(2);
3508                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3509                 let channel_id = chan.2;
3510
3511                 macro_rules! get_feerate {
3512                         ($node: expr) => {{
3513                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3514                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3515                                 chan.get_feerate()
3516                         }}
3517                 }
3518
3519                 // balancing
3520                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
3521
3522                 let feerate = get_feerate!(nodes[0]);
3523                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3524
3525                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3526                 assert_eq!(events_0.len(), 1);
3527                 let (update_msg, commitment_signed) = match events_0[0] {
3528                                 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3529                                 (update_fee.as_ref(), commitment_signed)
3530                         },
3531                         _ => panic!("Unexpected event"),
3532                 };
3533                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3534                 check_added_monitors!(nodes[0], 1);
3535                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3536                 let commitment_signed = commitment_signed.unwrap();
3537                 check_added_monitors!(nodes[1], 1);
3538
3539                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
3540
3541                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
3542
3543                 // nothing happens since node[1] is in AwaitingRemoteRevoke
3544                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
3545                 {
3546                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
3547                         assert_eq!(added_monitors.len(), 0);
3548                         added_monitors.clear();
3549                 }
3550                 let events = nodes[0].node.get_and_clear_pending_events();
3551                 assert_eq!(events.len(), 0);
3552                 // node[1] has nothing to do
3553
3554                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3555                 assert!(resp_option.is_none());
3556                 check_added_monitors!(nodes[0], 1);
3557
3558                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3559                 assert!(commitment_signed.is_none());
3560                 check_added_monitors!(nodes[0], 1);
3561                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3562                 // AwaitingRemoteRevoke ends here
3563
3564                 let commitment_update = resp_option.unwrap();
3565                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
3566                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
3567                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
3568                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
3569                 assert_eq!(commitment_update.update_fee.is_none(), true);
3570
3571                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
3572                 let (revoke, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3573                 check_added_monitors!(nodes[0], 1);
3574                 check_added_monitors!(nodes[1], 1);
3575                 let commitment_signed = commitment_signed.unwrap();
3576                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
3577                 check_added_monitors!(nodes[1], 1);
3578                 assert!(resp_option.is_none());
3579
3580                 let (revoke, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
3581                 check_added_monitors!(nodes[1], 1);
3582                 assert!(commitment_signed.is_none());
3583                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
3584                 check_added_monitors!(nodes[0], 1);
3585                 assert!(resp_option.is_none());
3586
3587                 let events = nodes[0].node.get_and_clear_pending_events();
3588                 assert_eq!(events.len(), 1);
3589                 match events[0] {
3590                         Event::PendingHTLCsForwardable { .. } => { },
3591                         _ => panic!("Unexpected event"),
3592                 };
3593                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
3594                 nodes[0].node.process_pending_htlc_forwards();
3595
3596                 let events = nodes[0].node.get_and_clear_pending_events();
3597                 assert_eq!(events.len(), 1);
3598                 match events[0] {
3599                         Event::PaymentReceived { .. } => { },
3600                         _ => panic!("Unexpected event"),
3601                 };
3602
3603                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
3604
3605                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
3606                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
3607                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3608         }
3609
3610         #[test]
3611         fn test_update_fee() {
3612                 let nodes = create_network(2);
3613                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
3614                 let channel_id = chan.2;
3615
3616                 macro_rules! get_feerate {
3617                         ($node: expr) => {{
3618                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3619                                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
3620                                 chan.get_feerate()
3621                         }}
3622                 }
3623
3624                 // A                                        B
3625                 // (1) update_fee/commitment_signed      ->
3626                 //                                       <- (2) revoke_and_ack
3627                 //                                       .- send (3) commitment_signed
3628                 // (4) update_fee/commitment_signed      ->
3629                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
3630                 //                                       <- (3) commitment_signed delivered
3631                 // send (6) revoke_and_ack               -.
3632                 //                                       <- (5) deliver revoke_and_ack
3633                 // (6) deliver revoke_and_ack            ->
3634                 //                                       .- send (7) commitment_signed in response to (4)
3635                 //                                       <- (7) deliver commitment_signed
3636                 // revoke_and_ack                        ->
3637
3638                 // Create and deliver (1)...
3639                 let feerate = get_feerate!(nodes[0]);
3640                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
3641
3642                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3643                 assert_eq!(events_0.len(), 1);
3644                 let (update_msg, commitment_signed) = match events_0[0] {
3645                                 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3646                                 (update_fee.as_ref(), commitment_signed)
3647                         },
3648                         _ => panic!("Unexpected event"),
3649                 };
3650                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3651
3652                 // Generate (2) and (3):
3653                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3654                 let commitment_signed_0 = commitment_signed.unwrap();
3655                 check_added_monitors!(nodes[0], 1);
3656                 check_added_monitors!(nodes[1], 1);
3657
3658                 // Deliver (2):
3659                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3660                 assert!(resp_option.is_none());
3661                 check_added_monitors!(nodes[0], 1);
3662
3663                 // Create and deliver (4)...
3664                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
3665                 let events_0 = nodes[0].node.get_and_clear_pending_events();
3666                 assert_eq!(events_0.len(), 1);
3667                 let (update_msg, commitment_signed) = match events_0[0] {
3668                                 Event::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
3669                                 (update_fee.as_ref(), commitment_signed)
3670                         },
3671                         _ => panic!("Unexpected event"),
3672                 };
3673                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
3674
3675                 let (revoke_msg, commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
3676                 // ... creating (5)
3677                 assert!(commitment_signed.is_none());
3678                 check_added_monitors!(nodes[0], 1);
3679                 check_added_monitors!(nodes[1], 1);
3680
3681                 // Handle (3), creating (6):
3682                 let (revoke_msg_0, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
3683                 assert!(commitment_signed.is_none());
3684                 check_added_monitors!(nodes[0], 1);
3685
3686                 // Deliver (5):
3687                 let resp_option = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
3688                 assert!(resp_option.is_none());
3689                 check_added_monitors!(nodes[0], 1);
3690
3691                 // Deliver (6), creating (7):
3692                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
3693                 let commitment_signed = resp_option.unwrap().commitment_signed;
3694                 check_added_monitors!(nodes[1], 1);
3695
3696                 // Deliver (7)
3697                 let (revoke_msg, commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3698                 assert!(commitment_signed.is_none());
3699                 check_added_monitors!(nodes[0], 1);
3700                 let resp_option = nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
3701                 assert!(resp_option.is_none());
3702                 check_added_monitors!(nodes[1], 1);
3703
3704                 assert_eq!(get_feerate!(nodes[0]), feerate + 30);
3705                 assert_eq!(get_feerate!(nodes[1]), feerate + 30);
3706                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
3707         }
3708
3709         #[test]
3710         fn fake_network_test() {
3711                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3712                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
3713                 let nodes = create_network(4);
3714
3715                 // Create some initial channels
3716                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3717                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3718                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3719
3720                 // Rebalance the network a bit by relaying one payment through all the channels...
3721                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3722                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3723                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3724                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
3725
3726                 // Send some more payments
3727                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
3728                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
3729                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
3730
3731                 // Test failure packets
3732                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
3733                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
3734
3735                 // Add a new channel that skips 3
3736                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
3737
3738                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
3739                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
3740                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3741                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3742                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3743                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3744                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
3745
3746                 // Do some rebalance loop payments, simultaneously
3747                 let mut hops = Vec::with_capacity(3);
3748                 hops.push(RouteHop {
3749                         pubkey: nodes[2].node.get_our_node_id(),
3750                         short_channel_id: chan_2.0.contents.short_channel_id,
3751                         fee_msat: 0,
3752                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3753                 });
3754                 hops.push(RouteHop {
3755                         pubkey: nodes[3].node.get_our_node_id(),
3756                         short_channel_id: chan_3.0.contents.short_channel_id,
3757                         fee_msat: 0,
3758                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3759                 });
3760                 hops.push(RouteHop {
3761                         pubkey: nodes[1].node.get_our_node_id(),
3762                         short_channel_id: chan_4.0.contents.short_channel_id,
3763                         fee_msat: 1000000,
3764                         cltv_expiry_delta: TEST_FINAL_CLTV,
3765                 });
3766                 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;
3767                 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;
3768                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3769
3770                 let mut hops = Vec::with_capacity(3);
3771                 hops.push(RouteHop {
3772                         pubkey: nodes[3].node.get_our_node_id(),
3773                         short_channel_id: chan_4.0.contents.short_channel_id,
3774                         fee_msat: 0,
3775                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3776                 });
3777                 hops.push(RouteHop {
3778                         pubkey: nodes[2].node.get_our_node_id(),
3779                         short_channel_id: chan_3.0.contents.short_channel_id,
3780                         fee_msat: 0,
3781                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3782                 });
3783                 hops.push(RouteHop {
3784                         pubkey: nodes[1].node.get_our_node_id(),
3785                         short_channel_id: chan_2.0.contents.short_channel_id,
3786                         fee_msat: 1000000,
3787                         cltv_expiry_delta: TEST_FINAL_CLTV,
3788                 });
3789                 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;
3790                 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;
3791                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3792
3793                 // Claim the rebalances...
3794                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3795                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3796
3797                 // Add a duplicate new channel from 2 to 4
3798                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3799
3800                 // Send some payments across both channels
3801                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3802                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3803                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3804
3805                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3806
3807                 //TODO: Test that routes work again here as we've been notified that the channel is full
3808
3809                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3810                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3811                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3812
3813                 // Close down the channels...
3814                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3815                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3816                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3817                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3818                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3819         }
3820
3821         #[test]
3822         fn duplicate_htlc_test() {
3823                 // Test that we accept duplicate payment_hash HTLCs across the network and that
3824                 // claiming/failing them are all separate and don't effect each other
3825                 let mut nodes = create_network(6);
3826
3827                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
3828                 create_announced_chan_between_nodes(&nodes, 0, 3);
3829                 create_announced_chan_between_nodes(&nodes, 1, 3);
3830                 create_announced_chan_between_nodes(&nodes, 2, 3);
3831                 create_announced_chan_between_nodes(&nodes, 3, 4);
3832                 create_announced_chan_between_nodes(&nodes, 3, 5);
3833
3834                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
3835
3836                 *nodes[0].network_payment_count.borrow_mut() -= 1;
3837                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
3838
3839                 *nodes[0].network_payment_count.borrow_mut() -= 1;
3840                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
3841
3842                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
3843                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
3844                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
3845         }
3846
3847         #[derive(PartialEq)]
3848         enum HTLCType { NONE, TIMEOUT, SUCCESS }
3849         /// Tests that the given node has broadcast transactions for the given Channel
3850         ///
3851         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
3852         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
3853         /// broadcast and the revoked outputs were claimed.
3854         ///
3855         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
3856         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
3857         ///
3858         /// All broadcast transactions must be accounted for in one of the above three types of we'll
3859         /// also fail.
3860         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
3861                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3862                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
3863
3864                 let mut res = Vec::with_capacity(2);
3865                 node_txn.retain(|tx| {
3866                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
3867                                 check_spends!(tx, chan.3.clone());
3868                                 if commitment_tx.is_none() {
3869                                         res.push(tx.clone());
3870                                 }
3871                                 false
3872                         } else { true }
3873                 });
3874                 if let Some(explicit_tx) = commitment_tx {
3875                         res.push(explicit_tx.clone());
3876                 }
3877
3878                 assert_eq!(res.len(), 1);
3879
3880                 if has_htlc_tx != HTLCType::NONE {
3881                         node_txn.retain(|tx| {
3882                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
3883                                         check_spends!(tx, res[0].clone());
3884                                         if has_htlc_tx == HTLCType::TIMEOUT {
3885                                                 assert!(tx.lock_time != 0);
3886                                         } else {
3887                                                 assert!(tx.lock_time == 0);
3888                                         }
3889                                         res.push(tx.clone());
3890                                         false
3891                                 } else { true }
3892                         });
3893                         assert_eq!(res.len(), 2);
3894                 }
3895
3896                 assert!(node_txn.is_empty());
3897                 res
3898         }
3899
3900         /// Tests that the given node has broadcast a claim transaction against the provided revoked
3901         /// HTLC transaction.
3902         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
3903                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3904                 assert_eq!(node_txn.len(), 1);
3905                 node_txn.retain(|tx| {
3906                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
3907                                 check_spends!(tx, revoked_tx.clone());
3908                                 false
3909                         } else { true }
3910                 });
3911                 assert!(node_txn.is_empty());
3912         }
3913
3914         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
3915                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3916
3917                 assert!(node_txn.len() >= 1);
3918                 assert_eq!(node_txn[0].input.len(), 1);
3919                 let mut found_prev = false;
3920
3921                 for tx in prev_txn {
3922                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
3923                                 check_spends!(node_txn[0], tx.clone());
3924                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
3925                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
3926
3927                                 found_prev = true;
3928                                 break;
3929                         }
3930                 }
3931                 assert!(found_prev);
3932
3933                 let mut res = Vec::new();
3934                 mem::swap(&mut *node_txn, &mut res);
3935                 res
3936         }
3937
3938         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
3939                 let events_1 = nodes[a].node.get_and_clear_pending_events();
3940                 assert_eq!(events_1.len(), 1);
3941                 let as_update = match events_1[0] {
3942                         Event::BroadcastChannelUpdate { ref msg } => {
3943                                 msg.clone()
3944                         },
3945                         _ => panic!("Unexpected event"),
3946                 };
3947
3948                 let events_2 = nodes[b].node.get_and_clear_pending_events();
3949                 assert_eq!(events_2.len(), 1);
3950                 let bs_update = match events_2[0] {
3951                         Event::BroadcastChannelUpdate { ref msg } => {
3952                                 msg.clone()
3953                         },
3954                         _ => panic!("Unexpected event"),
3955                 };
3956
3957                 for node in nodes {
3958                         node.router.handle_channel_update(&as_update).unwrap();
3959                         node.router.handle_channel_update(&bs_update).unwrap();
3960                 }
3961         }
3962
3963         #[test]
3964         fn channel_reserve_test() {
3965                 use util::rng;
3966                 use std::sync::atomic::Ordering;
3967                 use ln::msgs::HandleError;
3968
3969                 macro_rules! get_channel_value_stat {
3970                         ($node: expr, $channel_id: expr) => {{
3971                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3972                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3973                                 chan.get_value_stat()
3974                         }}
3975                 }
3976
3977                 let mut nodes = create_network(3);
3978                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
3979                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
3980
3981                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
3982                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
3983
3984                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
3985                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
3986
3987                 macro_rules! get_route_and_payment_hash {
3988                         ($recv_value: expr) => {{
3989                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
3990                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3991                                 (route, payment_hash, payment_preimage)
3992                         }}
3993                 };
3994
3995                 macro_rules! expect_pending_htlcs_forwardable {
3996                         ($node: expr) => {{
3997                                 let events = $node.node.get_and_clear_pending_events();
3998                                 assert_eq!(events.len(), 1);
3999                                 match events[0] {
4000                                         Event::PendingHTLCsForwardable { .. } => { },
4001                                         _ => panic!("Unexpected event"),
4002                                 };
4003                                 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4004                                 $node.node.process_pending_htlc_forwards();
4005                         }}
4006                 };
4007
4008                 macro_rules! expect_forward {
4009                         ($node: expr) => {{
4010                                 let mut events = $node.node.get_and_clear_pending_events();
4011                                 assert_eq!(events.len(), 1);
4012                                 check_added_monitors!($node, 1);
4013                                 let payment_event = SendEvent::from_event(events.remove(0));
4014                                 payment_event
4015                         }}
4016                 }
4017
4018                 macro_rules! expect_payment_received {
4019                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
4020                                 let events = $node.node.get_and_clear_pending_events();
4021                                 assert_eq!(events.len(), 1);
4022                                 match events[0] {
4023                                         Event::PaymentReceived { ref payment_hash, amt } => {
4024                                                 assert_eq!($expected_payment_hash, *payment_hash);
4025                                                 assert_eq!($expected_recv_value, amt);
4026                                         },
4027                                         _ => panic!("Unexpected event"),
4028                                 }
4029                         }
4030                 };
4031
4032                 let feemsat = 239; // somehow we know?
4033                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
4034
4035                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
4036
4037                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
4038                 {
4039                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
4040                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
4041                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
4042                         match err {
4043                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4044                                 _ => panic!("Unknown error variants"),
4045                         }
4046                 }
4047
4048                 let mut htlc_id = 0;
4049                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
4050                 // nodes[0]'s wealth
4051                 loop {
4052                         let amt_msat = recv_value_0 + total_fee_msat;
4053                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
4054                                 break;
4055                         }
4056                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
4057                         htlc_id += 1;
4058
4059                         let (stat01_, stat11_, stat12_, stat22_) = (
4060                                 get_channel_value_stat!(nodes[0], chan_1.2),
4061                                 get_channel_value_stat!(nodes[1], chan_1.2),
4062                                 get_channel_value_stat!(nodes[1], chan_2.2),
4063                                 get_channel_value_stat!(nodes[2], chan_2.2),
4064                         );
4065
4066                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
4067                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
4068                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
4069                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
4070                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
4071                 }
4072
4073                 {
4074                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
4075                         // attempt to get channel_reserve violation
4076                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
4077                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
4078                         match err {
4079                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4080                                 _ => panic!("Unknown error variants"),
4081                         }
4082                 }
4083
4084                 // adding pending output
4085                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
4086                 let amt_msat_1 = recv_value_1 + total_fee_msat;
4087
4088                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
4089                 let payment_event_1 = {
4090                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
4091                         check_added_monitors!(nodes[0], 1);
4092
4093                         let mut events = nodes[0].node.get_and_clear_pending_events();
4094                         assert_eq!(events.len(), 1);
4095                         SendEvent::from_event(events.remove(0))
4096                 };
4097                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
4098
4099                 // channel reserve test with htlc pending output > 0
4100                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
4101                 {
4102                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4103                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4104                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4105                                 _ => panic!("Unknown error variants"),
4106                         }
4107                 }
4108
4109                 {
4110                         // test channel_reserve test on nodes[1] side
4111                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
4112
4113                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
4114                         let secp_ctx = Secp256k1::new();
4115                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
4116                                 let mut session_key = [0; 32];
4117                                 rng::fill_bytes(&mut session_key);
4118                                 session_key
4119                         }).expect("RNG is bad!");
4120
4121                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4122                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
4123                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
4124                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
4125                         let msg = msgs::UpdateAddHTLC {
4126                                 channel_id: chan_1.2,
4127                                 htlc_id,
4128                                 amount_msat: htlc_msat,
4129                                 payment_hash: our_payment_hash,
4130                                 cltv_expiry: htlc_cltv,
4131                                 onion_routing_packet: onion_packet,
4132                         };
4133
4134                         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
4135                         match err {
4136                                 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
4137                         }
4138                 }
4139
4140                 // split the rest to test holding cell
4141                 let recv_value_21 = recv_value_2/2;
4142                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
4143                 {
4144                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
4145                         assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat), stat.channel_reserve_msat);
4146                 }
4147
4148                 // now see if they go through on both sides
4149                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
4150                 // but this will stuck in the holding cell
4151                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
4152                 check_added_monitors!(nodes[0], 0);
4153                 let events = nodes[0].node.get_and_clear_pending_events();
4154                 assert_eq!(events.len(), 0);
4155
4156                 // test with outbound holding cell amount > 0
4157                 {
4158                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
4159                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
4160                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
4161                                 _ => panic!("Unknown error variants"),
4162                         }
4163                 }
4164
4165                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
4166                 // this will also stuck in the holding cell
4167                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
4168                 check_added_monitors!(nodes[0], 0);
4169                 let events = nodes[0].node.get_and_clear_pending_events();
4170                 assert_eq!(events.len(), 0);
4171
4172                 // flush the pending htlc
4173                 let (as_revoke_and_ack, as_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
4174                 check_added_monitors!(nodes[1], 1);
4175
4176                 let commitment_update_2 = nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap().unwrap();
4177                 check_added_monitors!(nodes[0], 1);
4178                 let (bs_revoke_and_ack, bs_none) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
4179                 assert!(bs_none.is_none());
4180                 check_added_monitors!(nodes[0], 1);
4181                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4182                 check_added_monitors!(nodes[1], 1);
4183
4184                 expect_pending_htlcs_forwardable!(nodes[1]);
4185
4186                 let ref payment_event_11 = expect_forward!(nodes[1]);
4187                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
4188                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
4189
4190                 expect_pending_htlcs_forwardable!(nodes[2]);
4191                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
4192
4193                 // flush the htlcs in the holding cell
4194                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
4195                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
4196                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
4197                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
4198                 expect_pending_htlcs_forwardable!(nodes[1]);
4199
4200                 let ref payment_event_3 = expect_forward!(nodes[1]);
4201                 assert_eq!(payment_event_3.msgs.len(), 2);
4202                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
4203                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
4204
4205                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
4206                 expect_pending_htlcs_forwardable!(nodes[2]);
4207
4208                 let events = nodes[2].node.get_and_clear_pending_events();
4209                 assert_eq!(events.len(), 2);
4210                 match events[0] {
4211                         Event::PaymentReceived { ref payment_hash, amt } => {
4212                                 assert_eq!(our_payment_hash_21, *payment_hash);
4213                                 assert_eq!(recv_value_21, amt);
4214                         },
4215                         _ => panic!("Unexpected event"),
4216                 }
4217                 match events[1] {
4218                         Event::PaymentReceived { ref payment_hash, amt } => {
4219                                 assert_eq!(our_payment_hash_22, *payment_hash);
4220                                 assert_eq!(recv_value_22, amt);
4221                         },
4222                         _ => panic!("Unexpected event"),
4223                 }
4224
4225                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
4226                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
4227                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
4228
4229                 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat);
4230                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
4231                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
4232                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
4233
4234                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
4235                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
4236         }
4237
4238         #[test]
4239         fn channel_monitor_network_test() {
4240                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
4241                 // tests that ChannelMonitor is able to recover from various states.
4242                 let nodes = create_network(5);
4243
4244                 // Create some initial channels
4245                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4246                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4247                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4248                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4249
4250                 // Rebalance the network a bit by relaying one payment through all the channels...
4251                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4252                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4253                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4254                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
4255
4256                 // Simple case with no pending HTLCs:
4257                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
4258                 {
4259                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
4260                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4261                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4262                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
4263                 }
4264                 get_announce_close_broadcast_events(&nodes, 0, 1);
4265                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4266                 assert_eq!(nodes[1].node.list_channels().len(), 1);
4267
4268                 // One pending HTLC is discarded by the force-close:
4269                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
4270
4271                 // Simple case of one pending HTLC to HTLC-Timeout
4272                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
4273                 {
4274                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
4275                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4276                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
4277                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
4278                 }
4279                 get_announce_close_broadcast_events(&nodes, 1, 2);
4280                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4281                 assert_eq!(nodes[2].node.list_channels().len(), 1);
4282
4283                 macro_rules! claim_funds {
4284                         ($node: expr, $prev_node: expr, $preimage: expr) => {
4285                                 {
4286                                         assert!($node.node.claim_funds($preimage));
4287                                         check_added_monitors!($node, 1);
4288
4289                                         let events = $node.node.get_and_clear_pending_events();
4290                                         assert_eq!(events.len(), 1);
4291                                         match events[0] {
4292                                                 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
4293                                                         assert!(update_add_htlcs.is_empty());
4294                                                         assert!(update_fail_htlcs.is_empty());
4295                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
4296                                                 },
4297                                                 _ => panic!("Unexpected event"),
4298                                         };
4299                                 }
4300                         }
4301                 }
4302
4303                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
4304                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
4305                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
4306                 {
4307                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
4308
4309                         // Claim the payment on nodes[3], giving it knowledge of the preimage
4310                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
4311
4312                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4313                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
4314
4315                         check_preimage_claim(&nodes[3], &node_txn);
4316                 }
4317                 get_announce_close_broadcast_events(&nodes, 2, 3);
4318                 assert_eq!(nodes[2].node.list_channels().len(), 0);
4319                 assert_eq!(nodes[3].node.list_channels().len(), 1);
4320
4321                 { // Cheat and reset nodes[4]'s height to 1
4322                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4323                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
4324                 }
4325
4326                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
4327                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
4328                 // One pending HTLC to time out:
4329                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
4330                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
4331                 // buffer space).
4332
4333                 {
4334                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4335                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4336                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
4337                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4338                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4339                         }
4340
4341                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
4342
4343                         // Claim the payment on nodes[4], giving it knowledge of the preimage
4344                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
4345
4346                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4347                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
4348                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
4349                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4350                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
4351                         }
4352
4353                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
4354
4355                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4356                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
4357
4358                         check_preimage_claim(&nodes[4], &node_txn);
4359                 }
4360                 get_announce_close_broadcast_events(&nodes, 3, 4);
4361                 assert_eq!(nodes[3].node.list_channels().len(), 0);
4362                 assert_eq!(nodes[4].node.list_channels().len(), 0);
4363
4364                 // Create some new channels:
4365                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
4366
4367                 // A pending HTLC which will be revoked:
4368                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4369                 // Get the will-be-revoked local txn from nodes[0]
4370                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
4371                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
4372                 assert_eq!(revoked_local_txn[0].input.len(), 1);
4373                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
4374                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
4375                 assert_eq!(revoked_local_txn[1].input.len(), 1);
4376                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4377                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4378                 // Revoke the old state
4379                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
4380
4381                 {
4382                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4383                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4384                         {
4385                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4386                                 assert_eq!(node_txn.len(), 3);
4387                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
4388                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
4389
4390                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4391                                 node_txn.swap_remove(0);
4392                         }
4393                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
4394
4395                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4396                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
4397                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4398                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
4399                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
4400                 }
4401                 get_announce_close_broadcast_events(&nodes, 0, 1);
4402                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4403                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4404         }
4405
4406         #[test]
4407         fn revoked_output_claim() {
4408                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
4409                 // transaction is broadcast by its counterparty
4410                 let nodes = create_network(2);
4411                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4412                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
4413                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4414                 assert_eq!(revoked_local_txn.len(), 1);
4415                 // Only output is the full channel value back to nodes[0]:
4416                 assert_eq!(revoked_local_txn[0].output.len(), 1);
4417                 // Send a payment through, updating everyone's latest commitment txn
4418                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
4419
4420                 // Inform nodes[1] that nodes[0] broadcast a stale tx
4421                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4422                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4423                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4424                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
4425
4426                 assert_eq!(node_txn[0], node_txn[2]);
4427
4428                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
4429                 check_spends!(node_txn[1], chan_1.3.clone());
4430
4431                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
4432                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4433                 get_announce_close_broadcast_events(&nodes, 0, 1);
4434         }
4435
4436         #[test]
4437         fn claim_htlc_outputs_shared_tx() {
4438                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
4439                 let nodes = create_network(2);
4440
4441                 // Create some new channel:
4442                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4443
4444                 // Rebalance the network to generate htlc in the two directions
4445                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4446                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
4447                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4448                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4449
4450                 // Get the will-be-revoked local txn from node[0]
4451                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4452                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
4453                 assert_eq!(revoked_local_txn[0].input.len(), 1);
4454                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4455                 assert_eq!(revoked_local_txn[1].input.len(), 1);
4456                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
4457                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), 133); // HTLC-Timeout
4458                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
4459
4460                 //Revoke the old state
4461                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4462
4463                 {
4464                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4465
4466                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4467
4468                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4469                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4470                         assert_eq!(node_txn.len(), 4);
4471
4472                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
4473                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
4474
4475                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
4476
4477                         let mut witness_lens = BTreeSet::new();
4478                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4479                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
4480                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
4481                         assert_eq!(witness_lens.len(), 3);
4482                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4483                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4484                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4485
4486                         // Next nodes[1] broadcasts its current local tx state:
4487                         assert_eq!(node_txn[1].input.len(), 1);
4488                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
4489
4490                         assert_eq!(node_txn[2].input.len(), 1);
4491                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
4492                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4493                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
4494                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4495                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
4496                 }
4497                 get_announce_close_broadcast_events(&nodes, 0, 1);
4498                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4499                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4500         }
4501
4502         #[test]
4503         fn claim_htlc_outputs_single_tx() {
4504                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
4505                 let nodes = create_network(2);
4506
4507                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4508
4509                 // Rebalance the network to generate htlc in the two directions
4510                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4511                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
4512                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
4513                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4514                 let _payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
4515
4516                 // Get the will-be-revoked local txn from node[0]
4517                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4518
4519                 //Revoke the old state
4520                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
4521
4522                 {
4523                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4524
4525                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4526
4527                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
4528                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4529                         assert_eq!(node_txn.len(), 12); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan)
4530
4531                         assert_eq!(node_txn[0], node_txn[7]);
4532                         assert_eq!(node_txn[1], node_txn[8]);
4533                         assert_eq!(node_txn[2], node_txn[9]);
4534                         assert_eq!(node_txn[3], node_txn[10]);
4535                         assert_eq!(node_txn[4], node_txn[11]);
4536                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
4537                         assert_eq!(node_txn[4], node_txn[6]);
4538
4539                         assert_eq!(node_txn[0].input.len(), 1);
4540                         assert_eq!(node_txn[1].input.len(), 1);
4541                         assert_eq!(node_txn[2].input.len(), 1);
4542
4543                         let mut revoked_tx_map = HashMap::new();
4544                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
4545                         node_txn[0].verify(&revoked_tx_map).unwrap();
4546                         node_txn[1].verify(&revoked_tx_map).unwrap();
4547                         node_txn[2].verify(&revoked_tx_map).unwrap();
4548
4549                         let mut witness_lens = BTreeSet::new();
4550                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
4551                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
4552                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
4553                         assert_eq!(witness_lens.len(), 3);
4554                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
4555                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), 133); // revoked offered HTLC
4556                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), 138); // revoked received HTLC
4557
4558                         assert_eq!(node_txn[3].input.len(), 1);
4559                         check_spends!(node_txn[3], chan_1.3.clone());
4560
4561                         assert_eq!(node_txn[4].input.len(), 1);
4562                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
4563                         assert_eq!(witness_script.len(), 133); //Spending an offered htlc output
4564                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
4565                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
4566                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
4567                 }
4568                 get_announce_close_broadcast_events(&nodes, 0, 1);
4569                 assert_eq!(nodes[0].node.list_channels().len(), 0);
4570                 assert_eq!(nodes[1].node.list_channels().len(), 0);
4571         }
4572
4573         #[test]
4574         fn test_htlc_ignore_latest_remote_commitment() {
4575                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
4576                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
4577                 let nodes = create_network(2);
4578                 create_announced_chan_between_nodes(&nodes, 0, 1);
4579
4580                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
4581                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
4582                 {
4583                         let events = nodes[0].node.get_and_clear_pending_events();
4584                         assert_eq!(events.len(), 1);
4585                         match events[0] {
4586                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4587                                         assert_eq!(flags & 0b10, 0b10);
4588                                 },
4589                                 _ => panic!("Unexpected event"),
4590                         }
4591                 }
4592
4593                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4594                 assert_eq!(node_txn.len(), 2);
4595
4596                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4597                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4598
4599                 {
4600                         let events = nodes[1].node.get_and_clear_pending_events();
4601                         assert_eq!(events.len(), 1);
4602                         match events[0] {
4603                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4604                                         assert_eq!(flags & 0b10, 0b10);
4605                                 },
4606                                 _ => panic!("Unexpected event"),
4607                         }
4608                 }
4609
4610                 // Duplicate the block_connected call since this may happen due to other listeners
4611                 // registering new transactions
4612                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
4613         }
4614
4615         #[test]
4616         fn test_force_close_fail_back() {
4617                 // Check which HTLCs are failed-backwards on channel force-closure
4618                 let mut nodes = create_network(3);
4619                 create_announced_chan_between_nodes(&nodes, 0, 1);
4620                 create_announced_chan_between_nodes(&nodes, 1, 2);
4621
4622                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
4623
4624                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4625
4626                 let mut payment_event = {
4627                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4628                         check_added_monitors!(nodes[0], 1);
4629
4630                         let mut events = nodes[0].node.get_and_clear_pending_events();
4631                         assert_eq!(events.len(), 1);
4632                         SendEvent::from_event(events.remove(0))
4633                 };
4634
4635                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4636                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4637
4638                 let events_1 = nodes[1].node.get_and_clear_pending_events();
4639                 assert_eq!(events_1.len(), 1);
4640                 match events_1[0] {
4641                         Event::PendingHTLCsForwardable { .. } => { },
4642                         _ => panic!("Unexpected event"),
4643                 };
4644
4645                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
4646                 nodes[1].node.process_pending_htlc_forwards();
4647
4648                 let mut events_2 = nodes[1].node.get_and_clear_pending_events();
4649                 assert_eq!(events_2.len(), 1);
4650                 payment_event = SendEvent::from_event(events_2.remove(0));
4651                 assert_eq!(payment_event.msgs.len(), 1);
4652
4653                 check_added_monitors!(nodes[1], 1);
4654                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4655                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4656                 check_added_monitors!(nodes[2], 1);
4657
4658                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
4659                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
4660                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
4661
4662                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
4663                 let events_3 = nodes[2].node.get_and_clear_pending_events();
4664                 assert_eq!(events_3.len(), 1);
4665                 match events_3[0] {
4666                         Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4667                                 assert_eq!(flags & 0b10, 0b10);
4668                         },
4669                         _ => panic!("Unexpected event"),
4670                 }
4671
4672                 let tx = {
4673                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4674                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
4675                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
4676                         // back to nodes[1] upon timeout otherwise.
4677                         assert_eq!(node_txn.len(), 1);
4678                         node_txn.remove(0)
4679                 };
4680
4681                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4682                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4683
4684                 let events_4 = nodes[1].node.get_and_clear_pending_events();
4685                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
4686                 assert_eq!(events_4.len(), 1);
4687                 match events_4[0] {
4688                         Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4689                                 assert_eq!(flags & 0b10, 0b10);
4690                         },
4691                         _ => panic!("Unexpected event"),
4692                 }
4693
4694                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
4695                 {
4696                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
4697                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
4698                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
4699                 }
4700                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
4701                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
4702                 assert_eq!(node_txn.len(), 1);
4703                 assert_eq!(node_txn[0].input.len(), 1);
4704                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
4705                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
4706                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
4707
4708                 check_spends!(node_txn[0], tx);
4709         }
4710
4711         #[test]
4712         fn test_unconf_chan() {
4713                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
4714                 let nodes = create_network(2);
4715                 create_announced_chan_between_nodes(&nodes, 0, 1);
4716
4717                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4718                 assert_eq!(channel_state.by_id.len(), 1);
4719                 assert_eq!(channel_state.short_to_id.len(), 1);
4720                 mem::drop(channel_state);
4721
4722                 let mut headers = Vec::new();
4723                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4724                 headers.push(header.clone());
4725                 for _i in 2..100 {
4726                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4727                         headers.push(header.clone());
4728                 }
4729                 while !headers.is_empty() {
4730                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
4731                 }
4732                 {
4733                         let events = nodes[0].node.get_and_clear_pending_events();
4734                         assert_eq!(events.len(), 1);
4735                         match events[0] {
4736                                 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
4737                                         assert_eq!(flags & 0b10, 0b10);
4738                                 },
4739                                 _ => panic!("Unexpected event"),
4740                         }
4741                 }
4742                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
4743                 assert_eq!(channel_state.by_id.len(), 0);
4744                 assert_eq!(channel_state.short_to_id.len(), 0);
4745         }
4746
4747         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
4748         /// for claims/fails they are separated out.
4749         fn reconnect_nodes(node_a: &Node, node_b: &Node, pre_all_htlcs: bool, pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool)) {
4750                 let reestablish_1 = node_a.node.peer_connected(&node_b.node.get_our_node_id());
4751                 let reestablish_2 = node_b.node.peer_connected(&node_a.node.get_our_node_id());
4752
4753                 let mut resp_1 = Vec::new();
4754                 for msg in reestablish_1 {
4755                         resp_1.push(node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap());
4756                 }
4757                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4758                         check_added_monitors!(node_b, 1);
4759                 } else {
4760                         check_added_monitors!(node_b, 0);
4761                 }
4762
4763                 let mut resp_2 = Vec::new();
4764                 for msg in reestablish_2 {
4765                         resp_2.push(node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap());
4766                 }
4767                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4768                         check_added_monitors!(node_a, 1);
4769                 } else {
4770                         check_added_monitors!(node_a, 0);
4771                 }
4772
4773                 // We dont yet support both needing updates, as that would require a different commitment dance:
4774                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
4775                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
4776
4777                 for chan_msgs in resp_1.drain(..) {
4778                         if pre_all_htlcs {
4779                                 let a = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
4780                                 let _announcement_sigs_opt = a.unwrap();
4781                                 //TODO: Test announcement_sigs re-sending when we've implemented it
4782                         } else {
4783                                 assert!(chan_msgs.0.is_none());
4784                         }
4785                         if pending_raa.0 {
4786                                 assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4787                                 check_added_monitors!(node_a, 1);
4788                         } else {
4789                                 assert!(chan_msgs.1.is_none());
4790                         }
4791                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
4792                                 let commitment_update = chan_msgs.2.unwrap();
4793                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4794                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
4795                                 } else {
4796                                         assert!(commitment_update.update_add_htlcs.is_empty());
4797                                 }
4798                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4799                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4800                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4801                                 for update_add in commitment_update.update_add_htlcs {
4802                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
4803                                 }
4804                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
4805                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
4806                                 }
4807                                 for update_fail in commitment_update.update_fail_htlcs {
4808                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
4809                                 }
4810
4811                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
4812                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
4813                                 } else {
4814                                         let (as_revoke_and_ack, as_commitment_signed) = node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4815                                         check_added_monitors!(node_a, 1);
4816                                         assert!(as_commitment_signed.is_none());
4817                                         assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
4818                                         check_added_monitors!(node_b, 1);
4819                                 }
4820                         } else {
4821                                 assert!(chan_msgs.2.is_none());
4822                         }
4823                 }
4824
4825                 for chan_msgs in resp_2.drain(..) {
4826                         if pre_all_htlcs {
4827                                 let _announcement_sigs_opt = node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
4828                                 //TODO: Test announcement_sigs re-sending when we've implemented it
4829                         } else {
4830                                 assert!(chan_msgs.0.is_none());
4831                         }
4832                         if pending_raa.1 {
4833                                 assert!(node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap().is_none());
4834                                 check_added_monitors!(node_b, 1);
4835                         } else {
4836                                 assert!(chan_msgs.1.is_none());
4837                         }
4838                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
4839                                 let commitment_update = chan_msgs.2.unwrap();
4840                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
4841                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
4842                                 }
4843                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
4844                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
4845                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4846                                 for update_add in commitment_update.update_add_htlcs {
4847                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
4848                                 }
4849                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
4850                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
4851                                 }
4852                                 for update_fail in commitment_update.update_fail_htlcs {
4853                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
4854                                 }
4855
4856                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
4857                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
4858                                 } else {
4859                                         let (bs_revoke_and_ack, bs_commitment_signed) = node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4860                                         check_added_monitors!(node_b, 1);
4861                                         assert!(bs_commitment_signed.is_none());
4862                                         assert!(node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4863                                         check_added_monitors!(node_a, 1);
4864                                 }
4865                         } else {
4866                                 assert!(chan_msgs.2.is_none());
4867                         }
4868                 }
4869         }
4870
4871         #[test]
4872         fn test_simple_peer_disconnect() {
4873                 // Test that we can reconnect when there are no lost messages
4874                 let nodes = create_network(3);
4875                 create_announced_chan_between_nodes(&nodes, 0, 1);
4876                 create_announced_chan_between_nodes(&nodes, 1, 2);
4877
4878                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4879                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4880                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4881
4882                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
4883                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
4884                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
4885                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
4886
4887                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4888                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4889                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4890
4891                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
4892                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
4893                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
4894                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
4895
4896                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4897                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4898
4899                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
4900                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
4901
4902                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
4903                 {
4904                         let events = nodes[0].node.get_and_clear_pending_events();
4905                         assert_eq!(events.len(), 2);
4906                         match events[0] {
4907                                 Event::PaymentSent { payment_preimage } => {
4908                                         assert_eq!(payment_preimage, payment_preimage_3);
4909                                 },
4910                                 _ => panic!("Unexpected event"),
4911                         }
4912                         match events[1] {
4913                                 Event::PaymentFailed { payment_hash } => {
4914                                         assert_eq!(payment_hash, payment_hash_5);
4915                                 },
4916                                 _ => panic!("Unexpected event"),
4917                         }
4918                 }
4919
4920                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
4921                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
4922         }
4923
4924         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
4925                 // Test that we can reconnect when in-flight HTLC updates get dropped
4926                 let mut nodes = create_network(2);
4927                 if messages_delivered == 0 {
4928                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
4929                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
4930                 } else {
4931                         create_announced_chan_between_nodes(&nodes, 0, 1);
4932                 }
4933
4934                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4935                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
4936
4937                 let payment_event = {
4938                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
4939                         check_added_monitors!(nodes[0], 1);
4940
4941                         let mut events = nodes[0].node.get_and_clear_pending_events();
4942                         assert_eq!(events.len(), 1);
4943                         SendEvent::from_event(events.remove(0))
4944                 };
4945                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
4946
4947                 if messages_delivered < 2 {
4948                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
4949                 } else {
4950                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4951                         let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4952                         check_added_monitors!(nodes[1], 1);
4953
4954                         if messages_delivered >= 3 {
4955                                 assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
4956                                 check_added_monitors!(nodes[0], 1);
4957
4958                                 if messages_delivered >= 4 {
4959                                         let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed.unwrap()).unwrap();
4960                                         assert!(as_commitment_signed.is_none());
4961                                         check_added_monitors!(nodes[0], 1);
4962
4963                                         if messages_delivered >= 5 {
4964                                                 assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
4965                                                 check_added_monitors!(nodes[1], 1);
4966                                         }
4967                                 }
4968                         }
4969                 }
4970
4971                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4972                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4973                 if messages_delivered < 2 {
4974                         // Even if the funding_locked messages get exchanged, as long as nothing further was
4975                         // received on either side, both sides will need to resend them.
4976                         reconnect_nodes(&nodes[0], &nodes[1], true, (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
4977                 } else if messages_delivered == 2 {
4978                         // nodes[0] still wants its RAA + commitment_signed
4979                         reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
4980                 } else if messages_delivered == 3 {
4981                         // nodes[0] still wants its commitment_signed
4982                         reconnect_nodes(&nodes[0], &nodes[1], false, (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
4983                 } else if messages_delivered == 4 {
4984                         // nodes[1] still wants its final RAA
4985                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
4986                 } else if messages_delivered == 5 {
4987                         // Everything was delivered...
4988                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4989                 }
4990
4991                 let events_1 = nodes[1].node.get_and_clear_pending_events();
4992                 assert_eq!(events_1.len(), 1);
4993                 match events_1[0] {
4994                         Event::PendingHTLCsForwardable { .. } => { },
4995                         _ => panic!("Unexpected event"),
4996                 };
4997
4998                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4999                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5000                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5001
5002                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
5003                 nodes[1].node.process_pending_htlc_forwards();
5004
5005                 let events_2 = nodes[1].node.get_and_clear_pending_events();
5006                 assert_eq!(events_2.len(), 1);
5007                 match events_2[0] {
5008                         Event::PaymentReceived { ref payment_hash, amt } => {
5009                                 assert_eq!(payment_hash_1, *payment_hash);
5010                                 assert_eq!(amt, 1000000);
5011                         },
5012                         _ => panic!("Unexpected event"),
5013                 }
5014
5015                 nodes[1].node.claim_funds(payment_preimage_1);
5016                 check_added_monitors!(nodes[1], 1);
5017
5018                 let events_3 = nodes[1].node.get_and_clear_pending_events();
5019                 assert_eq!(events_3.len(), 1);
5020                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
5021                         Event::UpdateHTLCs { ref node_id, ref updates } => {
5022                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5023                                 assert!(updates.update_add_htlcs.is_empty());
5024                                 assert!(updates.update_fail_htlcs.is_empty());
5025                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5026                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5027                                 assert!(updates.update_fee.is_none());
5028                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
5029                         },
5030                         _ => panic!("Unexpected event"),
5031                 };
5032
5033                 if messages_delivered >= 1 {
5034                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
5035
5036                         let events_4 = nodes[0].node.get_and_clear_pending_events();
5037                         assert_eq!(events_4.len(), 1);
5038                         match events_4[0] {
5039                                 Event::PaymentSent { ref payment_preimage } => {
5040                                         assert_eq!(payment_preimage_1, *payment_preimage);
5041                                 },
5042                                 _ => panic!("Unexpected event"),
5043                         }
5044
5045                         if messages_delivered >= 2 {
5046                                 let (as_revoke_and_ack, as_commitment_signed) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
5047                                 check_added_monitors!(nodes[0], 1);
5048
5049                                 if messages_delivered >= 3 {
5050                                         assert!(nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
5051                                         check_added_monitors!(nodes[1], 1);
5052
5053                                         if messages_delivered >= 4 {
5054                                                 let (bs_revoke_and_ack, bs_commitment_signed) = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
5055                                                 assert!(bs_commitment_signed.is_none());
5056                                                 check_added_monitors!(nodes[1], 1);
5057
5058                                                 if messages_delivered >= 5 {
5059                                                         assert!(nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
5060                                                         check_added_monitors!(nodes[0], 1);
5061                                                 }
5062                                         }
5063                                 }
5064                         }
5065                 }
5066
5067                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5068                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5069                 if messages_delivered < 2 {
5070                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
5071                         //TODO: Deduplicate PaymentSent events, then enable this if:
5072                         //if messages_delivered < 1 {
5073                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
5074                                 assert_eq!(events_4.len(), 1);
5075                                 match events_4[0] {
5076                                         Event::PaymentSent { ref payment_preimage } => {
5077                                                 assert_eq!(payment_preimage_1, *payment_preimage);
5078                                         },
5079                                         _ => panic!("Unexpected event"),
5080                                 }
5081                         //}
5082                 } else if messages_delivered == 2 {
5083                         // nodes[0] still wants its RAA + commitment_signed
5084                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
5085                 } else if messages_delivered == 3 {
5086                         // nodes[0] still wants its commitment_signed
5087                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
5088                 } else if messages_delivered == 4 {
5089                         // nodes[1] still wants its final RAA
5090                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
5091                 } else if messages_delivered == 5 {
5092                         // Everything was delivered...
5093                         reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5094                 }
5095
5096                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5097                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5098                 reconnect_nodes(&nodes[0], &nodes[1], false, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5099
5100                 // Channel should still work fine...
5101                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
5102                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
5103         }
5104
5105         #[test]
5106         fn test_drop_messages_peer_disconnect_a() {
5107                 do_test_drop_messages_peer_disconnect(0);
5108                 do_test_drop_messages_peer_disconnect(1);
5109                 do_test_drop_messages_peer_disconnect(2);
5110         }
5111
5112         #[test]
5113         fn test_drop_messages_peer_disconnect_b() {
5114                 do_test_drop_messages_peer_disconnect(3);
5115                 do_test_drop_messages_peer_disconnect(4);
5116                 do_test_drop_messages_peer_disconnect(5);
5117         }
5118
5119         #[test]
5120         fn test_funding_peer_disconnect() {
5121                 // Test that we can lock in our funding tx while disconnected
5122                 let nodes = create_network(2);
5123                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
5124
5125                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5126                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5127
5128                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
5129                 let events_1 = nodes[0].node.get_and_clear_pending_events();
5130                 assert_eq!(events_1.len(), 1);
5131                 match events_1[0] {
5132                         Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5133                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5134                                 assert!(announcement_sigs.is_none());
5135                         },
5136                         _ => panic!("Unexpected event"),
5137                 }
5138
5139                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
5140                 let events_2 = nodes[1].node.get_and_clear_pending_events();
5141                 assert_eq!(events_2.len(), 1);
5142                 match events_2[0] {
5143                         Event::SendFundingLocked { ref node_id, msg: _, ref announcement_sigs } => {
5144                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
5145                                 assert!(announcement_sigs.is_none());
5146                         },
5147                         _ => panic!("Unexpected event"),
5148                 }
5149
5150                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5151                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5152                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5153                 reconnect_nodes(&nodes[0], &nodes[1], true, (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5154
5155                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
5156                 // rebroadcasting announcement_signatures upon reconnect.
5157
5158                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5159                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
5160                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
5161         }
5162
5163         #[test]
5164         fn test_invalid_channel_announcement() {
5165                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
5166                 let secp_ctx = Secp256k1::new();
5167                 let nodes = create_network(2);
5168
5169                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
5170
5171                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
5172                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
5173                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5174                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
5175
5176                 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
5177
5178                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
5179                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
5180
5181                 let as_network_key = nodes[0].node.get_our_node_id();
5182                 let bs_network_key = nodes[1].node.get_our_node_id();
5183
5184                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
5185
5186                 let mut chan_announcement;
5187
5188                 macro_rules! dummy_unsigned_msg {
5189                         () => {
5190                                 msgs::UnsignedChannelAnnouncement {
5191                                         features: msgs::GlobalFeatures::new(),
5192                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
5193                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
5194                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
5195                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
5196                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
5197                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
5198                                         excess_data: Vec::new(),
5199                                 };
5200                         }
5201                 }
5202
5203                 macro_rules! sign_msg {
5204                         ($unsigned_msg: expr) => {
5205                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
5206                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
5207                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
5208                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
5209                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
5210                                 chan_announcement = msgs::ChannelAnnouncement {
5211                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
5212                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
5213                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
5214                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
5215                                         contents: $unsigned_msg
5216                                 }
5217                         }
5218                 }
5219
5220                 let unsigned_msg = dummy_unsigned_msg!();
5221                 sign_msg!(unsigned_msg);
5222                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
5223                 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
5224
5225                 // Configured with Network::Testnet
5226                 let mut unsigned_msg = dummy_unsigned_msg!();
5227                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
5228                 sign_msg!(unsigned_msg);
5229                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5230
5231                 let mut unsigned_msg = dummy_unsigned_msg!();
5232                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
5233                 sign_msg!(unsigned_msg);
5234                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
5235         }
5236 }