]> git.bitcoin.ninja Git - rust-lightning/blob - src/ln/channelmanager.rs
Typify payment_hash and payment_preimage
[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::util::hash::{BitcoinHash, Sha256dHash};
16
17 use secp256k1::key::{SecretKey,PublicKey};
18 use secp256k1::{Secp256k1,Message};
19 use secp256k1::ecdh::SharedSecret;
20 use secp256k1;
21
22 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
23 use chain::transaction::OutPoint;
24 use ln::channel::{Channel, ChannelError};
25 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS};
26 use ln::router::{Route,RouteHop};
27 use ln::msgs;
28 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
29 use chain::keysinterface::KeysInterface;
30 use util::config::UserConfig;
31 use util::{byte_utils, events, internal_traits, rng};
32 use util::sha2::Sha256;
33 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
34 use util::chacha20poly1305rfc::ChaCha20;
35 use util::logger::Logger;
36 use util::errors::APIError;
37
38 use crypto;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
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 ln::channelmanager::PaymentHash;
67         use secp256k1::key::SecretKey;
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: [u8; 32],
74                 pub(super) payment_hash: PaymentHash,
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, PartialEq)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: [u8; 32],
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone, PartialEq)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                         /// Technically we can recalculate this from the route, but we cache it here to avoid
109                         /// doing a double-pass on route when we get a failure back
110                         first_hop_htlc_msat: u64,
111                 },
112         }
113         #[cfg(test)]
114         impl HTLCSource {
115                 pub fn dummy() -> Self {
116                         HTLCSource::OutboundRoute {
117                                 route: Route { hops: Vec::new() },
118                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119                                 first_hop_htlc_msat: 0,
120                         }
121                 }
122         }
123
124         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125         pub(crate) enum HTLCFailReason {
126                 ErrorPacket {
127                         err: msgs::OnionErrorPacket,
128                 },
129                 Reason {
130                         failure_code: u16,
131                         data: Vec<u8>,
132                 }
133         }
134 }
135 pub(super) use self::channel_held_info::*;
136
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
143
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
145
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
151
152 struct MsgHandleErrInternal {
153         err: msgs::HandleError,
154         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
155 }
156 impl MsgHandleErrInternal {
157         #[inline]
158         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
159                 Self {
160                         err: HandleError {
161                                 err,
162                                 action: Some(msgs::ErrorAction::SendErrorMessage {
163                                         msg: msgs::ErrorMessage {
164                                                 channel_id,
165                                                 data: err.to_string()
166                                         },
167                                 }),
168                         },
169                         shutdown_finish: None,
170                 }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, shutdown_finish: None }
175         }
176         #[inline]
177         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
178                 Self {
179                         err: HandleError {
180                                 err,
181                                 action: Some(msgs::ErrorAction::SendErrorMessage {
182                                         msg: msgs::ErrorMessage {
183                                                 channel_id,
184                                                 data: err.to_string()
185                                         },
186                                 }),
187                         },
188                         shutdown_finish: Some((shutdown_res, channel_update)),
189                 }
190         }
191         #[inline]
192         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
193                 Self {
194                         err: match err {
195                                 ChannelError::Ignore(msg) => HandleError {
196                                         err: msg,
197                                         action: Some(msgs::ErrorAction::IgnoreError),
198                                 },
199                                 ChannelError::Close(msg) => HandleError {
200                                         err: msg,
201                                         action: Some(msgs::ErrorAction::SendErrorMessage {
202                                                 msg: msgs::ErrorMessage {
203                                                         channel_id,
204                                                         data: msg.to_string()
205                                                 },
206                                         }),
207                                 },
208                         },
209                         shutdown_finish: None,
210                 }
211         }
212 }
213
214 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
215 /// after a PaymentReceived event.
216 #[derive(PartialEq)]
217 pub enum PaymentFailReason {
218         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
219         PreimageUnknown,
220         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
221         AmountMismatch,
222 }
223
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
229
230 struct HTLCForwardInfo {
231         prev_short_channel_id: u64,
232         prev_htlc_id: u64,
233         forward_info: PendingForwardHTLCInfo,
234 }
235
236 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
237 /// be sent in the order they appear in the return value, however sometimes the order needs to be
238 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
239 /// they were originally sent). In those cases, this enum is also returned.
240 #[derive(Clone, PartialEq)]
241 pub(super) enum RAACommitmentOrder {
242         /// Send the CommitmentUpdate messages first
243         CommitmentFirst,
244         /// Send the RevokeAndACK message first
245         RevokeAndACKFirst,
246 }
247
248 struct ChannelHolder {
249         by_id: HashMap<[u8; 32], Channel>,
250         short_to_id: HashMap<u64, [u8; 32]>,
251         next_forward: Instant,
252         /// short channel id -> forward infos. Key of 0 means payments received
253         /// Note that while this is held in the same mutex as the channels themselves, no consistency
254         /// guarantees are made about there existing a channel with the short id here, nor the short
255         /// ids in the PendingForwardHTLCInfo!
256         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
257         /// Note that while this is held in the same mutex as the channels themselves, no consistency
258         /// guarantees are made about the channels given here actually existing anymore by the time you
259         /// go to read them!
260         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
262         /// for broadcast messages, where ordering isn't as strict).
263         pending_msg_events: Vec<events::MessageSendEvent>,
264 }
265 struct MutChannelHolder<'a> {
266         by_id: &'a mut HashMap<[u8; 32], Channel>,
267         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
268         next_forward: &'a mut Instant,
269         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
270         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
271         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
272 }
273 impl ChannelHolder {
274         fn borrow_parts(&mut self) -> MutChannelHolder {
275                 MutChannelHolder {
276                         by_id: &mut self.by_id,
277                         short_to_id: &mut self.short_to_id,
278                         next_forward: &mut self.next_forward,
279                         forward_htlcs: &mut self.forward_htlcs,
280                         claimable_htlcs: &mut self.claimable_htlcs,
281                         pending_msg_events: &mut self.pending_msg_events,
282                 }
283         }
284 }
285
286 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
287 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
288
289 /// Manager which keeps track of a number of channels and sends messages to the appropriate
290 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
291 ///
292 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
293 /// to individual Channels.
294 ///
295 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
296 /// all peers during write/read (though does not modify this instance, only the instance being
297 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
298 /// called funding_transaction_generated for outbound channels).
299 ///
300 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
301 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
302 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
303 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
304 /// the serialization process). If the deserialized version is out-of-date compared to the
305 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
306 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
307 ///
308 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
309 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
310 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
311 /// block_connected() to step towards your best block) upon deserialization before using the
312 /// object!
313 pub struct ChannelManager {
314         default_configuration: UserConfig,
315         genesis_hash: Sha256dHash,
316         fee_estimator: Arc<FeeEstimator>,
317         monitor: Arc<ManyChannelMonitor>,
318         chain_monitor: Arc<ChainWatchInterface>,
319         tx_broadcaster: Arc<BroadcasterInterface>,
320
321         latest_block_height: AtomicUsize,
322         last_block_hash: Mutex<Sha256dHash>,
323         secp_ctx: Secp256k1<secp256k1::All>,
324
325         channel_state: Mutex<ChannelHolder>,
326         our_network_key: SecretKey,
327
328         pending_events: Mutex<Vec<events::Event>>,
329         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
330         /// Essentially just when we're serializing ourselves out.
331         /// Taken first everywhere where we are making changes before any other locks.
332         total_consistency_lock: RwLock<()>,
333
334         keys_manager: Arc<KeysInterface>,
335
336         logger: Arc<Logger>,
337 }
338
339 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
340 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
341 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
342 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
343 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
344 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
345 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
346
347 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS, ie that
348 // if the next-hop peer fails the HTLC within HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have
349 // HTLC_FAIL_TIMEOUT_BLOCKS left to fail it backwards ourselves before hitting the
350 // CLTV_CLAIM_BUFFER point and failing the channel on-chain to time out the HTLC.
351 #[deny(const_err)]
352 #[allow(dead_code)]
353 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER;
354
355 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
356 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
357 #[deny(const_err)]
358 #[allow(dead_code)]
359 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
360
361 macro_rules! secp_call {
362         ( $res: expr, $err: expr ) => {
363                 match $res {
364                         Ok(key) => key,
365                         Err(_) => return Err($err),
366                 }
367         };
368 }
369
370 struct OnionKeys {
371         #[cfg(test)]
372         shared_secret: SharedSecret,
373         #[cfg(test)]
374         blinding_factor: [u8; 32],
375         ephemeral_pubkey: PublicKey,
376         rho: [u8; 32],
377         mu: [u8; 32],
378 }
379
380 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
381 pub struct ChannelDetails {
382         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
383         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
384         /// Note that this means this value is *not* persistent - it can change once during the
385         /// lifetime of the channel.
386         pub channel_id: [u8; 32],
387         /// The position of the funding transaction in the chain. None if the funding transaction has
388         /// not yet been confirmed and the channel fully opened.
389         pub short_channel_id: Option<u64>,
390         /// The node_id of our counterparty
391         pub remote_network_id: PublicKey,
392         /// The value, in satoshis, of this channel as appears in the funding output
393         pub channel_value_satoshis: u64,
394         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
395         pub user_id: u64,
396 }
397
398 macro_rules! handle_error {
399         ($self: ident, $internal: expr, $their_node_id: expr) => {
400                 match $internal {
401                         Ok(msg) => Ok(msg),
402                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
403                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
404                                         $self.finish_force_close_channel(shutdown_res);
405                                         if let Some(update) = update_option {
406                                                 let mut channel_state = $self.channel_state.lock().unwrap();
407                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
408                                                         msg: update
409                                                 });
410                                         }
411                                 }
412                                 Err(err)
413                         },
414                 }
415         }
416 }
417
418 macro_rules! break_chan_entry {
419         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
420                 match $res {
421                         Ok(res) => res,
422                         Err(ChannelError::Ignore(msg)) => {
423                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
424                         },
425                         Err(ChannelError::Close(msg)) => {
426                                 let (channel_id, mut chan) = $entry.remove_entry();
427                                 if let Some(short_id) = chan.get_short_channel_id() {
428                                         $channel_state.short_to_id.remove(&short_id);
429                                 }
430                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
431                         },
432                 }
433         }
434 }
435
436 macro_rules! try_chan_entry {
437         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
438                 match $res {
439                         Ok(res) => res,
440                         Err(ChannelError::Ignore(msg)) => {
441                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
442                         },
443                         Err(ChannelError::Close(msg)) => {
444                                 let (channel_id, mut chan) = $entry.remove_entry();
445                                 if let Some(short_id) = chan.get_short_channel_id() {
446                                         $channel_state.short_to_id.remove(&short_id);
447                                 }
448                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
449                         },
450                 }
451         }
452 }
453
454 macro_rules! return_monitor_err {
455         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
456                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
457         };
458         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
459                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
460                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
461         };
462         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
463                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
464         };
465         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
466                 match $err {
467                         ChannelMonitorUpdateErr::PermanentFailure => {
468                                 let (channel_id, mut chan) = $entry.remove_entry();
469                                 if let Some(short_id) = chan.get_short_channel_id() {
470                                         $channel_state.short_to_id.remove(&short_id);
471                                 }
472                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
473                                 // chain in a confused state! We need to move them into the ChannelMonitor which
474                                 // will be responsible for failing backwards once things confirm on-chain.
475                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
476                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
477                                 // us bother trying to claim it just to forward on to another peer. If we're
478                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
479                                 // given up the preimage yet, so might as well just wait until the payment is
480                                 // retried, avoiding the on-chain fees.
481                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
482                         },
483                         ChannelMonitorUpdateErr::TemporaryFailure => {
484                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
485                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
486                         },
487                 }
488         }
489 }
490
491 // Does not break in case of TemporaryFailure!
492 macro_rules! maybe_break_monitor_err {
493         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
494                 match $err {
495                         ChannelMonitorUpdateErr::PermanentFailure => {
496                                 let (channel_id, mut chan) = $entry.remove_entry();
497                                 if let Some(short_id) = chan.get_short_channel_id() {
498                                         $channel_state.short_to_id.remove(&short_id);
499                                 }
500                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
501                         },
502                         ChannelMonitorUpdateErr::TemporaryFailure => {
503                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
504                         },
505                 }
506         }
507 }
508
509 impl ChannelManager {
510         /// Constructs a new ChannelManager to hold several channels and route between them.
511         ///
512         /// This is the main "logic hub" for all channel-related actions, and implements
513         /// ChannelMessageHandler.
514         ///
515         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
516         ///
517         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
518         pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
519                 let secp_ctx = Secp256k1::new();
520
521                 let res = Arc::new(ChannelManager {
522                         default_configuration: config.clone(),
523                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
524                         fee_estimator: feeest.clone(),
525                         monitor: monitor.clone(),
526                         chain_monitor,
527                         tx_broadcaster,
528
529                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
530                         last_block_hash: Mutex::new(Default::default()),
531                         secp_ctx,
532
533                         channel_state: Mutex::new(ChannelHolder{
534                                 by_id: HashMap::new(),
535                                 short_to_id: HashMap::new(),
536                                 next_forward: Instant::now(),
537                                 forward_htlcs: HashMap::new(),
538                                 claimable_htlcs: HashMap::new(),
539                                 pending_msg_events: Vec::new(),
540                         }),
541                         our_network_key: keys_manager.get_node_secret(),
542
543                         pending_events: Mutex::new(Vec::new()),
544                         total_consistency_lock: RwLock::new(()),
545
546                         keys_manager,
547
548                         logger,
549                 });
550                 let weak_res = Arc::downgrade(&res);
551                 res.chain_monitor.register_listener(weak_res);
552                 Ok(res)
553         }
554
555         /// Creates a new outbound channel to the given remote node and with the given value.
556         ///
557         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
558         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
559         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
560         /// may wish to avoid using 0 for user_id here.
561         ///
562         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
563         /// PeerManager::process_events afterwards.
564         ///
565         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
566         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
567         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
568                 if channel_value_satoshis < 1000 {
569                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
570                 }
571
572                 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
573                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
574
575                 let _ = self.total_consistency_lock.read().unwrap();
576                 let mut channel_state = self.channel_state.lock().unwrap();
577                 match channel_state.by_id.entry(channel.channel_id()) {
578                         hash_map::Entry::Occupied(_) => {
579                                 if cfg!(feature = "fuzztarget") {
580                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
581                                 } else {
582                                         panic!("RNG is bad???");
583                                 }
584                         },
585                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
586                 }
587                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
588                         node_id: their_network_key,
589                         msg: res,
590                 });
591                 Ok(())
592         }
593
594         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
595         /// more information.
596         pub fn list_channels(&self) -> Vec<ChannelDetails> {
597                 let channel_state = self.channel_state.lock().unwrap();
598                 let mut res = Vec::with_capacity(channel_state.by_id.len());
599                 for (channel_id, channel) in channel_state.by_id.iter() {
600                         res.push(ChannelDetails {
601                                 channel_id: (*channel_id).clone(),
602                                 short_channel_id: channel.get_short_channel_id(),
603                                 remote_network_id: channel.get_their_node_id(),
604                                 channel_value_satoshis: channel.get_value_satoshis(),
605                                 user_id: channel.get_user_id(),
606                         });
607                 }
608                 res
609         }
610
611         /// Gets the list of usable channels, in random order. Useful as an argument to
612         /// Router::get_route to ensure non-announced channels are used.
613         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
614                 let channel_state = self.channel_state.lock().unwrap();
615                 let mut res = Vec::with_capacity(channel_state.by_id.len());
616                 for (channel_id, channel) in channel_state.by_id.iter() {
617                         // Note we use is_live here instead of usable which leads to somewhat confused
618                         // internal/external nomenclature, but that's ok cause that's probably what the user
619                         // really wanted anyway.
620                         if channel.is_live() {
621                                 res.push(ChannelDetails {
622                                         channel_id: (*channel_id).clone(),
623                                         short_channel_id: channel.get_short_channel_id(),
624                                         remote_network_id: channel.get_their_node_id(),
625                                         channel_value_satoshis: channel.get_value_satoshis(),
626                                         user_id: channel.get_user_id(),
627                                 });
628                         }
629                 }
630                 res
631         }
632
633         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
634         /// will be accepted on the given channel, and after additional timeout/the closing of all
635         /// pending HTLCs, the channel will be closed on chain.
636         ///
637         /// May generate a SendShutdown message event on success, which should be relayed.
638         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
639                 let _ = self.total_consistency_lock.read().unwrap();
640
641                 let (mut failed_htlcs, chan_option) = {
642                         let mut channel_state_lock = self.channel_state.lock().unwrap();
643                         let channel_state = channel_state_lock.borrow_parts();
644                         match channel_state.by_id.entry(channel_id.clone()) {
645                                 hash_map::Entry::Occupied(mut chan_entry) => {
646                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
647                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
648                                                 node_id: chan_entry.get().get_their_node_id(),
649                                                 msg: shutdown_msg
650                                         });
651                                         if chan_entry.get().is_shutdown() {
652                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
653                                                         channel_state.short_to_id.remove(&short_id);
654                                                 }
655                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
656                                         } else { (failed_htlcs, None) }
657                                 },
658                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
659                         }
660                 };
661                 for htlc_source in failed_htlcs.drain(..) {
662                         // unknown_next_peer...I dunno who that is anymore....
663                         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() });
664                 }
665                 let chan_update = if let Some(chan) = chan_option {
666                         if let Ok(update) = self.get_channel_update(&chan) {
667                                 Some(update)
668                         } else { None }
669                 } else { None };
670
671                 if let Some(update) = chan_update {
672                         let mut channel_state = self.channel_state.lock().unwrap();
673                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
674                                 msg: update
675                         });
676                 }
677
678                 Ok(())
679         }
680
681         #[inline]
682         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
683                 let (local_txn, mut failed_htlcs) = shutdown_res;
684                 for htlc_source in failed_htlcs.drain(..) {
685                         // unknown_next_peer...I dunno who that is anymore....
686                         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() });
687                 }
688                 for tx in local_txn {
689                         self.tx_broadcaster.broadcast_transaction(&tx);
690                 }
691         }
692
693         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
694         /// the chain and rejecting new HTLCs on the given channel.
695         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
696                 let _ = self.total_consistency_lock.read().unwrap();
697
698                 let mut chan = {
699                         let mut channel_state_lock = self.channel_state.lock().unwrap();
700                         let channel_state = channel_state_lock.borrow_parts();
701                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
702                                 if let Some(short_id) = chan.get_short_channel_id() {
703                                         channel_state.short_to_id.remove(&short_id);
704                                 }
705                                 chan
706                         } else {
707                                 return;
708                         }
709                 };
710                 self.finish_force_close_channel(chan.force_shutdown());
711                 if let Ok(update) = self.get_channel_update(&chan) {
712                         let mut channel_state = self.channel_state.lock().unwrap();
713                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
714                                 msg: update
715                         });
716                 }
717         }
718
719         /// Force close all channels, immediately broadcasting the latest local commitment transaction
720         /// for each to the chain and rejecting new HTLCs on each.
721         pub fn force_close_all_channels(&self) {
722                 for chan in self.list_channels() {
723                         self.force_close_channel(&chan.channel_id);
724                 }
725         }
726
727         #[inline]
728         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
729                 assert_eq!(shared_secret.len(), 32);
730                 ({
731                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
732                         hmac.input(&shared_secret[..]);
733                         let mut res = [0; 32];
734                         hmac.raw_result(&mut res);
735                         res
736                 },
737                 {
738                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
739                         hmac.input(&shared_secret[..]);
740                         let mut res = [0; 32];
741                         hmac.raw_result(&mut res);
742                         res
743                 })
744         }
745
746         #[inline]
747         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
748                 assert_eq!(shared_secret.len(), 32);
749                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
750                 hmac.input(&shared_secret[..]);
751                 let mut res = [0; 32];
752                 hmac.raw_result(&mut res);
753                 res
754         }
755
756         #[inline]
757         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
758                 assert_eq!(shared_secret.len(), 32);
759                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
760                 hmac.input(&shared_secret[..]);
761                 let mut res = [0; 32];
762                 hmac.raw_result(&mut res);
763                 res
764         }
765
766         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
767         #[inline]
768         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> {
769                 let mut blinded_priv = session_priv.clone();
770                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
771
772                 for hop in route.hops.iter() {
773                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
774
775                         let mut sha = Sha256::new();
776                         sha.input(&blinded_pub.serialize()[..]);
777                         sha.input(&shared_secret[..]);
778                         let mut blinding_factor = [0u8; 32];
779                         sha.result(&mut blinding_factor);
780
781                         let ephemeral_pubkey = blinded_pub;
782
783                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
784                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
785
786                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
787                 }
788
789                 Ok(())
790         }
791
792         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
793         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
794                 let mut res = Vec::with_capacity(route.hops.len());
795
796                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
797                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
798
799                         res.push(OnionKeys {
800                                 #[cfg(test)]
801                                 shared_secret,
802                                 #[cfg(test)]
803                                 blinding_factor: _blinding_factor,
804                                 ephemeral_pubkey,
805                                 rho,
806                                 mu,
807                         });
808                 })?;
809
810                 Ok(res)
811         }
812
813         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
814         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
815                 let mut cur_value_msat = 0u64;
816                 let mut cur_cltv = starting_htlc_offset;
817                 let mut last_short_channel_id = 0;
818                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
819                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
820                 unsafe { res.set_len(route.hops.len()); }
821
822                 for (idx, hop) in route.hops.iter().enumerate().rev() {
823                         // First hop gets special values so that it can check, on receipt, that everything is
824                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
825                         // the intended recipient).
826                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
827                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
828                         res[idx] = msgs::OnionHopData {
829                                 realm: 0,
830                                 data: msgs::OnionRealm0HopData {
831                                         short_channel_id: last_short_channel_id,
832                                         amt_to_forward: value_msat,
833                                         outgoing_cltv_value: cltv,
834                                 },
835                                 hmac: [0; 32],
836                         };
837                         cur_value_msat += hop.fee_msat;
838                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
839                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
840                         }
841                         cur_cltv += hop.cltv_expiry_delta as u32;
842                         if cur_cltv >= 500000000 {
843                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
844                         }
845                         last_short_channel_id = hop.short_channel_id;
846                 }
847                 Ok((res, cur_value_msat, cur_cltv))
848         }
849
850         #[inline]
851         fn shift_arr_right(arr: &mut [u8; 20*65]) {
852                 unsafe {
853                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
854                 }
855                 for i in 0..65 {
856                         arr[i] = 0;
857                 }
858         }
859
860         #[inline]
861         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
862                 assert_eq!(dst.len(), src.len());
863
864                 for i in 0..dst.len() {
865                         dst[i] ^= src[i];
866                 }
867         }
868
869         const ZERO:[u8; 21*65] = [0; 21*65];
870         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
871                 let mut buf = Vec::with_capacity(21*65);
872                 buf.resize(21*65, 0);
873
874                 let filler = {
875                         let iters = payloads.len() - 1;
876                         let end_len = iters * 65;
877                         let mut res = Vec::with_capacity(end_len);
878                         res.resize(end_len, 0);
879
880                         for (i, keys) in onion_keys.iter().enumerate() {
881                                 if i == payloads.len() - 1 { continue; }
882                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
883                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
884                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
885                         }
886                         res
887                 };
888
889                 let mut packet_data = [0; 20*65];
890                 let mut hmac_res = [0; 32];
891
892                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
893                         ChannelManager::shift_arr_right(&mut packet_data);
894                         payload.hmac = hmac_res;
895                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
896
897                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
898                         chacha.process(&packet_data, &mut buf[0..20*65]);
899                         packet_data[..].copy_from_slice(&buf[0..20*65]);
900
901                         if i == 0 {
902                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
903                         }
904
905                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
906                         hmac.input(&packet_data);
907                         hmac.input(&associated_data.0[..]);
908                         hmac.raw_result(&mut hmac_res);
909                 }
910
911                 msgs::OnionPacket{
912                         version: 0,
913                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
914                         hop_data: packet_data,
915                         hmac: hmac_res,
916                 }
917         }
918
919         /// Encrypts a failure packet. raw_packet can either be a
920         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
921         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
922                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
923
924                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
925                 packet_crypted.resize(raw_packet.len(), 0);
926                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
927                 chacha.process(&raw_packet, &mut packet_crypted[..]);
928                 msgs::OnionErrorPacket {
929                         data: packet_crypted,
930                 }
931         }
932
933         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
934                 assert_eq!(shared_secret.len(), 32);
935                 assert!(failure_data.len() <= 256 - 2);
936
937                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
938
939                 let failuremsg = {
940                         let mut res = Vec::with_capacity(2 + failure_data.len());
941                         res.push(((failure_type >> 8) & 0xff) as u8);
942                         res.push(((failure_type >> 0) & 0xff) as u8);
943                         res.extend_from_slice(&failure_data[..]);
944                         res
945                 };
946                 let pad = {
947                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
948                         res.resize(256 - 2 - failure_data.len(), 0);
949                         res
950                 };
951                 let mut packet = msgs::DecodedOnionErrorPacket {
952                         hmac: [0; 32],
953                         failuremsg: failuremsg,
954                         pad: pad,
955                 };
956
957                 let mut hmac = Hmac::new(Sha256::new(), &um);
958                 hmac.input(&packet.encode()[32..]);
959                 hmac.raw_result(&mut packet.hmac);
960
961                 packet
962         }
963
964         #[inline]
965         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
966                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
967                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
968         }
969
970         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
971                 macro_rules! get_onion_hash {
972                         () => {
973                                 {
974                                         let mut sha = Sha256::new();
975                                         sha.input(&msg.onion_routing_packet.hop_data);
976                                         let mut onion_hash = [0; 32];
977                                         sha.result(&mut onion_hash);
978                                         onion_hash
979                                 }
980                         }
981                 }
982
983                 if let Err(_) = msg.onion_routing_packet.public_key {
984                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
985                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
986                                 channel_id: msg.channel_id,
987                                 htlc_id: msg.htlc_id,
988                                 sha256_of_onion: get_onion_hash!(),
989                                 failure_code: 0x8000 | 0x4000 | 6,
990                         })), self.channel_state.lock().unwrap());
991                 }
992
993                 let shared_secret = {
994                         let mut arr = [0; 32];
995                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
996                         arr
997                 };
998                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
999
1000                 let mut channel_state = None;
1001                 macro_rules! return_err {
1002                         ($msg: expr, $err_code: expr, $data: expr) => {
1003                                 {
1004                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1005                                         if channel_state.is_none() {
1006                                                 channel_state = Some(self.channel_state.lock().unwrap());
1007                                         }
1008                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1009                                                 channel_id: msg.channel_id,
1010                                                 htlc_id: msg.htlc_id,
1011                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1012                                         })), channel_state.unwrap());
1013                                 }
1014                         }
1015                 }
1016
1017                 if msg.onion_routing_packet.version != 0 {
1018                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1019                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1020                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1021                         //receiving node would have to brute force to figure out which version was put in the
1022                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1023                         //node knows the HMAC matched, so they already know what is there...
1024                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1025                 }
1026
1027                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1028                 hmac.input(&msg.onion_routing_packet.hop_data);
1029                 hmac.input(&msg.payment_hash.0[..]);
1030                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1031                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1032                 }
1033
1034                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1035                 let next_hop_data = {
1036                         let mut decoded = [0; 65];
1037                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1038                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1039                                 Err(err) => {
1040                                         let error_code = match err {
1041                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1042                                                 _ => 0x2000 | 2, // Should never happen
1043                                         };
1044                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1045                                 },
1046                                 Ok(msg) => msg
1047                         }
1048                 };
1049
1050                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1051                                 // OUR PAYMENT!
1052                                 // final_expiry_too_soon
1053                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1054                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1055                                 }
1056                                 // final_incorrect_htlc_amount
1057                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1058                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1059                                 }
1060                                 // final_incorrect_cltv_expiry
1061                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1062                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1063                                 }
1064
1065                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1066                                 // message, however that would leak that we are the recipient of this payment, so
1067                                 // instead we stay symmetric with the forwarding case, only responding (after a
1068                                 // delay) once they've send us a commitment_signed!
1069
1070                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1071                                         onion_packet: None,
1072                                         payment_hash: msg.payment_hash.clone(),
1073                                         short_channel_id: 0,
1074                                         incoming_shared_secret: shared_secret,
1075                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1076                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1077                                 })
1078                         } else {
1079                                 let mut new_packet_data = [0; 20*65];
1080                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1081                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1082
1083                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1084
1085                                 let blinding_factor = {
1086                                         let mut sha = Sha256::new();
1087                                         sha.input(&new_pubkey.serialize()[..]);
1088                                         sha.input(&shared_secret);
1089                                         let mut res = [0u8; 32];
1090                                         sha.result(&mut res);
1091                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1092                                                 Err(_) => {
1093                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1094                                                 },
1095                                                 Ok(key) => key
1096                                         }
1097                                 };
1098
1099                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1100                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1101                                 }
1102
1103                                 let outgoing_packet = msgs::OnionPacket {
1104                                         version: 0,
1105                                         public_key: Ok(new_pubkey),
1106                                         hop_data: new_packet_data,
1107                                         hmac: next_hop_data.hmac.clone(),
1108                                 };
1109
1110                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1111                                         onion_packet: Some(outgoing_packet),
1112                                         payment_hash: msg.payment_hash.clone(),
1113                                         short_channel_id: next_hop_data.data.short_channel_id,
1114                                         incoming_shared_secret: shared_secret,
1115                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1116                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1117                                 })
1118                         };
1119
1120                 channel_state = Some(self.channel_state.lock().unwrap());
1121                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1122                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1123                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1124                                 let forwarding_id = match id_option {
1125                                         None => { // unknown_next_peer
1126                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1127                                         },
1128                                         Some(id) => id.clone(),
1129                                 };
1130                                 if let Some((err, code, chan_update)) = loop {
1131                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1132
1133                                         // Note that we could technically not return an error yet here and just hope
1134                                         // that the connection is reestablished or monitor updated by the time we get
1135                                         // around to doing the actual forward, but better to fail early if we can and
1136                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1137                                         // on a small/per-node/per-channel scale.
1138                                         if !chan.is_live() { // channel_disabled
1139                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1140                                         }
1141                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1142                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1143                                         }
1144                                         let fee = amt_to_forward.checked_mul(chan.get_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) });
1145                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1146                                                 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())));
1147                                         }
1148                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1149                                                 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())));
1150                                         }
1151                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1152                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1153                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1154                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1155                                         }
1156                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1157                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1158                                         }
1159                                         break None;
1160                                 }
1161                                 {
1162                                         let mut res = Vec::with_capacity(8 + 128);
1163                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1164                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1165                                         }
1166                                         else if code == 0x1000 | 13 {
1167                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1168                                         }
1169                                         if let Some(chan_update) = chan_update {
1170                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1171                                         }
1172                                         return_err!(err, code, &res[..]);
1173                                 }
1174                         }
1175                 }
1176
1177                 (pending_forward_info, channel_state.unwrap())
1178         }
1179
1180         /// only fails if the channel does not yet have an assigned short_id
1181         /// May be called with channel_state already locked!
1182         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1183                 let short_channel_id = match chan.get_short_channel_id() {
1184                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1185                         Some(id) => id,
1186                 };
1187
1188                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1189
1190                 let unsigned = msgs::UnsignedChannelUpdate {
1191                         chain_hash: self.genesis_hash,
1192                         short_channel_id: short_channel_id,
1193                         timestamp: chan.get_channel_update_count(),
1194                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1195                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1196                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1197                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1198                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1199                         excess_data: Vec::new(),
1200                 };
1201
1202                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1203                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1204
1205                 Ok(msgs::ChannelUpdate {
1206                         signature: sig,
1207                         contents: unsigned
1208                 })
1209         }
1210
1211         /// Sends a payment along a given route.
1212         ///
1213         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1214         /// fields for more info.
1215         ///
1216         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1217         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1218         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1219         /// specified in the last hop in the route! Thus, you should probably do your own
1220         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1221         /// payment") and prevent double-sends yourself.
1222         ///
1223         /// May generate a SendHTLCs message event on success, which should be relayed.
1224         ///
1225         /// Raises APIError::RoutError when invalid route or forward parameter
1226         /// (cltv_delta, fee, node public key) is specified.
1227         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1228         /// (including due to previous monitor update failure or new permanent monitor update failure).
1229         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1230         /// relevant updates.
1231         ///
1232         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1233         /// and you may wish to retry via a different route immediately.
1234         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1235         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1236         /// the payment via a different route unless you intend to pay twice!
1237         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1238                 if route.hops.len() < 1 || route.hops.len() > 20 {
1239                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1240                 }
1241                 let our_node_id = self.get_our_node_id();
1242                 for (idx, hop) in route.hops.iter().enumerate() {
1243                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1244                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1245                         }
1246                 }
1247
1248                 let session_priv = self.keys_manager.get_session_key();
1249
1250                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1251
1252                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1253                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1254                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1255                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1256
1257                 let _ = self.total_consistency_lock.read().unwrap();
1258
1259                 let err: Result<(), _> = loop {
1260                         let mut channel_lock = self.channel_state.lock().unwrap();
1261
1262                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1263                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1264                                 Some(id) => id.clone(),
1265                         };
1266
1267                         let channel_state = channel_lock.borrow_parts();
1268                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1269                                 match {
1270                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1271                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1272                                         }
1273                                         if !chan.get().is_live() {
1274                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1275                                         }
1276                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1277                                                 route: route.clone(),
1278                                                 session_priv: session_priv.clone(),
1279                                                 first_hop_htlc_msat: htlc_msat,
1280                                         }, onion_packet), channel_state, chan)
1281                                 } {
1282                                         Some((update_add, commitment_signed, chan_monitor)) => {
1283                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1284                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1285                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1286                                                         // that we will resent the commitment update once we unfree monitor
1287                                                         // updating, so we have to take special care that we don't return
1288                                                         // something else in case we will resend later!
1289                                                         return Err(APIError::MonitorUpdateFailed);
1290                                                 }
1291
1292                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1293                                                         node_id: route.hops.first().unwrap().pubkey,
1294                                                         updates: msgs::CommitmentUpdate {
1295                                                                 update_add_htlcs: vec![update_add],
1296                                                                 update_fulfill_htlcs: Vec::new(),
1297                                                                 update_fail_htlcs: Vec::new(),
1298                                                                 update_fail_malformed_htlcs: Vec::new(),
1299                                                                 update_fee: None,
1300                                                                 commitment_signed,
1301                                                         },
1302                                                 });
1303                                         },
1304                                         None => {},
1305                                 }
1306                         } else { unreachable!(); }
1307                         return Ok(());
1308                 };
1309
1310                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1311                         Ok(_) => unreachable!(),
1312                         Err(e) => {
1313                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1314                                 } else {
1315                                         log_error!(self, "Got bad keys: {}!", e.err);
1316                                         let mut channel_state = self.channel_state.lock().unwrap();
1317                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1318                                                 node_id: route.hops.first().unwrap().pubkey,
1319                                                 action: e.action,
1320                                         });
1321                                 }
1322                                 Err(APIError::ChannelUnavailable { err: e.err })
1323                         },
1324                 }
1325         }
1326
1327         /// Call this upon creation of a funding transaction for the given channel.
1328         ///
1329         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1330         /// or your counterparty can steal your funds!
1331         ///
1332         /// Panics if a funding transaction has already been provided for this channel.
1333         ///
1334         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1335         /// be trivially prevented by using unique funding transaction keys per-channel).
1336         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1337                 let _ = self.total_consistency_lock.read().unwrap();
1338
1339                 let (chan, msg, chan_monitor) = {
1340                         let (res, chan) = {
1341                                 let mut channel_state = self.channel_state.lock().unwrap();
1342                                 match channel_state.by_id.remove(temporary_channel_id) {
1343                                         Some(mut chan) => {
1344                                                 (chan.get_outbound_funding_created(funding_txo)
1345                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1346                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1347                                                         } else { unreachable!(); })
1348                                                 , chan)
1349                                         },
1350                                         None => return
1351                                 }
1352                         };
1353                         match handle_error!(self, res, chan.get_their_node_id()) {
1354                                 Ok(funding_msg) => {
1355                                         (chan, funding_msg.0, funding_msg.1)
1356                                 },
1357                                 Err(e) => {
1358                                         log_error!(self, "Got bad signatures: {}!", e.err);
1359                                         let mut channel_state = self.channel_state.lock().unwrap();
1360                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1361                                                 node_id: chan.get_their_node_id(),
1362                                                 action: e.action,
1363                                         });
1364                                         return;
1365                                 },
1366                         }
1367                 };
1368                 // Because we have exclusive ownership of the channel here we can release the channel_state
1369                 // lock before add_update_monitor
1370                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1371                         unimplemented!();
1372                 }
1373
1374                 let mut channel_state = self.channel_state.lock().unwrap();
1375                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1376                         node_id: chan.get_their_node_id(),
1377                         msg: msg,
1378                 });
1379                 match channel_state.by_id.entry(chan.channel_id()) {
1380                         hash_map::Entry::Occupied(_) => {
1381                                 panic!("Generated duplicate funding txid?");
1382                         },
1383                         hash_map::Entry::Vacant(e) => {
1384                                 e.insert(chan);
1385                         }
1386                 }
1387         }
1388
1389         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1390                 if !chan.should_announce() { return None }
1391
1392                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1393                         Ok(res) => res,
1394                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1395                 };
1396                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1397                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1398
1399                 Some(msgs::AnnouncementSignatures {
1400                         channel_id: chan.channel_id(),
1401                         short_channel_id: chan.get_short_channel_id().unwrap(),
1402                         node_signature: our_node_sig,
1403                         bitcoin_signature: our_bitcoin_sig,
1404                 })
1405         }
1406
1407         /// Processes HTLCs which are pending waiting on random forward delay.
1408         ///
1409         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1410         /// Will likely generate further events.
1411         pub fn process_pending_htlc_forwards(&self) {
1412                 let _ = self.total_consistency_lock.read().unwrap();
1413
1414                 let mut new_events = Vec::new();
1415                 let mut failed_forwards = Vec::new();
1416                 {
1417                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1418                         let channel_state = channel_state_lock.borrow_parts();
1419
1420                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1421                                 return;
1422                         }
1423
1424                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1425                                 if short_chan_id != 0 {
1426                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1427                                                 Some(chan_id) => chan_id.clone(),
1428                                                 None => {
1429                                                         failed_forwards.reserve(pending_forwards.len());
1430                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1431                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1432                                                                         short_channel_id: prev_short_channel_id,
1433                                                                         htlc_id: prev_htlc_id,
1434                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1435                                                                 });
1436                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1437                                                         }
1438                                                         continue;
1439                                                 }
1440                                         };
1441                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1442
1443                                         let mut add_htlc_msgs = Vec::new();
1444                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1445                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1446                                                         short_channel_id: prev_short_channel_id,
1447                                                         htlc_id: prev_htlc_id,
1448                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1449                                                 });
1450                                                 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()) {
1451                                                         Err(_e) => {
1452                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1453                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1454                                                                 continue;
1455                                                         },
1456                                                         Ok(update_add) => {
1457                                                                 match update_add {
1458                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1459                                                                         None => {
1460                                                                                 // Nothing to do here...we're waiting on a remote
1461                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1462                                                                                 // will automatically handle building the update_add_htlc and
1463                                                                                 // commitment_signed messages when we can.
1464                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1465                                                                                 // as we don't really want others relying on us relaying through
1466                                                                                 // this channel currently :/.
1467                                                                         }
1468                                                                 }
1469                                                         }
1470                                                 }
1471                                         }
1472
1473                                         if !add_htlc_msgs.is_empty() {
1474                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1475                                                         Ok(res) => res,
1476                                                         Err(e) => {
1477                                                                 if let ChannelError::Ignore(_) = e {
1478                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1479                                                                 }
1480                                                                 //TODO: Handle...this is bad!
1481                                                                 continue;
1482                                                         },
1483                                                 };
1484                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1485                                                         unimplemented!();
1486                                                 }
1487                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1488                                                         node_id: forward_chan.get_their_node_id(),
1489                                                         updates: msgs::CommitmentUpdate {
1490                                                                 update_add_htlcs: add_htlc_msgs,
1491                                                                 update_fulfill_htlcs: Vec::new(),
1492                                                                 update_fail_htlcs: Vec::new(),
1493                                                                 update_fail_malformed_htlcs: Vec::new(),
1494                                                                 update_fee: None,
1495                                                                 commitment_signed: commitment_msg,
1496                                                         },
1497                                                 });
1498                                         }
1499                                 } else {
1500                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1501                                                 let prev_hop_data = HTLCPreviousHopData {
1502                                                         short_channel_id: prev_short_channel_id,
1503                                                         htlc_id: prev_htlc_id,
1504                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1505                                                 };
1506                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1507                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1508                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1509                                                 };
1510                                                 new_events.push(events::Event::PaymentReceived {
1511                                                         payment_hash: forward_info.payment_hash,
1512                                                         amt: forward_info.amt_to_forward,
1513                                                 });
1514                                         }
1515                                 }
1516                         }
1517                 }
1518
1519                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1520                         match update {
1521                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1522                                 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() }),
1523                         };
1524                 }
1525
1526                 if new_events.is_empty() { return }
1527                 let mut events = self.pending_events.lock().unwrap();
1528                 events.append(&mut new_events);
1529         }
1530
1531         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1532         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1533                 let _ = self.total_consistency_lock.read().unwrap();
1534
1535                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1536                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1537                 if let Some(mut sources) = removed_source {
1538                         for htlc_with_hash in sources.drain(..) {
1539                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1540                                 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: if reason == PaymentFailReason::PreimageUnknown {0x4000 | 15} else {0x4000 | 16}, data: Vec::new() });
1541                         }
1542                         true
1543                 } else { false }
1544         }
1545
1546         /// Fails an HTLC backwards to the sender of it to us.
1547         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1548         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1549         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1550         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1551         /// still-available channels.
1552         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1553                 match source {
1554                         HTLCSource::OutboundRoute { .. } => {
1555                                 mem::drop(channel_state_lock);
1556                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1557                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1558                                         if let Some(update) = channel_update {
1559                                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1560                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate {
1561                                                                 update,
1562                                                         }
1563                                                 );
1564                                         }
1565                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1566                                                 payment_hash: payment_hash.clone(),
1567                                                 rejected_by_dest: !payment_retryable,
1568                                         });
1569                                 } else {
1570                                         //TODO: Pass this back (see GH #243)
1571                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1572                                                 payment_hash: payment_hash.clone(),
1573                                                 rejected_by_dest: false, // We failed it ourselves, can't blame them
1574                                         });
1575                                 }
1576                         },
1577                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1578                                 let err_packet = match onion_error {
1579                                         HTLCFailReason::Reason { failure_code, data } => {
1580                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1581                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1582                                         },
1583                                         HTLCFailReason::ErrorPacket { err } => {
1584                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1585                                         }
1586                                 };
1587
1588                                 let channel_state = channel_state_lock.borrow_parts();
1589
1590                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1591                                         Some(chan_id) => chan_id.clone(),
1592                                         None => return
1593                                 };
1594
1595                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1596                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1597                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1598                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1599                                                         unimplemented!();
1600                                                 }
1601                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1602                                                         node_id: chan.get_their_node_id(),
1603                                                         updates: msgs::CommitmentUpdate {
1604                                                                 update_add_htlcs: Vec::new(),
1605                                                                 update_fulfill_htlcs: Vec::new(),
1606                                                                 update_fail_htlcs: vec![msg],
1607                                                                 update_fail_malformed_htlcs: Vec::new(),
1608                                                                 update_fee: None,
1609                                                                 commitment_signed: commitment_msg,
1610                                                         },
1611                                                 });
1612                                         },
1613                                         Ok(None) => {},
1614                                         Err(_e) => {
1615                                                 //TODO: Do something with e?
1616                                                 return;
1617                                         },
1618                                 }
1619                         },
1620                 }
1621         }
1622
1623         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1624         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1625         /// should probably kick the net layer to go send messages if this returns true!
1626         ///
1627         /// May panic if called except in response to a PaymentReceived event.
1628         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1629                 let mut sha = Sha256::new();
1630                 sha.input(&payment_preimage.0[..]);
1631                 let mut payment_hash = PaymentHash([0; 32]);
1632                 sha.result(&mut payment_hash.0[..]);
1633
1634                 let _ = self.total_consistency_lock.read().unwrap();
1635
1636                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1637                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1638                 if let Some(mut sources) = removed_source {
1639                         for htlc_with_hash in sources.drain(..) {
1640                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1641                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1642                         }
1643                         true
1644                 } else { false }
1645         }
1646         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1647                 match source {
1648                         HTLCSource::OutboundRoute { .. } => {
1649                                 mem::drop(channel_state_lock);
1650                                 let mut pending_events = self.pending_events.lock().unwrap();
1651                                 pending_events.push(events::Event::PaymentSent {
1652                                         payment_preimage
1653                                 });
1654                         },
1655                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1656                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1657                                 let channel_state = channel_state_lock.borrow_parts();
1658
1659                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1660                                         Some(chan_id) => chan_id.clone(),
1661                                         None => {
1662                                                 // TODO: There is probably a channel manager somewhere that needs to
1663                                                 // learn the preimage as the channel already hit the chain and that's
1664                                                 // why its missing.
1665                                                 return
1666                                         }
1667                                 };
1668
1669                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1670                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1671                                         Ok((msgs, monitor_option)) => {
1672                                                 if let Some(chan_monitor) = monitor_option {
1673                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1674                                                                 unimplemented!();// but def dont push the event...
1675                                                         }
1676                                                 }
1677                                                 if let Some((msg, commitment_signed)) = msgs {
1678                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1679                                                                 node_id: chan.get_their_node_id(),
1680                                                                 updates: msgs::CommitmentUpdate {
1681                                                                         update_add_htlcs: Vec::new(),
1682                                                                         update_fulfill_htlcs: vec![msg],
1683                                                                         update_fail_htlcs: Vec::new(),
1684                                                                         update_fail_malformed_htlcs: Vec::new(),
1685                                                                         update_fee: None,
1686                                                                         commitment_signed,
1687                                                                 }
1688                                                         });
1689                                                 }
1690                                         },
1691                                         Err(_e) => {
1692                                                 // TODO: There is probably a channel manager somewhere that needs to
1693                                                 // learn the preimage as the channel may be about to hit the chain.
1694                                                 //TODO: Do something with e?
1695                                                 return
1696                                         },
1697                                 }
1698                         },
1699                 }
1700         }
1701
1702         /// Gets the node_id held by this ChannelManager
1703         pub fn get_our_node_id(&self) -> PublicKey {
1704                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1705         }
1706
1707         /// Used to restore channels to normal operation after a
1708         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1709         /// operation.
1710         pub fn test_restore_channel_monitor(&self) {
1711                 let mut close_results = Vec::new();
1712                 let mut htlc_forwards = Vec::new();
1713                 let mut htlc_failures = Vec::new();
1714                 let _ = self.total_consistency_lock.read().unwrap();
1715
1716                 {
1717                         let mut channel_lock = self.channel_state.lock().unwrap();
1718                         let channel_state = channel_lock.borrow_parts();
1719                         let short_to_id = channel_state.short_to_id;
1720                         let pending_msg_events = channel_state.pending_msg_events;
1721                         channel_state.by_id.retain(|_, channel| {
1722                                 if channel.is_awaiting_monitor_update() {
1723                                         let chan_monitor = channel.channel_monitor();
1724                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1725                                                 match e {
1726                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1727                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1728                                                                 // backwards when a monitor update failed. We should make sure
1729                                                                 // knowledge of those gets moved into the appropriate in-memory
1730                                                                 // ChannelMonitor and they get failed backwards once we get
1731                                                                 // on-chain confirmations.
1732                                                                 // Note I think #198 addresses this, so once its merged a test
1733                                                                 // should be written.
1734                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1735                                                                         short_to_id.remove(&short_id);
1736                                                                 }
1737                                                                 close_results.push(channel.force_shutdown());
1738                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1739                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1740                                                                                 msg: update
1741                                                                         });
1742                                                                 }
1743                                                                 false
1744                                                         },
1745                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1746                                                 }
1747                                         } else {
1748                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1749                                                 if !pending_forwards.is_empty() {
1750                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1751                                                 }
1752                                                 htlc_failures.append(&mut pending_failures);
1753
1754                                                 macro_rules! handle_cs { () => {
1755                                                         if let Some(update) = commitment_update {
1756                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1757                                                                         node_id: channel.get_their_node_id(),
1758                                                                         updates: update,
1759                                                                 });
1760                                                         }
1761                                                 } }
1762                                                 macro_rules! handle_raa { () => {
1763                                                         if let Some(revoke_and_ack) = raa {
1764                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1765                                                                         node_id: channel.get_their_node_id(),
1766                                                                         msg: revoke_and_ack,
1767                                                                 });
1768                                                         }
1769                                                 } }
1770                                                 match order {
1771                                                         RAACommitmentOrder::CommitmentFirst => {
1772                                                                 handle_cs!();
1773                                                                 handle_raa!();
1774                                                         },
1775                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1776                                                                 handle_raa!();
1777                                                                 handle_cs!();
1778                                                         },
1779                                                 }
1780                                                 true
1781                                         }
1782                                 } else { true }
1783                         });
1784                 }
1785
1786                 for failure in htlc_failures.drain(..) {
1787                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1788                 }
1789                 self.forward_htlcs(&mut htlc_forwards[..]);
1790
1791                 for res in close_results.drain(..) {
1792                         self.finish_force_close_channel(res);
1793                 }
1794         }
1795
1796         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1797                 if msg.chain_hash != self.genesis_hash {
1798                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1799                 }
1800
1801                 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1802                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1803                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1804                 let channel_state = channel_state_lock.borrow_parts();
1805                 match channel_state.by_id.entry(channel.channel_id()) {
1806                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1807                         hash_map::Entry::Vacant(entry) => {
1808                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1809                                         node_id: their_node_id.clone(),
1810                                         msg: channel.get_accept_channel(),
1811                                 });
1812                                 entry.insert(channel);
1813                         }
1814                 }
1815                 Ok(())
1816         }
1817
1818         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1819                 let (value, output_script, user_id) = {
1820                         let mut channel_lock = self.channel_state.lock().unwrap();
1821                         let channel_state = channel_lock.borrow_parts();
1822                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1823                                 hash_map::Entry::Occupied(mut chan) => {
1824                                         if chan.get().get_their_node_id() != *their_node_id {
1825                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1826                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1827                                         }
1828                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1829                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1830                                 },
1831                                 //TODO: same as above
1832                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1833                         }
1834                 };
1835                 let mut pending_events = self.pending_events.lock().unwrap();
1836                 pending_events.push(events::Event::FundingGenerationReady {
1837                         temporary_channel_id: msg.temporary_channel_id,
1838                         channel_value_satoshis: value,
1839                         output_script: output_script,
1840                         user_channel_id: user_id,
1841                 });
1842                 Ok(())
1843         }
1844
1845         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1846                 let ((funding_msg, monitor_update), chan) = {
1847                         let mut channel_lock = self.channel_state.lock().unwrap();
1848                         let channel_state = channel_lock.borrow_parts();
1849                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1850                                 hash_map::Entry::Occupied(mut chan) => {
1851                                         if chan.get().get_their_node_id() != *their_node_id {
1852                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1853                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1854                                         }
1855                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1856                                 },
1857                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1858                         }
1859                 };
1860                 // Because we have exclusive ownership of the channel here we can release the channel_state
1861                 // lock before add_update_monitor
1862                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1863                         unimplemented!();
1864                 }
1865                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1866                 let channel_state = channel_state_lock.borrow_parts();
1867                 match channel_state.by_id.entry(funding_msg.channel_id) {
1868                         hash_map::Entry::Occupied(_) => {
1869                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1870                         },
1871                         hash_map::Entry::Vacant(e) => {
1872                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1873                                         node_id: their_node_id.clone(),
1874                                         msg: funding_msg,
1875                                 });
1876                                 e.insert(chan);
1877                         }
1878                 }
1879                 Ok(())
1880         }
1881
1882         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1883                 let (funding_txo, user_id) = {
1884                         let mut channel_lock = self.channel_state.lock().unwrap();
1885                         let channel_state = channel_lock.borrow_parts();
1886                         match channel_state.by_id.entry(msg.channel_id) {
1887                                 hash_map::Entry::Occupied(mut chan) => {
1888                                         if chan.get().get_their_node_id() != *their_node_id {
1889                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1890                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1891                                         }
1892                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1893                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1894                                                 unimplemented!();
1895                                         }
1896                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1897                                 },
1898                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1899                         }
1900                 };
1901                 let mut pending_events = self.pending_events.lock().unwrap();
1902                 pending_events.push(events::Event::FundingBroadcastSafe {
1903                         funding_txo: funding_txo,
1904                         user_channel_id: user_id,
1905                 });
1906                 Ok(())
1907         }
1908
1909         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1910                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1911                 let channel_state = channel_state_lock.borrow_parts();
1912                 match channel_state.by_id.entry(msg.channel_id) {
1913                         hash_map::Entry::Occupied(mut chan) => {
1914                                 if chan.get().get_their_node_id() != *their_node_id {
1915                                         //TODO: here and below MsgHandleErrInternal, #153 case
1916                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1917                                 }
1918                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1919                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1920                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1921                                                 node_id: their_node_id.clone(),
1922                                                 msg: announcement_sigs,
1923                                         });
1924                                 }
1925                                 Ok(())
1926                         },
1927                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1928                 }
1929         }
1930
1931         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1932                 let (mut dropped_htlcs, chan_option) = {
1933                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1934                         let channel_state = channel_state_lock.borrow_parts();
1935
1936                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1937                                 hash_map::Entry::Occupied(mut chan_entry) => {
1938                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1939                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1940                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1941                                         }
1942                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1943                                         if let Some(msg) = shutdown {
1944                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1945                                                         node_id: their_node_id.clone(),
1946                                                         msg,
1947                                                 });
1948                                         }
1949                                         if let Some(msg) = closing_signed {
1950                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1951                                                         node_id: their_node_id.clone(),
1952                                                         msg,
1953                                                 });
1954                                         }
1955                                         if chan_entry.get().is_shutdown() {
1956                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1957                                                         channel_state.short_to_id.remove(&short_id);
1958                                                 }
1959                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1960                                         } else { (dropped_htlcs, None) }
1961                                 },
1962                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1963                         }
1964                 };
1965                 for htlc_source in dropped_htlcs.drain(..) {
1966                         // unknown_next_peer...I dunno who that is anymore....
1967                         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() });
1968                 }
1969                 if let Some(chan) = chan_option {
1970                         if let Ok(update) = self.get_channel_update(&chan) {
1971                                 let mut channel_state = self.channel_state.lock().unwrap();
1972                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1973                                         msg: update
1974                                 });
1975                         }
1976                 }
1977                 Ok(())
1978         }
1979
1980         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1981                 let (tx, chan_option) = {
1982                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1983                         let channel_state = channel_state_lock.borrow_parts();
1984                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1985                                 hash_map::Entry::Occupied(mut chan_entry) => {
1986                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1987                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1988                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1989                                         }
1990                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1991                                         if let Some(msg) = closing_signed {
1992                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1993                                                         node_id: their_node_id.clone(),
1994                                                         msg,
1995                                                 });
1996                                         }
1997                                         if tx.is_some() {
1998                                                 // We're done with this channel, we've got a signed closing transaction and
1999                                                 // will send the closing_signed back to the remote peer upon return. This
2000                                                 // also implies there are no pending HTLCs left on the channel, so we can
2001                                                 // fully delete it from tracking (the channel monitor is still around to
2002                                                 // watch for old state broadcasts)!
2003                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2004                                                         channel_state.short_to_id.remove(&short_id);
2005                                                 }
2006                                                 (tx, Some(chan_entry.remove_entry().1))
2007                                         } else { (tx, None) }
2008                                 },
2009                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2010                         }
2011                 };
2012                 if let Some(broadcast_tx) = tx {
2013                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2014                 }
2015                 if let Some(chan) = chan_option {
2016                         if let Ok(update) = self.get_channel_update(&chan) {
2017                                 let mut channel_state = self.channel_state.lock().unwrap();
2018                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2019                                         msg: update
2020                                 });
2021                         }
2022                 }
2023                 Ok(())
2024         }
2025
2026         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2027                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2028                 //determine the state of the payment based on our response/if we forward anything/the time
2029                 //we take to respond. We should take care to avoid allowing such an attack.
2030                 //
2031                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2032                 //us repeatedly garbled in different ways, and compare our error messages, which are
2033                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2034                 //but we should prevent it anyway.
2035
2036                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2037                 let channel_state = channel_state_lock.borrow_parts();
2038
2039                 match channel_state.by_id.entry(msg.channel_id) {
2040                         hash_map::Entry::Occupied(mut chan) => {
2041                                 if chan.get().get_their_node_id() != *their_node_id {
2042                                         //TODO: here MsgHandleErrInternal, #153 case
2043                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2044                                 }
2045                                 if !chan.get().is_usable() {
2046                                         // If the update_add is completely bogus, the call will Err and we will close,
2047                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2048                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2049                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2050                                                 let chan_update = self.get_channel_update(chan.get());
2051                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2052                                                         channel_id: msg.channel_id,
2053                                                         htlc_id: msg.htlc_id,
2054                                                         reason: if let Ok(update) = chan_update {
2055                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2056                                                         } else {
2057                                                                 // This can only happen if the channel isn't in the fully-funded
2058                                                                 // state yet, implying our counterparty is trying to route payments
2059                                                                 // over the channel back to themselves (cause no one else should
2060                                                                 // know the short_id is a lightning channel yet). We should have no
2061                                                                 // problem just calling this unknown_next_peer
2062                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2063                                                         },
2064                                                 }));
2065                                         }
2066                                 }
2067                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2068                         },
2069                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2070                 }
2071                 Ok(())
2072         }
2073
2074         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2075                 let mut channel_lock = self.channel_state.lock().unwrap();
2076                 let htlc_source = {
2077                         let channel_state = channel_lock.borrow_parts();
2078                         match channel_state.by_id.entry(msg.channel_id) {
2079                                 hash_map::Entry::Occupied(mut chan) => {
2080                                         if chan.get().get_their_node_id() != *their_node_id {
2081                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2082                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2083                                         }
2084                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2085                                 },
2086                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2087                         }
2088                 };
2089                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2090                 Ok(())
2091         }
2092
2093         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2094         // indicating that the payment itself failed
2095         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2096                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2097                         macro_rules! onion_failure_log {
2098                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2099                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2100                                 };
2101                                 ( $error_code_textual: expr, $error_code: expr ) => {
2102                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2103                                 };
2104                         }
2105
2106                         const BADONION: u16 = 0x8000;
2107                         const PERM: u16 = 0x4000;
2108                         const UPDATE: u16 = 0x1000;
2109
2110                         let mut res = None;
2111                         let mut htlc_msat = *first_hop_htlc_msat;
2112
2113                         // Handle packed channel/node updates for passing back for the route handler
2114                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2115                                 if res.is_some() { return; }
2116
2117                                 let incoming_htlc_msat = htlc_msat;
2118                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2119                                 htlc_msat = amt_to_forward;
2120
2121                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2122
2123                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2124                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2125                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2126                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2127                                 packet_decrypted = decryption_tmp;
2128
2129                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2130
2131                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2132                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2133                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2134                                         hmac.input(&err_packet.encode()[32..]);
2135                                         let mut calc_tag = [0u8; 32];
2136                                         hmac.raw_result(&mut calc_tag);
2137
2138                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2139                                                 if err_packet.failuremsg.len() < 2 {
2140                                                         // Useless packet that we can't use but it passed HMAC, so it
2141                                                         // definitely came from the peer in question
2142                                                         res = Some((None, !is_from_final_node));
2143                                                 } else {
2144                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2145
2146                                                         match error_code & 0xff {
2147                                                                 1|2|3 => {
2148                                                                         // either from an intermediate or final node
2149                                                                         //   invalid_realm(PERM|1),
2150                                                                         //   temporary_node_failure(NODE|2)
2151                                                                         //   permanent_node_failure(PERM|NODE|2)
2152                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2153                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2154                                                                                 node_id: route_hop.pubkey,
2155                                                                                 is_permanent: error_code & PERM == PERM,
2156                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2157                                                                         // node returning invalid_realm is removed from network_map,
2158                                                                         // although NODE flag is not set, TODO: or remove channel only?
2159                                                                         // retry payment when removed node is not a final node
2160                                                                         return;
2161                                                                 },
2162                                                                 _ => {}
2163                                                         }
2164
2165                                                         if is_from_final_node {
2166                                                                 let payment_retryable = match error_code {
2167                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2168                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2169                                                                         17 => true, // final_expiry_too_soon
2170                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2171                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2172                                                                                 true
2173                                                                         },
2174                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2175                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2176                                                                                 true
2177                                                                         },
2178                                                                         _ => {
2179                                                                                 // A final node has sent us either an invalid code or an error_code that
2180                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2181                                                                                 // does not coform to the spec.
2182                                                                                 // Remove it from the network map and don't may retry payment
2183                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2184                                                                                         node_id: route_hop.pubkey,
2185                                                                                         is_permanent: true,
2186                                                                                 }), false));
2187                                                                                 return;
2188                                                                         }
2189                                                                 };
2190                                                                 res = Some((None, payment_retryable));
2191                                                                 return;
2192                                                         }
2193
2194                                                         // now, error_code should be only from the intermediate nodes
2195                                                         match error_code {
2196                                                                 _c if error_code & PERM == PERM => {
2197                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2198                                                                                 short_channel_id: route_hop.short_channel_id,
2199                                                                                 is_permanent: true,
2200                                                                         }), false));
2201                                                                 },
2202                                                                 _c if error_code & UPDATE == UPDATE => {
2203                                                                         let offset = match error_code {
2204                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2205                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2206                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2207                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2208                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2209                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2210                                                                                 _ =>  {
2211                                                                                         // node sending unknown code
2212                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2213                                                                                                 node_id: route_hop.pubkey,
2214                                                                                                 is_permanent: true,
2215                                                                                         }), false));
2216                                                                                         return;
2217                                                                                 }
2218                                                                         };
2219
2220                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2221                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2222                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2223                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2224                                                                                                 // if channel_update should NOT have caused the failure:
2225                                                                                                 // MAY treat the channel_update as invalid.
2226                                                                                                 let is_chan_update_invalid = match error_code {
2227                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2228                                                                                                                 false
2229                                                                                                         },
2230                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2231                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2232                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2233                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2234                                                                                                         },
2235                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2236                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2237                                                                                                                 let new_fee =  amt_to_forward.checked_mul(chan_update.contents.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan_update.contents.fee_base_msat as u64) });
2238                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2239                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2240                                                                                                         }
2241                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2242                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2243                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2244                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2245                                                                                                         },
2246                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2247                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2248                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2249                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2250                                                                                                         },
2251                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2252                                                                                                         _ => { unreachable!(); },
2253                                                                                                 };
2254
2255                                                                                                 let msg = if is_chan_update_invalid { None } else {
2256                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2257                                                                                                                 msg: chan_update,
2258                                                                                                         })
2259                                                                                                 };
2260                                                                                                 res = Some((msg, true));
2261                                                                                                 return;
2262                                                                                         }
2263                                                                                 }
2264                                                                         }
2265                                                                 },
2266                                                                 _c if error_code & BADONION == BADONION => {
2267                                                                         //TODO
2268                                                                 },
2269                                                                 14 => { // expiry_too_soon
2270                                                                         res = Some((None, true));
2271                                                                         return;
2272                                                                 }
2273                                                                 _ => {
2274                                                                         // node sending unknown code
2275                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2276                                                                                 node_id: route_hop.pubkey,
2277                                                                                 is_permanent: true,
2278                                                                         }), false));
2279                                                                         return;
2280                                                                 }
2281                                                         }
2282                                                 }
2283                                         }
2284                                 }
2285                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2286                         res.unwrap_or((None, true))
2287                 } else { ((None, true)) }
2288         }
2289
2290         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2291                 let mut channel_lock = self.channel_state.lock().unwrap();
2292                 let channel_state = channel_lock.borrow_parts();
2293                 match channel_state.by_id.entry(msg.channel_id) {
2294                         hash_map::Entry::Occupied(mut chan) => {
2295                                 if chan.get().get_their_node_id() != *their_node_id {
2296                                         //TODO: here and below MsgHandleErrInternal, #153 case
2297                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2298                                 }
2299                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2300                         },
2301                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2302                 }
2303                 Ok(())
2304         }
2305
2306         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2307                 let mut channel_lock = self.channel_state.lock().unwrap();
2308                 let channel_state = channel_lock.borrow_parts();
2309                 match channel_state.by_id.entry(msg.channel_id) {
2310                         hash_map::Entry::Occupied(mut chan) => {
2311                                 if chan.get().get_their_node_id() != *their_node_id {
2312                                         //TODO: here and below MsgHandleErrInternal, #153 case
2313                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2314                                 }
2315                                 if (msg.failure_code & 0x8000) == 0 {
2316                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2317                                 }
2318                                 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
2319                                 Ok(())
2320                         },
2321                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2322                 }
2323         }
2324
2325         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2326                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2327                 let channel_state = channel_state_lock.borrow_parts();
2328                 match channel_state.by_id.entry(msg.channel_id) {
2329                         hash_map::Entry::Occupied(mut chan) => {
2330                                 if chan.get().get_their_node_id() != *their_node_id {
2331                                         //TODO: here and below MsgHandleErrInternal, #153 case
2332                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2333                                 }
2334                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2335                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2336                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2337                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2338                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2339                                 }
2340                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2341                                         node_id: their_node_id.clone(),
2342                                         msg: revoke_and_ack,
2343                                 });
2344                                 if let Some(msg) = commitment_signed {
2345                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2346                                                 node_id: their_node_id.clone(),
2347                                                 updates: msgs::CommitmentUpdate {
2348                                                         update_add_htlcs: Vec::new(),
2349                                                         update_fulfill_htlcs: Vec::new(),
2350                                                         update_fail_htlcs: Vec::new(),
2351                                                         update_fail_malformed_htlcs: Vec::new(),
2352                                                         update_fee: None,
2353                                                         commitment_signed: msg,
2354                                                 },
2355                                         });
2356                                 }
2357                                 if let Some(msg) = closing_signed {
2358                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2359                                                 node_id: their_node_id.clone(),
2360                                                 msg,
2361                                         });
2362                                 }
2363                                 Ok(())
2364                         },
2365                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2366                 }
2367         }
2368
2369         #[inline]
2370         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2371                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2372                         let mut forward_event = None;
2373                         if !pending_forwards.is_empty() {
2374                                 let mut channel_state = self.channel_state.lock().unwrap();
2375                                 if channel_state.forward_htlcs.is_empty() {
2376                                         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));
2377                                         channel_state.next_forward = forward_event.unwrap();
2378                                 }
2379                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2380                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2381                                                 hash_map::Entry::Occupied(mut entry) => {
2382                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2383                                                 },
2384                                                 hash_map::Entry::Vacant(entry) => {
2385                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2386                                                 }
2387                                         }
2388                                 }
2389                         }
2390                         match forward_event {
2391                                 Some(time) => {
2392                                         let mut pending_events = self.pending_events.lock().unwrap();
2393                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2394                                                 time_forwardable: time
2395                                         });
2396                                 }
2397                                 None => {},
2398                         }
2399                 }
2400         }
2401
2402         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2403                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2404                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2405                         let channel_state = channel_state_lock.borrow_parts();
2406                         match channel_state.by_id.entry(msg.channel_id) {
2407                                 hash_map::Entry::Occupied(mut chan) => {
2408                                         if chan.get().get_their_node_id() != *their_node_id {
2409                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2410                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2411                                         }
2412                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2413                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2414                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2415                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2416                                         }
2417                                         if let Some(updates) = commitment_update {
2418                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2419                                                         node_id: their_node_id.clone(),
2420                                                         updates,
2421                                                 });
2422                                         }
2423                                         if let Some(msg) = closing_signed {
2424                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2425                                                         node_id: their_node_id.clone(),
2426                                                         msg,
2427                                                 });
2428                                         }
2429                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2430                                 },
2431                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2432                         }
2433                 };
2434                 for failure in pending_failures.drain(..) {
2435                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2436                 }
2437                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2438
2439                 Ok(())
2440         }
2441
2442         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2443                 let mut channel_lock = self.channel_state.lock().unwrap();
2444                 let channel_state = channel_lock.borrow_parts();
2445                 match channel_state.by_id.entry(msg.channel_id) {
2446                         hash_map::Entry::Occupied(mut chan) => {
2447                                 if chan.get().get_their_node_id() != *their_node_id {
2448                                         //TODO: here and below MsgHandleErrInternal, #153 case
2449                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2450                                 }
2451                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2452                         },
2453                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2454                 }
2455                 Ok(())
2456         }
2457
2458         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2459                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2460                 let channel_state = channel_state_lock.borrow_parts();
2461
2462                 match channel_state.by_id.entry(msg.channel_id) {
2463                         hash_map::Entry::Occupied(mut chan) => {
2464                                 if chan.get().get_their_node_id() != *their_node_id {
2465                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2466                                 }
2467                                 if !chan.get().is_usable() {
2468                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2469                                 }
2470
2471                                 let our_node_id = self.get_our_node_id();
2472                                 let (announcement, our_bitcoin_sig) =
2473                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2474
2475                                 let were_node_one = announcement.node_id_1 == our_node_id;
2476                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2477                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2478                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2479                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2480                                 }
2481
2482                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2483
2484                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2485                                         msg: msgs::ChannelAnnouncement {
2486                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2487                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2488                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2489                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2490                                                 contents: announcement,
2491                                         },
2492                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2493                                 });
2494                         },
2495                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2496                 }
2497                 Ok(())
2498         }
2499
2500         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2501                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2502                 let channel_state = channel_state_lock.borrow_parts();
2503
2504                 match channel_state.by_id.entry(msg.channel_id) {
2505                         hash_map::Entry::Occupied(mut chan) => {
2506                                 if chan.get().get_their_node_id() != *their_node_id {
2507                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2508                                 }
2509                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2510                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2511                                 if let Some(monitor) = channel_monitor {
2512                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2513                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2514                                                 // for the messages it returns, but if we're setting what messages to
2515                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2516                                                 if revoke_and_ack.is_none() {
2517                                                         order = RAACommitmentOrder::CommitmentFirst;
2518                                                 }
2519                                                 if commitment_update.is_none() {
2520                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2521                                                 }
2522                                                 return_monitor_err!(self, e, channel_state, chan, order);
2523                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2524                                         }
2525                                 }
2526                                 if let Some(msg) = funding_locked {
2527                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2528                                                 node_id: their_node_id.clone(),
2529                                                 msg
2530                                         });
2531                                 }
2532                                 macro_rules! send_raa { () => {
2533                                         if let Some(msg) = revoke_and_ack {
2534                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2535                                                         node_id: their_node_id.clone(),
2536                                                         msg
2537                                                 });
2538                                         }
2539                                 } }
2540                                 macro_rules! send_cu { () => {
2541                                         if let Some(updates) = commitment_update {
2542                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2543                                                         node_id: their_node_id.clone(),
2544                                                         updates
2545                                                 });
2546                                         }
2547                                 } }
2548                                 match order {
2549                                         RAACommitmentOrder::RevokeAndACKFirst => {
2550                                                 send_raa!();
2551                                                 send_cu!();
2552                                         },
2553                                         RAACommitmentOrder::CommitmentFirst => {
2554                                                 send_cu!();
2555                                                 send_raa!();
2556                                         },
2557                                 }
2558                                 if let Some(msg) = shutdown {
2559                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2560                                                 node_id: their_node_id.clone(),
2561                                                 msg,
2562                                         });
2563                                 }
2564                                 Ok(())
2565                         },
2566                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2567                 }
2568         }
2569
2570         /// Begin Update fee process. Allowed only on an outbound channel.
2571         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2572         /// PeerManager::process_events afterwards.
2573         /// Note: This API is likely to change!
2574         #[doc(hidden)]
2575         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2576                 let _ = self.total_consistency_lock.read().unwrap();
2577                 let their_node_id;
2578                 let err: Result<(), _> = loop {
2579                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2580                         let channel_state = channel_state_lock.borrow_parts();
2581
2582                         match channel_state.by_id.entry(channel_id) {
2583                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2584                                 hash_map::Entry::Occupied(mut chan) => {
2585                                         if !chan.get().is_outbound() {
2586                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2587                                         }
2588                                         if chan.get().is_awaiting_monitor_update() {
2589                                                 return Err(APIError::MonitorUpdateFailed);
2590                                         }
2591                                         if !chan.get().is_live() {
2592                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2593                                         }
2594                                         their_node_id = chan.get().get_their_node_id();
2595                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2596                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2597                                         {
2598                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2599                                                         unimplemented!();
2600                                                 }
2601                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2602                                                         node_id: chan.get().get_their_node_id(),
2603                                                         updates: msgs::CommitmentUpdate {
2604                                                                 update_add_htlcs: Vec::new(),
2605                                                                 update_fulfill_htlcs: Vec::new(),
2606                                                                 update_fail_htlcs: Vec::new(),
2607                                                                 update_fail_malformed_htlcs: Vec::new(),
2608                                                                 update_fee: Some(update_fee),
2609                                                                 commitment_signed,
2610                                                         },
2611                                                 });
2612                                         }
2613                                 },
2614                         }
2615                         return Ok(())
2616                 };
2617
2618                 match handle_error!(self, err, their_node_id) {
2619                         Ok(_) => unreachable!(),
2620                         Err(e) => {
2621                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2622                                 } else {
2623                                         log_error!(self, "Got bad keys: {}!", e.err);
2624                                         let mut channel_state = self.channel_state.lock().unwrap();
2625                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2626                                                 node_id: their_node_id,
2627                                                 action: e.action,
2628                                         });
2629                                 }
2630                                 Err(APIError::APIMisuseError { err: e.err })
2631                         },
2632                 }
2633         }
2634 }
2635
2636 impl events::MessageSendEventsProvider for ChannelManager {
2637         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2638                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2639                 // user to serialize a ChannelManager with pending events in it and lose those events on
2640                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2641                 {
2642                         //TODO: This behavior should be documented.
2643                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2644                                 if let Some(preimage) = htlc_update.payment_preimage {
2645                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2646                                 } else {
2647                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2648                                 }
2649                         }
2650                 }
2651
2652                 let mut ret = Vec::new();
2653                 let mut channel_state = self.channel_state.lock().unwrap();
2654                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2655                 ret
2656         }
2657 }
2658
2659 impl events::EventsProvider for ChannelManager {
2660         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2661                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2662                 // user to serialize a ChannelManager with pending events in it and lose those events on
2663                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2664                 {
2665                         //TODO: This behavior should be documented.
2666                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2667                                 if let Some(preimage) = htlc_update.payment_preimage {
2668                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2669                                 } else {
2670                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2671                                 }
2672                         }
2673                 }
2674
2675                 let mut ret = Vec::new();
2676                 let mut pending_events = self.pending_events.lock().unwrap();
2677                 mem::swap(&mut ret, &mut *pending_events);
2678                 ret
2679         }
2680 }
2681
2682 impl ChainListener for ChannelManager {
2683         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2684                 let _ = self.total_consistency_lock.read().unwrap();
2685                 let mut failed_channels = Vec::new();
2686                 {
2687                         let mut channel_lock = self.channel_state.lock().unwrap();
2688                         let channel_state = channel_lock.borrow_parts();
2689                         let short_to_id = channel_state.short_to_id;
2690                         let pending_msg_events = channel_state.pending_msg_events;
2691                         channel_state.by_id.retain(|_, channel| {
2692                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2693                                 if let Ok(Some(funding_locked)) = chan_res {
2694                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2695                                                 node_id: channel.get_their_node_id(),
2696                                                 msg: funding_locked,
2697                                         });
2698                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2699                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2700                                                         node_id: channel.get_their_node_id(),
2701                                                         msg: announcement_sigs,
2702                                                 });
2703                                         }
2704                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2705                                 } else if let Err(e) = chan_res {
2706                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2707                                                 node_id: channel.get_their_node_id(),
2708                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2709                                         });
2710                                         return false;
2711                                 }
2712                                 if let Some(funding_txo) = channel.get_funding_txo() {
2713                                         for tx in txn_matched {
2714                                                 for inp in tx.input.iter() {
2715                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2716                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2717                                                                         short_to_id.remove(&short_id);
2718                                                                 }
2719                                                                 // It looks like our counterparty went on-chain. We go ahead and
2720                                                                 // broadcast our latest local state as well here, just in case its
2721                                                                 // some kind of SPV attack, though we expect these to be dropped.
2722                                                                 failed_channels.push(channel.force_shutdown());
2723                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2724                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2725                                                                                 msg: update
2726                                                                         });
2727                                                                 }
2728                                                                 return false;
2729                                                         }
2730                                                 }
2731                                         }
2732                                 }
2733                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2734                                         if let Some(short_id) = channel.get_short_channel_id() {
2735                                                 short_to_id.remove(&short_id);
2736                                         }
2737                                         failed_channels.push(channel.force_shutdown());
2738                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2739                                         // the latest local tx for us, so we should skip that here (it doesn't really
2740                                         // hurt anything, but does make tests a bit simpler).
2741                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2742                                         if let Ok(update) = self.get_channel_update(&channel) {
2743                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2744                                                         msg: update
2745                                                 });
2746                                         }
2747                                         return false;
2748                                 }
2749                                 true
2750                         });
2751                 }
2752                 for failure in failed_channels.drain(..) {
2753                         self.finish_force_close_channel(failure);
2754                 }
2755                 self.latest_block_height.store(height as usize, Ordering::Release);
2756                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2757         }
2758
2759         /// We force-close the channel without letting our counterparty participate in the shutdown
2760         fn block_disconnected(&self, header: &BlockHeader) {
2761                 let _ = self.total_consistency_lock.read().unwrap();
2762                 let mut failed_channels = Vec::new();
2763                 {
2764                         let mut channel_lock = self.channel_state.lock().unwrap();
2765                         let channel_state = channel_lock.borrow_parts();
2766                         let short_to_id = channel_state.short_to_id;
2767                         let pending_msg_events = channel_state.pending_msg_events;
2768                         channel_state.by_id.retain(|_,  v| {
2769                                 if v.block_disconnected(header) {
2770                                         if let Some(short_id) = v.get_short_channel_id() {
2771                                                 short_to_id.remove(&short_id);
2772                                         }
2773                                         failed_channels.push(v.force_shutdown());
2774                                         if let Ok(update) = self.get_channel_update(&v) {
2775                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2776                                                         msg: update
2777                                                 });
2778                                         }
2779                                         false
2780                                 } else {
2781                                         true
2782                                 }
2783                         });
2784                 }
2785                 for failure in failed_channels.drain(..) {
2786                         self.finish_force_close_channel(failure);
2787                 }
2788                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2789                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2790         }
2791 }
2792
2793 impl ChannelMessageHandler for ChannelManager {
2794         //TODO: Handle errors and close channel (or so)
2795         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2796                 let _ = self.total_consistency_lock.read().unwrap();
2797                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2798         }
2799
2800         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2801                 let _ = self.total_consistency_lock.read().unwrap();
2802                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2803         }
2804
2805         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2806                 let _ = self.total_consistency_lock.read().unwrap();
2807                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2808         }
2809
2810         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2811                 let _ = self.total_consistency_lock.read().unwrap();
2812                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2813         }
2814
2815         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2816                 let _ = self.total_consistency_lock.read().unwrap();
2817                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2818         }
2819
2820         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2821                 let _ = self.total_consistency_lock.read().unwrap();
2822                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2823         }
2824
2825         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2826                 let _ = self.total_consistency_lock.read().unwrap();
2827                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2828         }
2829
2830         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2831                 let _ = self.total_consistency_lock.read().unwrap();
2832                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2833         }
2834
2835         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2836                 let _ = self.total_consistency_lock.read().unwrap();
2837                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2838         }
2839
2840         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2841                 let _ = self.total_consistency_lock.read().unwrap();
2842                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2843         }
2844
2845         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2846                 let _ = self.total_consistency_lock.read().unwrap();
2847                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2848         }
2849
2850         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2851                 let _ = self.total_consistency_lock.read().unwrap();
2852                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2853         }
2854
2855         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2856                 let _ = self.total_consistency_lock.read().unwrap();
2857                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2858         }
2859
2860         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2861                 let _ = self.total_consistency_lock.read().unwrap();
2862                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2863         }
2864
2865         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2866                 let _ = self.total_consistency_lock.read().unwrap();
2867                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2868         }
2869
2870         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2871                 let _ = self.total_consistency_lock.read().unwrap();
2872                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2873         }
2874
2875         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2876                 let _ = self.total_consistency_lock.read().unwrap();
2877                 let mut failed_channels = Vec::new();
2878                 let mut failed_payments = Vec::new();
2879                 {
2880                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2881                         let channel_state = channel_state_lock.borrow_parts();
2882                         let short_to_id = channel_state.short_to_id;
2883                         let pending_msg_events = channel_state.pending_msg_events;
2884                         if no_connection_possible {
2885                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2886                                 channel_state.by_id.retain(|_, chan| {
2887                                         if chan.get_their_node_id() == *their_node_id {
2888                                                 if let Some(short_id) = chan.get_short_channel_id() {
2889                                                         short_to_id.remove(&short_id);
2890                                                 }
2891                                                 failed_channels.push(chan.force_shutdown());
2892                                                 if let Ok(update) = self.get_channel_update(&chan) {
2893                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2894                                                                 msg: update
2895                                                         });
2896                                                 }
2897                                                 false
2898                                         } else {
2899                                                 true
2900                                         }
2901                                 });
2902                         } else {
2903                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2904                                 channel_state.by_id.retain(|_, chan| {
2905                                         if chan.get_their_node_id() == *their_node_id {
2906                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2907                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2908                                                 if !failed_adds.is_empty() {
2909                                                         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
2910                                                         failed_payments.push((chan_update, failed_adds));
2911                                                 }
2912                                                 if chan.is_shutdown() {
2913                                                         if let Some(short_id) = chan.get_short_channel_id() {
2914                                                                 short_to_id.remove(&short_id);
2915                                                         }
2916                                                         return false;
2917                                                 }
2918                                         }
2919                                         true
2920                                 })
2921                         }
2922                 }
2923                 for failure in failed_channels.drain(..) {
2924                         self.finish_force_close_channel(failure);
2925                 }
2926                 for (chan_update, mut htlc_sources) in failed_payments {
2927                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2928                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2929                         }
2930                 }
2931         }
2932
2933         fn peer_connected(&self, their_node_id: &PublicKey) {
2934                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2935
2936                 let _ = self.total_consistency_lock.read().unwrap();
2937                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2938                 let channel_state = channel_state_lock.borrow_parts();
2939                 let pending_msg_events = channel_state.pending_msg_events;
2940                 channel_state.by_id.retain(|_, chan| {
2941                         if chan.get_their_node_id() == *their_node_id {
2942                                 if !chan.have_received_message() {
2943                                         // If we created this (outbound) channel while we were disconnected from the
2944                                         // peer we probably failed to send the open_channel message, which is now
2945                                         // lost. We can't have had anything pending related to this channel, so we just
2946                                         // drop it.
2947                                         false
2948                                 } else {
2949                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2950                                                 node_id: chan.get_their_node_id(),
2951                                                 msg: chan.get_channel_reestablish(),
2952                                         });
2953                                         true
2954                                 }
2955                         } else { true }
2956                 });
2957                 //TODO: Also re-broadcast announcement_signatures
2958         }
2959
2960         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2961                 let _ = self.total_consistency_lock.read().unwrap();
2962
2963                 if msg.channel_id == [0; 32] {
2964                         for chan in self.list_channels() {
2965                                 if chan.remote_network_id == *their_node_id {
2966                                         self.force_close_channel(&chan.channel_id);
2967                                 }
2968                         }
2969                 } else {
2970                         self.force_close_channel(&msg.channel_id);
2971                 }
2972         }
2973 }
2974
2975 const SERIALIZATION_VERSION: u8 = 1;
2976 const MIN_SERIALIZATION_VERSION: u8 = 1;
2977
2978 impl Writeable for PendingForwardHTLCInfo {
2979         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2980                 if let &Some(ref onion) = &self.onion_packet {
2981                         1u8.write(writer)?;
2982                         onion.write(writer)?;
2983                 } else {
2984                         0u8.write(writer)?;
2985                 }
2986                 self.incoming_shared_secret.write(writer)?;
2987                 self.payment_hash.write(writer)?;
2988                 self.short_channel_id.write(writer)?;
2989                 self.amt_to_forward.write(writer)?;
2990                 self.outgoing_cltv_value.write(writer)?;
2991                 Ok(())
2992         }
2993 }
2994
2995 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2996         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2997                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2998                         0 => None,
2999                         1 => Some(msgs::OnionPacket::read(reader)?),
3000                         _ => return Err(DecodeError::InvalidValue),
3001                 };
3002                 Ok(PendingForwardHTLCInfo {
3003                         onion_packet,
3004                         incoming_shared_secret: Readable::read(reader)?,
3005                         payment_hash: Readable::read(reader)?,
3006                         short_channel_id: Readable::read(reader)?,
3007                         amt_to_forward: Readable::read(reader)?,
3008                         outgoing_cltv_value: Readable::read(reader)?,
3009                 })
3010         }
3011 }
3012
3013 impl Writeable for HTLCFailureMsg {
3014         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3015                 match self {
3016                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3017                                 0u8.write(writer)?;
3018                                 fail_msg.write(writer)?;
3019                         },
3020                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3021                                 1u8.write(writer)?;
3022                                 fail_msg.write(writer)?;
3023                         }
3024                 }
3025                 Ok(())
3026         }
3027 }
3028
3029 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3030         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3031                 match <u8 as Readable<R>>::read(reader)? {
3032                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3033                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3034                         _ => Err(DecodeError::InvalidValue),
3035                 }
3036         }
3037 }
3038
3039 impl Writeable for PendingHTLCStatus {
3040         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3041                 match self {
3042                         &PendingHTLCStatus::Forward(ref forward_info) => {
3043                                 0u8.write(writer)?;
3044                                 forward_info.write(writer)?;
3045                         },
3046                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3047                                 1u8.write(writer)?;
3048                                 fail_msg.write(writer)?;
3049                         }
3050                 }
3051                 Ok(())
3052         }
3053 }
3054
3055 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3056         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3057                 match <u8 as Readable<R>>::read(reader)? {
3058                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3059                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3060                         _ => Err(DecodeError::InvalidValue),
3061                 }
3062         }
3063 }
3064
3065 impl_writeable!(HTLCPreviousHopData, 0, {
3066         short_channel_id,
3067         htlc_id,
3068         incoming_packet_shared_secret
3069 });
3070
3071 impl Writeable for HTLCSource {
3072         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3073                 match self {
3074                         &HTLCSource::PreviousHopData(ref hop_data) => {
3075                                 0u8.write(writer)?;
3076                                 hop_data.write(writer)?;
3077                         },
3078                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3079                                 1u8.write(writer)?;
3080                                 route.write(writer)?;
3081                                 session_priv.write(writer)?;
3082                                 first_hop_htlc_msat.write(writer)?;
3083                         }
3084                 }
3085                 Ok(())
3086         }
3087 }
3088
3089 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3090         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3091                 match <u8 as Readable<R>>::read(reader)? {
3092                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3093                         1 => Ok(HTLCSource::OutboundRoute {
3094                                 route: Readable::read(reader)?,
3095                                 session_priv: Readable::read(reader)?,
3096                                 first_hop_htlc_msat: Readable::read(reader)?,
3097                         }),
3098                         _ => Err(DecodeError::InvalidValue),
3099                 }
3100         }
3101 }
3102
3103 impl Writeable for HTLCFailReason {
3104         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3105                 match self {
3106                         &HTLCFailReason::ErrorPacket { ref err } => {
3107                                 0u8.write(writer)?;
3108                                 err.write(writer)?;
3109                         },
3110                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3111                                 1u8.write(writer)?;
3112                                 failure_code.write(writer)?;
3113                                 data.write(writer)?;
3114                         }
3115                 }
3116                 Ok(())
3117         }
3118 }
3119
3120 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3121         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3122                 match <u8 as Readable<R>>::read(reader)? {
3123                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3124                         1 => Ok(HTLCFailReason::Reason {
3125                                 failure_code: Readable::read(reader)?,
3126                                 data: Readable::read(reader)?,
3127                         }),
3128                         _ => Err(DecodeError::InvalidValue),
3129                 }
3130         }
3131 }
3132
3133 impl_writeable!(HTLCForwardInfo, 0, {
3134         prev_short_channel_id,
3135         prev_htlc_id,
3136         forward_info
3137 });
3138
3139 impl Writeable for ChannelManager {
3140         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3141                 let _ = self.total_consistency_lock.write().unwrap();
3142
3143                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3144                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3145
3146                 self.genesis_hash.write(writer)?;
3147                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3148                 self.last_block_hash.lock().unwrap().write(writer)?;
3149
3150                 let channel_state = self.channel_state.lock().unwrap();
3151                 let mut unfunded_channels = 0;
3152                 for (_, channel) in channel_state.by_id.iter() {
3153                         if !channel.is_funding_initiated() {
3154                                 unfunded_channels += 1;
3155                         }
3156                 }
3157                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3158                 for (_, channel) in channel_state.by_id.iter() {
3159                         if channel.is_funding_initiated() {
3160                                 channel.write(writer)?;
3161                         }
3162                 }
3163
3164                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3165                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3166                         short_channel_id.write(writer)?;
3167                         (pending_forwards.len() as u64).write(writer)?;
3168                         for forward in pending_forwards {
3169                                 forward.write(writer)?;
3170                         }
3171                 }
3172
3173                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3174                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3175                         payment_hash.write(writer)?;
3176                         (previous_hops.len() as u64).write(writer)?;
3177                         for previous_hop in previous_hops {
3178                                 previous_hop.write(writer)?;
3179                         }
3180                 }
3181
3182                 Ok(())
3183         }
3184 }
3185
3186 /// Arguments for the creation of a ChannelManager that are not deserialized.
3187 ///
3188 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3189 /// is:
3190 /// 1) Deserialize all stored ChannelMonitors.
3191 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3192 ///    ChannelManager)>::read(reader, args).
3193 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3194 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3195 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3196 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3197 /// 4) Reconnect blocks on your ChannelMonitors.
3198 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3199 /// 6) Disconnect/connect blocks on the ChannelManager.
3200 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3201 ///    automatically as it does in ChannelManager::new()).
3202 pub struct ChannelManagerReadArgs<'a> {
3203         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3204         /// deserialization.
3205         pub keys_manager: Arc<KeysInterface>,
3206
3207         /// The fee_estimator for use in the ChannelManager in the future.
3208         ///
3209         /// No calls to the FeeEstimator will be made during deserialization.
3210         pub fee_estimator: Arc<FeeEstimator>,
3211         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3212         ///
3213         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3214         /// you have deserialized ChannelMonitors separately and will add them to your
3215         /// ManyChannelMonitor after deserializing this ChannelManager.
3216         pub monitor: Arc<ManyChannelMonitor>,
3217         /// The ChainWatchInterface for use in the ChannelManager in the future.
3218         ///
3219         /// No calls to the ChainWatchInterface will be made during deserialization.
3220         pub chain_monitor: Arc<ChainWatchInterface>,
3221         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3222         /// used to broadcast the latest local commitment transactions of channels which must be
3223         /// force-closed during deserialization.
3224         pub tx_broadcaster: Arc<BroadcasterInterface>,
3225         /// The Logger for use in the ChannelManager and which may be used to log information during
3226         /// deserialization.
3227         pub logger: Arc<Logger>,
3228         /// Default settings used for new channels. Any existing channels will continue to use the
3229         /// runtime settings which were stored when the ChannelManager was serialized.
3230         pub default_config: UserConfig,
3231
3232         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3233         /// value.get_funding_txo() should be the key).
3234         ///
3235         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3236         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3237         /// is true for missing channels as well. If there is a monitor missing for which we find
3238         /// channel data Err(DecodeError::InvalidValue) will be returned.
3239         ///
3240         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3241         /// this struct.
3242         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3243 }
3244
3245 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3246         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3247                 let _ver: u8 = Readable::read(reader)?;
3248                 let min_ver: u8 = Readable::read(reader)?;
3249                 if min_ver > SERIALIZATION_VERSION {
3250                         return Err(DecodeError::UnknownVersion);
3251                 }
3252
3253                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3254                 let latest_block_height: u32 = Readable::read(reader)?;
3255                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3256
3257                 let mut closed_channels = Vec::new();
3258
3259                 let channel_count: u64 = Readable::read(reader)?;
3260                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3261                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3262                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3263                 for _ in 0..channel_count {
3264                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3265                         if channel.last_block_connected != last_block_hash {
3266                                 return Err(DecodeError::InvalidValue);
3267                         }
3268
3269                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3270                         funding_txo_set.insert(funding_txo.clone());
3271                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3272                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3273                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3274                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3275                                         let mut force_close_res = channel.force_shutdown();
3276                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3277                                         closed_channels.push(force_close_res);
3278                                 } else {
3279                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3280                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3281                                         }
3282                                         by_id.insert(channel.channel_id(), channel);
3283                                 }
3284                         } else {
3285                                 return Err(DecodeError::InvalidValue);
3286                         }
3287                 }
3288
3289                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3290                         if !funding_txo_set.contains(funding_txo) {
3291                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3292                         }
3293                 }
3294
3295                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3296                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3297                 for _ in 0..forward_htlcs_count {
3298                         let short_channel_id = Readable::read(reader)?;
3299                         let pending_forwards_count: u64 = Readable::read(reader)?;
3300                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3301                         for _ in 0..pending_forwards_count {
3302                                 pending_forwards.push(Readable::read(reader)?);
3303                         }
3304                         forward_htlcs.insert(short_channel_id, pending_forwards);
3305                 }
3306
3307                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3308                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3309                 for _ in 0..claimable_htlcs_count {
3310                         let payment_hash = Readable::read(reader)?;
3311                         let previous_hops_len: u64 = Readable::read(reader)?;
3312                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3313                         for _ in 0..previous_hops_len {
3314                                 previous_hops.push(Readable::read(reader)?);
3315                         }
3316                         claimable_htlcs.insert(payment_hash, previous_hops);
3317                 }
3318
3319                 let channel_manager = ChannelManager {
3320                         genesis_hash,
3321                         fee_estimator: args.fee_estimator,
3322                         monitor: args.monitor,
3323                         chain_monitor: args.chain_monitor,
3324                         tx_broadcaster: args.tx_broadcaster,
3325
3326                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3327                         last_block_hash: Mutex::new(last_block_hash),
3328                         secp_ctx: Secp256k1::new(),
3329
3330                         channel_state: Mutex::new(ChannelHolder {
3331                                 by_id,
3332                                 short_to_id,
3333                                 next_forward: Instant::now(),
3334                                 forward_htlcs,
3335                                 claimable_htlcs,
3336                                 pending_msg_events: Vec::new(),
3337                         }),
3338                         our_network_key: args.keys_manager.get_node_secret(),
3339
3340                         pending_events: Mutex::new(Vec::new()),
3341                         total_consistency_lock: RwLock::new(()),
3342                         keys_manager: args.keys_manager,
3343                         logger: args.logger,
3344                         default_configuration: args.default_config,
3345                 };
3346
3347                 for close_res in closed_channels.drain(..) {
3348                         channel_manager.finish_force_close_channel(close_res);
3349                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3350                         //connection or two.
3351                 }
3352
3353                 Ok((last_block_hash.clone(), channel_manager))
3354         }
3355 }
3356
3357 #[cfg(test)]
3358 mod tests {
3359         use chain::chaininterface;
3360         use chain::transaction::OutPoint;
3361         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3362         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3363         use chain::keysinterface;
3364         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3365         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3366         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3367         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3368         use ln::router::{Route, RouteHop, Router};
3369         use ln::msgs;
3370         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3371         use util::test_utils;
3372         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3373         use util::errors::APIError;
3374         use util::logger::Logger;
3375         use util::ser::{Writeable, Writer, ReadableArgs};
3376         use util::config::UserConfig;
3377
3378         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3379         use bitcoin::util::bip143;
3380         use bitcoin::util::address::Address;
3381         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3382         use bitcoin::blockdata::block::{Block, BlockHeader};
3383         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3384         use bitcoin::blockdata::script::{Builder, Script};
3385         use bitcoin::blockdata::opcodes;
3386         use bitcoin::blockdata::constants::genesis_block;
3387         use bitcoin::network::constants::Network;
3388
3389         use hex;
3390
3391         use secp256k1::{Secp256k1, Message};
3392         use secp256k1::key::{PublicKey,SecretKey};
3393
3394         use crypto::sha2::Sha256;
3395         use crypto::digest::Digest;
3396
3397         use rand::{thread_rng,Rng};
3398
3399         use std::cell::RefCell;
3400         use std::collections::{BTreeSet, HashMap, HashSet};
3401         use std::default::Default;
3402         use std::rc::Rc;
3403         use std::sync::{Arc, Mutex};
3404         use std::sync::atomic::Ordering;
3405         use std::time::Instant;
3406         use std::mem;
3407
3408         fn build_test_onion_keys() -> Vec<OnionKeys> {
3409                 // Keys from BOLT 4, used in both test vector tests
3410                 let secp_ctx = Secp256k1::new();
3411
3412                 let route = Route {
3413                         hops: vec!(
3414                                         RouteHop {
3415                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3416                                                 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
3417                                         },
3418                                         RouteHop {
3419                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3420                                                 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
3421                                         },
3422                                         RouteHop {
3423                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3424                                                 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
3425                                         },
3426                                         RouteHop {
3427                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3428                                                 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
3429                                         },
3430                                         RouteHop {
3431                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3432                                                 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
3433                                         },
3434                         ),
3435                 };
3436
3437                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3438
3439                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3440                 assert_eq!(onion_keys.len(), route.hops.len());
3441                 onion_keys
3442         }
3443
3444         #[test]
3445         fn onion_vectors() {
3446                 // Packet creation test vectors from BOLT 4
3447                 let onion_keys = build_test_onion_keys();
3448
3449                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3450                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3451                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3452                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3453                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3454
3455                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3456                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3457                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3458                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3459                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3460
3461                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3462                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3463                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3464                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3465                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3466
3467                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3468                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3469                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3470                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3471                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3472
3473                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3474                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3475                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3476                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3477                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3478
3479                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3480                 let payloads = vec!(
3481                         msgs::OnionHopData {
3482                                 realm: 0,
3483                                 data: msgs::OnionRealm0HopData {
3484                                         short_channel_id: 0,
3485                                         amt_to_forward: 0,
3486                                         outgoing_cltv_value: 0,
3487                                 },
3488                                 hmac: [0; 32],
3489                         },
3490                         msgs::OnionHopData {
3491                                 realm: 0,
3492                                 data: msgs::OnionRealm0HopData {
3493                                         short_channel_id: 0x0101010101010101,
3494                                         amt_to_forward: 0x0100000001,
3495                                         outgoing_cltv_value: 0,
3496                                 },
3497                                 hmac: [0; 32],
3498                         },
3499                         msgs::OnionHopData {
3500                                 realm: 0,
3501                                 data: msgs::OnionRealm0HopData {
3502                                         short_channel_id: 0x0202020202020202,
3503                                         amt_to_forward: 0x0200000002,
3504                                         outgoing_cltv_value: 0,
3505                                 },
3506                                 hmac: [0; 32],
3507                         },
3508                         msgs::OnionHopData {
3509                                 realm: 0,
3510                                 data: msgs::OnionRealm0HopData {
3511                                         short_channel_id: 0x0303030303030303,
3512                                         amt_to_forward: 0x0300000003,
3513                                         outgoing_cltv_value: 0,
3514                                 },
3515                                 hmac: [0; 32],
3516                         },
3517                         msgs::OnionHopData {
3518                                 realm: 0,
3519                                 data: msgs::OnionRealm0HopData {
3520                                         short_channel_id: 0x0404040404040404,
3521                                         amt_to_forward: 0x0400000004,
3522                                         outgoing_cltv_value: 0,
3523                                 },
3524                                 hmac: [0; 32],
3525                         },
3526                 );
3527
3528                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3529                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3530                 // anyway...
3531                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3532         }
3533
3534         #[test]
3535         fn test_failure_packet_onion() {
3536                 // Returning Errors test vectors from BOLT 4
3537
3538                 let onion_keys = build_test_onion_keys();
3539                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3540                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3541
3542                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3543                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3544
3545                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3546                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3547
3548                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3549                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3550
3551                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3552                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3553
3554                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3555                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3556         }
3557
3558         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3559                 assert!(chain.does_match_tx(tx));
3560                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3561                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3562                 for i in 2..100 {
3563                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3564                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3565                 }
3566         }
3567
3568         struct Node {
3569                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3570                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3571                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3572                 node: Arc<ChannelManager>,
3573                 router: Router,
3574                 node_seed: [u8; 32],
3575                 network_payment_count: Rc<RefCell<u8>>,
3576                 network_chan_count: Rc<RefCell<u32>>,
3577         }
3578         impl Drop for Node {
3579                 fn drop(&mut self) {
3580                         if !::std::thread::panicking() {
3581                                 // Check that we processed all pending events
3582                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3583                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3584                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3585                         }
3586                 }
3587         }
3588
3589         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3590                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3591         }
3592
3593         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) {
3594                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3595                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3596                 (announcement, as_update, bs_update, channel_id, tx)
3597         }
3598
3599         macro_rules! get_revoke_commit_msgs {
3600                 ($node: expr, $node_id: expr) => {
3601                         {
3602                                 let events = $node.node.get_and_clear_pending_msg_events();
3603                                 assert_eq!(events.len(), 2);
3604                                 (match events[0] {
3605                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3606                                                 assert_eq!(*node_id, $node_id);
3607                                                 (*msg).clone()
3608                                         },
3609                                         _ => panic!("Unexpected event"),
3610                                 }, match events[1] {
3611                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3612                                                 assert_eq!(*node_id, $node_id);
3613                                                 assert!(updates.update_add_htlcs.is_empty());
3614                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3615                                                 assert!(updates.update_fail_htlcs.is_empty());
3616                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3617                                                 assert!(updates.update_fee.is_none());
3618                                                 updates.commitment_signed.clone()
3619                                         },
3620                                         _ => panic!("Unexpected event"),
3621                                 })
3622                         }
3623                 }
3624         }
3625
3626         macro_rules! get_event_msg {
3627                 ($node: expr, $event_type: path, $node_id: expr) => {
3628                         {
3629                                 let events = $node.node.get_and_clear_pending_msg_events();
3630                                 assert_eq!(events.len(), 1);
3631                                 match events[0] {
3632                                         $event_type { ref node_id, ref msg } => {
3633                                                 assert_eq!(*node_id, $node_id);
3634                                                 (*msg).clone()
3635                                         },
3636                                         _ => panic!("Unexpected event"),
3637                                 }
3638                         }
3639                 }
3640         }
3641
3642         macro_rules! get_htlc_update_msgs {
3643                 ($node: expr, $node_id: expr) => {
3644                         {
3645                                 let events = $node.node.get_and_clear_pending_msg_events();
3646                                 assert_eq!(events.len(), 1);
3647                                 match events[0] {
3648                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3649                                                 assert_eq!(*node_id, $node_id);
3650                                                 (*updates).clone()
3651                                         },
3652                                         _ => panic!("Unexpected event"),
3653                                 }
3654                         }
3655                 }
3656         }
3657
3658         macro_rules! get_feerate {
3659                 ($node: expr, $channel_id: expr) => {
3660                         {
3661                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3662                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3663                                 chan.get_feerate()
3664                         }
3665                 }
3666         }
3667
3668
3669         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3670                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3671                 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
3672                 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id())).unwrap();
3673
3674                 let chan_id = *node_a.network_chan_count.borrow();
3675                 let tx;
3676                 let funding_output;
3677
3678                 let events_2 = node_a.node.get_and_clear_pending_events();
3679                 assert_eq!(events_2.len(), 1);
3680                 match events_2[0] {
3681                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3682                                 assert_eq!(*channel_value_satoshis, channel_value);
3683                                 assert_eq!(user_channel_id, 42);
3684
3685                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3686                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3687                                 }]};
3688                                 funding_output = OutPoint::new(tx.txid(), 0);
3689
3690                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3691                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3692                                 assert_eq!(added_monitors.len(), 1);
3693                                 assert_eq!(added_monitors[0].0, funding_output);
3694                                 added_monitors.clear();
3695                         },
3696                         _ => panic!("Unexpected event"),
3697                 }
3698
3699                 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id())).unwrap();
3700                 {
3701                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3702                         assert_eq!(added_monitors.len(), 1);
3703                         assert_eq!(added_monitors[0].0, funding_output);
3704                         added_monitors.clear();
3705                 }
3706
3707                 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id())).unwrap();
3708                 {
3709                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3710                         assert_eq!(added_monitors.len(), 1);
3711                         assert_eq!(added_monitors[0].0, funding_output);
3712                         added_monitors.clear();
3713                 }
3714
3715                 let events_4 = node_a.node.get_and_clear_pending_events();
3716                 assert_eq!(events_4.len(), 1);
3717                 match events_4[0] {
3718                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3719                                 assert_eq!(user_channel_id, 42);
3720                                 assert_eq!(*funding_txo, funding_output);
3721                         },
3722                         _ => panic!("Unexpected event"),
3723                 };
3724
3725                 tx
3726         }
3727
3728         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3729                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3730                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingLocked, node_a.node.get_our_node_id())).unwrap();
3731
3732                 let channel_id;
3733
3734                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3735                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3736                 assert_eq!(events_6.len(), 2);
3737                 ((match events_6[0] {
3738                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3739                                 channel_id = msg.channel_id.clone();
3740                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3741                                 msg.clone()
3742                         },
3743                         _ => panic!("Unexpected event"),
3744                 }, match events_6[1] {
3745                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3746                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3747                                 msg.clone()
3748                         },
3749                         _ => panic!("Unexpected event"),
3750                 }), channel_id)
3751         }
3752
3753         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) {
3754                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3755                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3756                 (msgs, chan_id, tx)
3757         }
3758
3759         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) {
3760                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3761                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3762                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3763
3764                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3765                 assert_eq!(events_7.len(), 1);
3766                 let (announcement, bs_update) = match events_7[0] {
3767                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3768                                 (msg, update_msg)
3769                         },
3770                         _ => panic!("Unexpected event"),
3771                 };
3772
3773                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3774                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3775                 assert_eq!(events_8.len(), 1);
3776                 let as_update = match events_8[0] {
3777                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3778                                 assert!(*announcement == *msg);
3779                                 update_msg
3780                         },
3781                         _ => panic!("Unexpected event"),
3782                 };
3783
3784                 *node_a.network_chan_count.borrow_mut() += 1;
3785
3786                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3787         }
3788
3789         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3790                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3791         }
3792
3793         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) {
3794                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3795                 for node in nodes {
3796                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3797                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3798                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3799                 }
3800                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3801         }
3802
3803         macro_rules! check_spends {
3804                 ($tx: expr, $spends_tx: expr) => {
3805                         {
3806                                 let mut funding_tx_map = HashMap::new();
3807                                 let spends_tx = $spends_tx;
3808                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3809                                 $tx.verify(&funding_tx_map).unwrap();
3810                         }
3811                 }
3812         }
3813
3814         macro_rules! get_closing_signed_broadcast {
3815                 ($node: expr, $dest_pubkey: expr) => {
3816                         {
3817                                 let events = $node.get_and_clear_pending_msg_events();
3818                                 assert!(events.len() == 1 || events.len() == 2);
3819                                 (match events[events.len() - 1] {
3820                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3821                                                 assert_eq!(msg.contents.flags & 2, 2);
3822                                                 msg.clone()
3823                                         },
3824                                         _ => panic!("Unexpected event"),
3825                                 }, if events.len() == 2 {
3826                                         match events[0] {
3827                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3828                                                         assert_eq!(*node_id, $dest_pubkey);
3829                                                         Some(msg.clone())
3830                                                 },
3831                                                 _ => panic!("Unexpected event"),
3832                                         }
3833                                 } else { None })
3834                         }
3835                 }
3836         }
3837
3838         fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
3839                 let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
3840                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3841                 let (tx_a, tx_b);
3842
3843                 node_a.close_channel(channel_id).unwrap();
3844                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3845
3846                 let events_1 = node_b.get_and_clear_pending_msg_events();
3847                 assert!(events_1.len() >= 1);
3848                 let shutdown_b = match events_1[0] {
3849                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3850                                 assert_eq!(node_id, &node_a.get_our_node_id());
3851                                 msg.clone()
3852                         },
3853                         _ => panic!("Unexpected event"),
3854                 };
3855
3856                 let closing_signed_b = if !close_inbound_first {
3857                         assert_eq!(events_1.len(), 1);
3858                         None
3859                 } else {
3860                         Some(match events_1[1] {
3861                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3862                                         assert_eq!(node_id, &node_a.get_our_node_id());
3863                                         msg.clone()
3864                                 },
3865                                 _ => panic!("Unexpected event"),
3866                         })
3867                 };
3868
3869                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3870                 let (as_update, bs_update) = if close_inbound_first {
3871                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3872                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3873                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3874                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3875                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3876
3877                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3878                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3879                         assert!(none_b.is_none());
3880                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3881                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3882                         (as_update, bs_update)
3883                 } else {
3884                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3885
3886                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3887                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3888                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3889                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3890
3891                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3892                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3893                         assert!(none_a.is_none());
3894                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3895                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3896                         (as_update, bs_update)
3897                 };
3898                 assert_eq!(tx_a, tx_b);
3899                 check_spends!(tx_a, funding_tx);
3900
3901                 (as_update, bs_update, tx_a)
3902         }
3903
3904         struct SendEvent {
3905                 node_id: PublicKey,
3906                 msgs: Vec<msgs::UpdateAddHTLC>,
3907                 commitment_msg: msgs::CommitmentSigned,
3908         }
3909         impl SendEvent {
3910                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3911                         assert!(updates.update_fulfill_htlcs.is_empty());
3912                         assert!(updates.update_fail_htlcs.is_empty());
3913                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3914                         assert!(updates.update_fee.is_none());
3915                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3916                 }
3917
3918                 fn from_event(event: MessageSendEvent) -> SendEvent {
3919                         match event {
3920                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3921                                 _ => panic!("Unexpected event type!"),
3922                         }
3923                 }
3924
3925                 fn from_node(node: &Node) -> SendEvent {
3926                         let mut events = node.node.get_and_clear_pending_msg_events();
3927                         assert_eq!(events.len(), 1);
3928                         SendEvent::from_event(events.pop().unwrap())
3929                 }
3930         }
3931
3932         macro_rules! check_added_monitors {
3933                 ($node: expr, $count: expr) => {
3934                         {
3935                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3936                                 assert_eq!(added_monitors.len(), $count);
3937                                 added_monitors.clear();
3938                         }
3939                 }
3940         }
3941
3942         macro_rules! commitment_signed_dance {
3943                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3944                         {
3945                                 check_added_monitors!($node_a, 0);
3946                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3947                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3948                                 check_added_monitors!($node_a, 1);
3949                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3950                         }
3951                 };
3952                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3953                         {
3954                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3955                                 check_added_monitors!($node_b, 0);
3956                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3957                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3958                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3959                                 check_added_monitors!($node_b, 1);
3960                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3961                                 let (bs_revoke_and_ack, extra_msg_option) = {
3962                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3963                                         assert!(events.len() <= 2);
3964                                         (match events[0] {
3965                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3966                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3967                                                         (*msg).clone()
3968                                                 },
3969                                                 _ => panic!("Unexpected event"),
3970                                         }, events.get(1).map(|e| e.clone()))
3971                                 };
3972                                 check_added_monitors!($node_b, 1);
3973                                 if $fail_backwards {
3974                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3975                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3976                                 }
3977                                 (extra_msg_option, bs_revoke_and_ack)
3978                         }
3979                 };
3980                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3981                         {
3982                                 check_added_monitors!($node_a, 0);
3983                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3984                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3985                                 check_added_monitors!($node_a, 1);
3986                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3987                                 assert!(extra_msg_option.is_none());
3988                                 bs_revoke_and_ack
3989                         }
3990                 };
3991                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3992                         {
3993                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3994                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3995                                 {
3996                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3997                                         if $fail_backwards {
3998                                                 assert_eq!(added_monitors.len(), 2);
3999                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4000                                         } else {
4001                                                 assert_eq!(added_monitors.len(), 1);
4002                                         }
4003                                         added_monitors.clear();
4004                                 }
4005                                 extra_msg_option
4006                         }
4007                 };
4008                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4009                         {
4010                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4011                         }
4012                 };
4013                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4014                         {
4015                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4016                                 if $fail_backwards {
4017                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4018                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4019                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4020                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4021                                         } else { panic!("Unexpected event"); }
4022                                 } else {
4023                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4024                                 }
4025                         }
4026                 }
4027         }
4028
4029         macro_rules! get_payment_preimage_hash {
4030                 ($node: expr) => {
4031                         {
4032                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4033                                 *$node.network_payment_count.borrow_mut() += 1;
4034                                 let mut payment_hash = PaymentHash([0; 32]);
4035                                 let mut sha = Sha256::new();
4036                                 sha.input(&payment_preimage.0[..]);
4037                                 sha.result(&mut payment_hash.0[..]);
4038                                 (payment_preimage, payment_hash)
4039                         }
4040                 }
4041         }
4042
4043         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4044                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4045
4046                 let mut payment_event = {
4047                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4048                         check_added_monitors!(origin_node, 1);
4049
4050                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4051                         assert_eq!(events.len(), 1);
4052                         SendEvent::from_event(events.remove(0))
4053                 };
4054                 let mut prev_node = origin_node;
4055
4056                 for (idx, &node) in expected_route.iter().enumerate() {
4057                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4058
4059                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4060                         check_added_monitors!(node, 0);
4061                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4062
4063                         let events_1 = node.node.get_and_clear_pending_events();
4064                         assert_eq!(events_1.len(), 1);
4065                         match events_1[0] {
4066                                 Event::PendingHTLCsForwardable { .. } => { },
4067                                 _ => panic!("Unexpected event"),
4068                         };
4069
4070                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4071                         node.node.process_pending_htlc_forwards();
4072
4073                         if idx == expected_route.len() - 1 {
4074                                 let events_2 = node.node.get_and_clear_pending_events();
4075                                 assert_eq!(events_2.len(), 1);
4076                                 match events_2[0] {
4077                                         Event::PaymentReceived { ref payment_hash, amt } => {
4078                                                 assert_eq!(our_payment_hash, *payment_hash);
4079                                                 assert_eq!(amt, recv_value);
4080                                         },
4081                                         _ => panic!("Unexpected event"),
4082                                 }
4083                         } else {
4084                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4085                                 assert_eq!(events_2.len(), 1);
4086                                 check_added_monitors!(node, 1);
4087                                 payment_event = SendEvent::from_event(events_2.remove(0));
4088                                 assert_eq!(payment_event.msgs.len(), 1);
4089                         }
4090
4091                         prev_node = node;
4092                 }
4093
4094                 (our_payment_preimage, our_payment_hash)
4095         }
4096
4097         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4098                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4099                 check_added_monitors!(expected_route.last().unwrap(), 1);
4100
4101                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4102                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4103                 macro_rules! get_next_msgs {
4104                         ($node: expr) => {
4105                                 {
4106                                         let events = $node.node.get_and_clear_pending_msg_events();
4107                                         assert_eq!(events.len(), 1);
4108                                         match events[0] {
4109                                                 MessageSendEvent::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 } } => {
4110                                                         assert!(update_add_htlcs.is_empty());
4111                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4112                                                         assert!(update_fail_htlcs.is_empty());
4113                                                         assert!(update_fail_malformed_htlcs.is_empty());
4114                                                         assert!(update_fee.is_none());
4115                                                         expected_next_node = node_id.clone();
4116                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4117                                                 },
4118                                                 _ => panic!("Unexpected event"),
4119                                         }
4120                                 }
4121                         }
4122                 }
4123
4124                 macro_rules! last_update_fulfill_dance {
4125                         ($node: expr, $prev_node: expr) => {
4126                                 {
4127                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4128                                         check_added_monitors!($node, 0);
4129                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4130                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4131                                 }
4132                         }
4133                 }
4134                 macro_rules! mid_update_fulfill_dance {
4135                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4136                                 {
4137                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4138                                         check_added_monitors!($node, 1);
4139                                         let new_next_msgs = if $new_msgs {
4140                                                 get_next_msgs!($node)
4141                                         } else {
4142                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4143                                                 None
4144                                         };
4145                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4146                                         next_msgs = new_next_msgs;
4147                                 }
4148                         }
4149                 }
4150
4151                 let mut prev_node = expected_route.last().unwrap();
4152                 for (idx, node) in expected_route.iter().rev().enumerate() {
4153                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4154                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4155                         if next_msgs.is_some() {
4156                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4157                         } else if update_next_msgs {
4158                                 next_msgs = get_next_msgs!(node);
4159                         } else {
4160                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4161                         }
4162                         if !skip_last && idx == expected_route.len() - 1 {
4163                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4164                         }
4165
4166                         prev_node = node;
4167                 }
4168
4169                 if !skip_last {
4170                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4171                         let events = origin_node.node.get_and_clear_pending_events();
4172                         assert_eq!(events.len(), 1);
4173                         match events[0] {
4174                                 Event::PaymentSent { payment_preimage } => {
4175                                         assert_eq!(payment_preimage, our_payment_preimage);
4176                                 },
4177                                 _ => panic!("Unexpected event"),
4178                         }
4179                 }
4180         }
4181
4182         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4183                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4184         }
4185
4186         const TEST_FINAL_CLTV: u32 = 32;
4187
4188         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4189                 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();
4190                 assert_eq!(route.hops.len(), expected_route.len());
4191                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4192                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4193                 }
4194
4195                 send_along_route(origin_node, route, expected_route, recv_value)
4196         }
4197
4198         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4199                 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();
4200                 assert_eq!(route.hops.len(), expected_route.len());
4201                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4202                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4203                 }
4204
4205                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4206
4207                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4208                 match err {
4209                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4210                         _ => panic!("Unknown error variants"),
4211                 };
4212         }
4213
4214         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4215                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4216                 claim_payment(&origin, expected_route, our_payment_preimage);
4217         }
4218
4219         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4220                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4221                 check_added_monitors!(expected_route.last().unwrap(), 1);
4222
4223                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4224                 macro_rules! update_fail_dance {
4225                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4226                                 {
4227                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4228                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4229                                 }
4230                         }
4231                 }
4232
4233                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4234                 let mut prev_node = expected_route.last().unwrap();
4235                 for (idx, node) in expected_route.iter().rev().enumerate() {
4236                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4237                         if next_msgs.is_some() {
4238                                 // We may be the "last node" for the purpose of the commitment dance if we're
4239                                 // skipping the last node (implying it is disconnected) and we're the
4240                                 // second-to-last node!
4241                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4242                         }
4243
4244                         let events = node.node.get_and_clear_pending_msg_events();
4245                         if !skip_last || idx != expected_route.len() - 1 {
4246                                 assert_eq!(events.len(), 1);
4247                                 match events[0] {
4248                                         MessageSendEvent::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 } } => {
4249                                                 assert!(update_add_htlcs.is_empty());
4250                                                 assert!(update_fulfill_htlcs.is_empty());
4251                                                 assert_eq!(update_fail_htlcs.len(), 1);
4252                                                 assert!(update_fail_malformed_htlcs.is_empty());
4253                                                 assert!(update_fee.is_none());
4254                                                 expected_next_node = node_id.clone();
4255                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4256                                         },
4257                                         _ => panic!("Unexpected event"),
4258                                 }
4259                         } else {
4260                                 assert!(events.is_empty());
4261                         }
4262                         if !skip_last && idx == expected_route.len() - 1 {
4263                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4264                         }
4265
4266                         prev_node = node;
4267                 }
4268
4269                 if !skip_last {
4270                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4271
4272                         let events = origin_node.node.get_and_clear_pending_events();
4273                         assert_eq!(events.len(), 1);
4274                         match events[0] {
4275                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4276                                         assert_eq!(payment_hash, our_payment_hash);
4277                                         assert!(rejected_by_dest);
4278                                 },
4279                                 _ => panic!("Unexpected event"),
4280                         }
4281                 }
4282         }
4283
4284         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4285                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4286         }
4287
4288         fn create_network(node_count: usize) -> Vec<Node> {
4289                 let mut nodes = Vec::new();
4290                 let mut rng = thread_rng();
4291                 let secp_ctx = Secp256k1::new();
4292                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
4293
4294                 let chan_count = Rc::new(RefCell::new(0));
4295                 let payment_count = Rc::new(RefCell::new(0));
4296
4297                 for _ in 0..node_count {
4298                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4299                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4300                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4301                         let mut seed = [0; 32];
4302                         rng.fill_bytes(&mut seed);
4303                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4304                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4305                         let mut config = UserConfig::new();
4306                         config.channel_options.announced_channel = true;
4307                         config.channel_limits.force_announced_channel_preference = false;
4308                         let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap();
4309                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4310                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4311                                 network_payment_count: payment_count.clone(),
4312                                 network_chan_count: chan_count.clone(),
4313                         });
4314                 }
4315
4316                 nodes
4317         }
4318
4319         #[test]
4320         fn test_async_inbound_update_fee() {
4321                 let mut nodes = create_network(2);
4322                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4323                 let channel_id = chan.2;
4324
4325                 // balancing
4326                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4327
4328                 // A                                        B
4329                 // update_fee                            ->
4330                 // send (1) commitment_signed            -.
4331                 //                                       <- update_add_htlc/commitment_signed
4332                 // send (2) RAA (awaiting remote revoke) -.
4333                 // (1) commitment_signed is delivered    ->
4334                 //                                       .- send (3) RAA (awaiting remote revoke)
4335                 // (2) RAA is delivered                  ->
4336                 //                                       .- send (4) commitment_signed
4337                 //                                       <- (3) RAA is delivered
4338                 // send (5) commitment_signed            -.
4339                 //                                       <- (4) commitment_signed is delivered
4340                 // send (6) RAA                          -.
4341                 // (5) commitment_signed is delivered    ->
4342                 //                                       <- RAA
4343                 // (6) RAA is delivered                  ->
4344
4345                 // First nodes[0] generates an update_fee
4346                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4347                 check_added_monitors!(nodes[0], 1);
4348
4349                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4350                 assert_eq!(events_0.len(), 1);
4351                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4352                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4353                                 (update_fee.as_ref(), commitment_signed)
4354                         },
4355                         _ => panic!("Unexpected event"),
4356                 };
4357
4358                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4359
4360                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4361                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4362                 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();
4363                 check_added_monitors!(nodes[1], 1);
4364
4365                 let payment_event = {
4366                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4367                         assert_eq!(events_1.len(), 1);
4368                         SendEvent::from_event(events_1.remove(0))
4369                 };
4370                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4371                 assert_eq!(payment_event.msgs.len(), 1);
4372
4373                 // ...now when the messages get delivered everyone should be happy
4374                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4375                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4376                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4377                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4378                 check_added_monitors!(nodes[0], 1);
4379
4380                 // deliver(1), generate (3):
4381                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4382                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4383                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4384                 check_added_monitors!(nodes[1], 1);
4385
4386                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4387                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4388                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4389                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4390                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4391                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4392                 assert!(bs_update.update_fee.is_none()); // (4)
4393                 check_added_monitors!(nodes[1], 1);
4394
4395                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4396                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4397                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4398                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4399                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4400                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4401                 assert!(as_update.update_fee.is_none()); // (5)
4402                 check_added_monitors!(nodes[0], 1);
4403
4404                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4405                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4406                 // only (6) so get_event_msg's assert(len == 1) passes
4407                 check_added_monitors!(nodes[0], 1);
4408
4409                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4410                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4411                 check_added_monitors!(nodes[1], 1);
4412
4413                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4414                 check_added_monitors!(nodes[0], 1);
4415
4416                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4417                 assert_eq!(events_2.len(), 1);
4418                 match events_2[0] {
4419                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4420                         _ => panic!("Unexpected event"),
4421                 }
4422
4423                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4424                 check_added_monitors!(nodes[1], 1);
4425         }
4426
4427         #[test]
4428         fn test_update_fee_unordered_raa() {
4429                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4430                 // crash in an earlier version of the update_fee patch)
4431                 let mut nodes = create_network(2);
4432                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4433                 let channel_id = chan.2;
4434
4435                 // balancing
4436                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4437
4438                 // First nodes[0] generates an update_fee
4439                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4440                 check_added_monitors!(nodes[0], 1);
4441
4442                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4443                 assert_eq!(events_0.len(), 1);
4444                 let update_msg = match events_0[0] { // (1)
4445                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4446                                 update_fee.as_ref()
4447                         },
4448                         _ => panic!("Unexpected event"),
4449                 };
4450
4451                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4452
4453                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4454                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4455                 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();
4456                 check_added_monitors!(nodes[1], 1);
4457
4458                 let payment_event = {
4459                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4460                         assert_eq!(events_1.len(), 1);
4461                         SendEvent::from_event(events_1.remove(0))
4462                 };
4463                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4464                 assert_eq!(payment_event.msgs.len(), 1);
4465
4466                 // ...now when the messages get delivered everyone should be happy
4467                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4468                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4469                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4470                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4471                 check_added_monitors!(nodes[0], 1);
4472
4473                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4474                 check_added_monitors!(nodes[1], 1);
4475
4476                 // We can't continue, sadly, because our (1) now has a bogus signature
4477         }
4478
4479         #[test]
4480         fn test_multi_flight_update_fee() {
4481                 let nodes = create_network(2);
4482                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4483                 let channel_id = chan.2;
4484
4485                 // A                                        B
4486                 // update_fee/commitment_signed          ->
4487                 //                                       .- send (1) RAA and (2) commitment_signed
4488                 // update_fee (never committed)          ->
4489                 // (3) update_fee                        ->
4490                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4491                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4492                 // AwaitingRAA mode and will not generate the update_fee yet.
4493                 //                                       <- (1) RAA delivered
4494                 // (3) is generated and send (4) CS      -.
4495                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4496                 // know the per_commitment_point to use for it.
4497                 //                                       <- (2) commitment_signed delivered
4498                 // revoke_and_ack                        ->
4499                 //                                          B should send no response here
4500                 // (4) commitment_signed delivered       ->
4501                 //                                       <- RAA/commitment_signed delivered
4502                 // revoke_and_ack                        ->
4503
4504                 // First nodes[0] generates an update_fee
4505                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4506                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4507                 check_added_monitors!(nodes[0], 1);
4508
4509                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4510                 assert_eq!(events_0.len(), 1);
4511                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4512                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4513                                 (update_fee.as_ref().unwrap(), commitment_signed)
4514                         },
4515                         _ => panic!("Unexpected event"),
4516                 };
4517
4518                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4519                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4520                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4521                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4522                 check_added_monitors!(nodes[1], 1);
4523
4524                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4525                 // transaction:
4526                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4527                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4528                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4529
4530                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4531                 let mut update_msg_2 = msgs::UpdateFee {
4532                         channel_id: update_msg_1.channel_id.clone(),
4533                         feerate_per_kw: (initial_feerate + 30) as u32,
4534                 };
4535
4536                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4537
4538                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4539                 // Deliver (3)
4540                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4541
4542                 // Deliver (1), generating (3) and (4)
4543                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4544                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4545                 check_added_monitors!(nodes[0], 1);
4546                 assert!(as_second_update.update_add_htlcs.is_empty());
4547                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4548                 assert!(as_second_update.update_fail_htlcs.is_empty());
4549                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4550                 // Check that the update_fee newly generated matches what we delivered:
4551                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4552                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4553
4554                 // Deliver (2) commitment_signed
4555                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4556                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4557                 check_added_monitors!(nodes[0], 1);
4558                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4559
4560                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4561                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4562                 check_added_monitors!(nodes[1], 1);
4563
4564                 // Delever (4)
4565                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4566                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4567                 check_added_monitors!(nodes[1], 1);
4568
4569                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4570                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4571                 check_added_monitors!(nodes[0], 1);
4572
4573                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4574                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4575                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4576                 check_added_monitors!(nodes[0], 1);
4577
4578                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4579                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4580                 check_added_monitors!(nodes[1], 1);
4581         }
4582
4583         #[test]
4584         fn test_update_fee_vanilla() {
4585                 let nodes = create_network(2);
4586                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4587                 let channel_id = chan.2;
4588
4589                 let feerate = get_feerate!(nodes[0], channel_id);
4590                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4591                 check_added_monitors!(nodes[0], 1);
4592
4593                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4594                 assert_eq!(events_0.len(), 1);
4595                 let (update_msg, commitment_signed) = match events_0[0] {
4596                                 MessageSendEvent::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 } } => {
4597                                 (update_fee.as_ref(), commitment_signed)
4598                         },
4599                         _ => panic!("Unexpected event"),
4600                 };
4601                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4602
4603                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4604                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4605                 check_added_monitors!(nodes[1], 1);
4606
4607                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4608                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4609                 check_added_monitors!(nodes[0], 1);
4610
4611                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4612                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4613                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4614                 check_added_monitors!(nodes[0], 1);
4615
4616                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4617                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4618                 check_added_monitors!(nodes[1], 1);
4619         }
4620
4621         #[test]
4622         fn test_update_fee_that_funder_cannot_afford() {
4623                 let nodes = create_network(2);
4624                 let channel_value = 1888;
4625                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4626                 let channel_id = chan.2;
4627
4628                 let feerate = 260;
4629                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4630                 check_added_monitors!(nodes[0], 1);
4631                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4632
4633                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4634
4635                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4636
4637                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4638                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4639                 {
4640                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4641                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4642
4643                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4644                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4645                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4646                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4647                         actual_fee = channel_value - actual_fee;
4648                         assert_eq!(total_fee, actual_fee);
4649                 } //drop the mutex
4650
4651                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4652                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4653                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4654                 check_added_monitors!(nodes[0], 1);
4655
4656                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4657
4658                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4659
4660                 //While producing the commitment_signed response after handling a received update_fee request the
4661                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4662                 //Should produce and error.
4663                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4664
4665                 assert!(match err.err {
4666                         "Funding remote cannot afford proposed new fee" => true,
4667                         _ => false,
4668                 });
4669
4670                 //clear the message we could not handle
4671                 nodes[1].node.get_and_clear_pending_msg_events();
4672         }
4673
4674         #[test]
4675         fn test_update_fee_with_fundee_update_add_htlc() {
4676                 let mut nodes = create_network(2);
4677                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4678                 let channel_id = chan.2;
4679
4680                 // balancing
4681                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4682
4683                 let feerate = get_feerate!(nodes[0], channel_id);
4684                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4685                 check_added_monitors!(nodes[0], 1);
4686
4687                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4688                 assert_eq!(events_0.len(), 1);
4689                 let (update_msg, commitment_signed) = match events_0[0] {
4690                                 MessageSendEvent::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 } } => {
4691                                 (update_fee.as_ref(), commitment_signed)
4692                         },
4693                         _ => panic!("Unexpected event"),
4694                 };
4695                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4696                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4697                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4698                 check_added_monitors!(nodes[1], 1);
4699
4700                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4701
4702                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4703
4704                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4705                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4706                 {
4707                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4708                         assert_eq!(added_monitors.len(), 0);
4709                         added_monitors.clear();
4710                 }
4711                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4712                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4713                 // node[1] has nothing to do
4714
4715                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4716                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4717                 check_added_monitors!(nodes[0], 1);
4718
4719                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4720                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4721                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4722                 check_added_monitors!(nodes[0], 1);
4723                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4724                 check_added_monitors!(nodes[1], 1);
4725                 // AwaitingRemoteRevoke ends here
4726
4727                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4728                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4729                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4730                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4731                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4732                 assert_eq!(commitment_update.update_fee.is_none(), true);
4733
4734                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4735                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4736                 check_added_monitors!(nodes[0], 1);
4737                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4738
4739                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4740                 check_added_monitors!(nodes[1], 1);
4741                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4742
4743                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4744                 check_added_monitors!(nodes[1], 1);
4745                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4746                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4747
4748                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4749                 check_added_monitors!(nodes[0], 1);
4750                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4751
4752                 let events = nodes[0].node.get_and_clear_pending_events();
4753                 assert_eq!(events.len(), 1);
4754                 match events[0] {
4755                         Event::PendingHTLCsForwardable { .. } => { },
4756                         _ => panic!("Unexpected event"),
4757                 };
4758                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4759                 nodes[0].node.process_pending_htlc_forwards();
4760
4761                 let events = nodes[0].node.get_and_clear_pending_events();
4762                 assert_eq!(events.len(), 1);
4763                 match events[0] {
4764                         Event::PaymentReceived { .. } => { },
4765                         _ => panic!("Unexpected event"),
4766                 };
4767
4768                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4769
4770                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4771                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4772                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4773         }
4774
4775         #[test]
4776         fn test_update_fee() {
4777                 let nodes = create_network(2);
4778                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4779                 let channel_id = chan.2;
4780
4781                 // A                                        B
4782                 // (1) update_fee/commitment_signed      ->
4783                 //                                       <- (2) revoke_and_ack
4784                 //                                       .- send (3) commitment_signed
4785                 // (4) update_fee/commitment_signed      ->
4786                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4787                 //                                       <- (3) commitment_signed delivered
4788                 // send (6) revoke_and_ack               -.
4789                 //                                       <- (5) deliver revoke_and_ack
4790                 // (6) deliver revoke_and_ack            ->
4791                 //                                       .- send (7) commitment_signed in response to (4)
4792                 //                                       <- (7) deliver commitment_signed
4793                 // revoke_and_ack                        ->
4794
4795                 // Create and deliver (1)...
4796                 let feerate = get_feerate!(nodes[0], channel_id);
4797                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4798                 check_added_monitors!(nodes[0], 1);
4799
4800                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4801                 assert_eq!(events_0.len(), 1);
4802                 let (update_msg, commitment_signed) = match events_0[0] {
4803                                 MessageSendEvent::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 } } => {
4804                                 (update_fee.as_ref(), commitment_signed)
4805                         },
4806                         _ => panic!("Unexpected event"),
4807                 };
4808                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4809
4810                 // Generate (2) and (3):
4811                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4812                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4813                 check_added_monitors!(nodes[1], 1);
4814
4815                 // Deliver (2):
4816                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4817                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4818                 check_added_monitors!(nodes[0], 1);
4819
4820                 // Create and deliver (4)...
4821                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4822                 check_added_monitors!(nodes[0], 1);
4823                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4824                 assert_eq!(events_0.len(), 1);
4825                 let (update_msg, commitment_signed) = match events_0[0] {
4826                                 MessageSendEvent::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 } } => {
4827                                 (update_fee.as_ref(), commitment_signed)
4828                         },
4829                         _ => panic!("Unexpected event"),
4830                 };
4831
4832                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4833                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4834                 check_added_monitors!(nodes[1], 1);
4835                 // ... creating (5)
4836                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4837                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4838
4839                 // Handle (3), creating (6):
4840                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4841                 check_added_monitors!(nodes[0], 1);
4842                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4843                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4844
4845                 // Deliver (5):
4846                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4847                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4848                 check_added_monitors!(nodes[0], 1);
4849
4850                 // Deliver (6), creating (7):
4851                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4852                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4853                 assert!(commitment_update.update_add_htlcs.is_empty());
4854                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4855                 assert!(commitment_update.update_fail_htlcs.is_empty());
4856                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4857                 assert!(commitment_update.update_fee.is_none());
4858                 check_added_monitors!(nodes[1], 1);
4859
4860                 // Deliver (7)
4861                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4862                 check_added_monitors!(nodes[0], 1);
4863                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4864                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4865
4866                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4867                 check_added_monitors!(nodes[1], 1);
4868                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4869
4870                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4871                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4872                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4873         }
4874
4875         #[test]
4876         fn pre_funding_lock_shutdown_test() {
4877                 // Test sending a shutdown prior to funding_locked after funding generation
4878                 let nodes = create_network(2);
4879                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4880                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4881                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4882                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4883
4884                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4885                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4886                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4887                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4888                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4889
4890                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4891                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4892                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4893                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4894                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4895                 assert!(node_0_none.is_none());
4896
4897                 assert!(nodes[0].node.list_channels().is_empty());
4898                 assert!(nodes[1].node.list_channels().is_empty());
4899         }
4900
4901         #[test]
4902         fn updates_shutdown_wait() {
4903                 // Test sending a shutdown with outstanding updates pending
4904                 let mut nodes = create_network(3);
4905                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4906                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4907                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4908                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4909
4910                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4911
4912                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4913                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4914                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4915                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4916                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4917
4918                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4919                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4920
4921                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4922                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4923                 else { panic!("New sends should fail!") };
4924                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4925                 else { panic!("New sends should fail!") };
4926
4927                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4928                 check_added_monitors!(nodes[2], 1);
4929                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4930                 assert!(updates.update_add_htlcs.is_empty());
4931                 assert!(updates.update_fail_htlcs.is_empty());
4932                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4933                 assert!(updates.update_fee.is_none());
4934                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4935                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4936                 check_added_monitors!(nodes[1], 1);
4937                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4938                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4939
4940                 assert!(updates_2.update_add_htlcs.is_empty());
4941                 assert!(updates_2.update_fail_htlcs.is_empty());
4942                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4943                 assert!(updates_2.update_fee.is_none());
4944                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4945                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4946                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4947
4948                 let events = nodes[0].node.get_and_clear_pending_events();
4949                 assert_eq!(events.len(), 1);
4950                 match events[0] {
4951                         Event::PaymentSent { ref payment_preimage } => {
4952                                 assert_eq!(our_payment_preimage, *payment_preimage);
4953                         },
4954                         _ => panic!("Unexpected event"),
4955                 }
4956
4957                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4958                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4959                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4960                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4961                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4962                 assert!(node_0_none.is_none());
4963
4964                 assert!(nodes[0].node.list_channels().is_empty());
4965
4966                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4967                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4968                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4969                 assert!(nodes[1].node.list_channels().is_empty());
4970                 assert!(nodes[2].node.list_channels().is_empty());
4971         }
4972
4973         #[test]
4974         fn htlc_fail_async_shutdown() {
4975                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4976                 let mut nodes = create_network(3);
4977                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4978                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4979
4980                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4981                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4982                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4983                 check_added_monitors!(nodes[0], 1);
4984                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4985                 assert_eq!(updates.update_add_htlcs.len(), 1);
4986                 assert!(updates.update_fulfill_htlcs.is_empty());
4987                 assert!(updates.update_fail_htlcs.is_empty());
4988                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4989                 assert!(updates.update_fee.is_none());
4990
4991                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4992                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4993                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4994                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4995
4996                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4997                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4998                 check_added_monitors!(nodes[1], 1);
4999                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5000                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5001
5002                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5003                 assert!(updates_2.update_add_htlcs.is_empty());
5004                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5005                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5006                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5007                 assert!(updates_2.update_fee.is_none());
5008
5009                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5010                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5011
5012                 let events = nodes[0].node.get_and_clear_pending_events();
5013                 assert_eq!(events.len(), 1);
5014                 match events[0] {
5015                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5016                                 assert_eq!(our_payment_hash, *payment_hash);
5017                                 assert!(!rejected_by_dest);
5018                         },
5019                         _ => panic!("Unexpected event"),
5020                 }
5021
5022                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5023                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5024                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5025                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5026                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5027                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5028                 assert!(node_0_none.is_none());
5029
5030                 assert!(nodes[0].node.list_channels().is_empty());
5031
5032                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5033                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5034                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5035                 assert!(nodes[1].node.list_channels().is_empty());
5036                 assert!(nodes[2].node.list_channels().is_empty());
5037         }
5038
5039         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5040                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5041                 // messages delivered prior to disconnect
5042                 let nodes = create_network(3);
5043                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5044                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5045
5046                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5047
5048                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5049                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5050                 if recv_count > 0 {
5051                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5052                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5053                         if recv_count > 1 {
5054                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5055                         }
5056                 }
5057
5058                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5059                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5060
5061                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5062                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5063                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5064                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5065
5066                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5067                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5068                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5069
5070                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5071                 let node_0_2nd_shutdown = if recv_count > 0 {
5072                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5073                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5074                         node_0_2nd_shutdown
5075                 } else {
5076                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5077                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5078                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5079                 };
5080                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5081
5082                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5083                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5084
5085                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5086                 check_added_monitors!(nodes[2], 1);
5087                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5088                 assert!(updates.update_add_htlcs.is_empty());
5089                 assert!(updates.update_fail_htlcs.is_empty());
5090                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5091                 assert!(updates.update_fee.is_none());
5092                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5093                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5094                 check_added_monitors!(nodes[1], 1);
5095                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5096                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5097
5098                 assert!(updates_2.update_add_htlcs.is_empty());
5099                 assert!(updates_2.update_fail_htlcs.is_empty());
5100                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5101                 assert!(updates_2.update_fee.is_none());
5102                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5103                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5104                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5105
5106                 let events = nodes[0].node.get_and_clear_pending_events();
5107                 assert_eq!(events.len(), 1);
5108                 match events[0] {
5109                         Event::PaymentSent { ref payment_preimage } => {
5110                                 assert_eq!(our_payment_preimage, *payment_preimage);
5111                         },
5112                         _ => panic!("Unexpected event"),
5113                 }
5114
5115                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5116                 if recv_count > 0 {
5117                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5118                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5119                         assert!(node_1_closing_signed.is_some());
5120                 }
5121
5122                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5123                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5124
5125                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5126                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5127                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5128                 if recv_count == 0 {
5129                         // If all closing_signeds weren't delivered we can just resume where we left off...
5130                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5131
5132                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5133                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5134                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5135
5136                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5137                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5138                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5139
5140                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5141                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5142
5143                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5144                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5145                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5146
5147                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5148                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5149                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5150                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5151                         assert!(node_0_none.is_none());
5152                 } else {
5153                         // If one node, however, received + responded with an identical closing_signed we end
5154                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5155                         // There isn't really anything better we can do simply, but in the future we might
5156                         // explore storing a set of recently-closed channels that got disconnected during
5157                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5158                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5159                         // transaction.
5160                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5161
5162                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5163                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5164                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5165                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5166                                 assert_eq!(*channel_id, chan_1.2);
5167                         } else { panic!("Needed SendErrorMessage close"); }
5168
5169                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5170                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5171                         // closing_signed so we do it ourselves
5172                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5173                         assert_eq!(events.len(), 1);
5174                         match events[0] {
5175                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5176                                         assert_eq!(msg.contents.flags & 2, 2);
5177                                 },
5178                                 _ => panic!("Unexpected event"),
5179                         }
5180                 }
5181
5182                 assert!(nodes[0].node.list_channels().is_empty());
5183
5184                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5185                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5186                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5187                 assert!(nodes[1].node.list_channels().is_empty());
5188                 assert!(nodes[2].node.list_channels().is_empty());
5189         }
5190
5191         #[test]
5192         fn test_shutdown_rebroadcast() {
5193                 do_test_shutdown_rebroadcast(0);
5194                 do_test_shutdown_rebroadcast(1);
5195                 do_test_shutdown_rebroadcast(2);
5196         }
5197
5198         #[test]
5199         fn fake_network_test() {
5200                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5201                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5202                 let nodes = create_network(4);
5203
5204                 // Create some initial channels
5205                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5206                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5207                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5208
5209                 // Rebalance the network a bit by relaying one payment through all the channels...
5210                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5211                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5212                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5213                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5214
5215                 // Send some more payments
5216                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5217                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5218                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5219
5220                 // Test failure packets
5221                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5222                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5223
5224                 // Add a new channel that skips 3
5225                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5226
5227                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5228                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5229                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5230                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5231                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5232                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5233                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5234
5235                 // Do some rebalance loop payments, simultaneously
5236                 let mut hops = Vec::with_capacity(3);
5237                 hops.push(RouteHop {
5238                         pubkey: nodes[2].node.get_our_node_id(),
5239                         short_channel_id: chan_2.0.contents.short_channel_id,
5240                         fee_msat: 0,
5241                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5242                 });
5243                 hops.push(RouteHop {
5244                         pubkey: nodes[3].node.get_our_node_id(),
5245                         short_channel_id: chan_3.0.contents.short_channel_id,
5246                         fee_msat: 0,
5247                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5248                 });
5249                 hops.push(RouteHop {
5250                         pubkey: nodes[1].node.get_our_node_id(),
5251                         short_channel_id: chan_4.0.contents.short_channel_id,
5252                         fee_msat: 1000000,
5253                         cltv_expiry_delta: TEST_FINAL_CLTV,
5254                 });
5255                 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;
5256                 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;
5257                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5258
5259                 let mut hops = Vec::with_capacity(3);
5260                 hops.push(RouteHop {
5261                         pubkey: nodes[3].node.get_our_node_id(),
5262                         short_channel_id: chan_4.0.contents.short_channel_id,
5263                         fee_msat: 0,
5264                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5265                 });
5266                 hops.push(RouteHop {
5267                         pubkey: nodes[2].node.get_our_node_id(),
5268                         short_channel_id: chan_3.0.contents.short_channel_id,
5269                         fee_msat: 0,
5270                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5271                 });
5272                 hops.push(RouteHop {
5273                         pubkey: nodes[1].node.get_our_node_id(),
5274                         short_channel_id: chan_2.0.contents.short_channel_id,
5275                         fee_msat: 1000000,
5276                         cltv_expiry_delta: TEST_FINAL_CLTV,
5277                 });
5278                 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;
5279                 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;
5280                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5281
5282                 // Claim the rebalances...
5283                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5284                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5285
5286                 // Add a duplicate new channel from 2 to 4
5287                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5288
5289                 // Send some payments across both channels
5290                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5291                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5292                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5293
5294                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5295
5296                 //TODO: Test that routes work again here as we've been notified that the channel is full
5297
5298                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5299                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5300                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5301
5302                 // Close down the channels...
5303                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5304                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5305                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5306                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5307                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5308         }
5309
5310         #[test]
5311         fn duplicate_htlc_test() {
5312                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5313                 // claiming/failing them are all separate and don't effect each other
5314                 let mut nodes = create_network(6);
5315
5316                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5317                 create_announced_chan_between_nodes(&nodes, 0, 3);
5318                 create_announced_chan_between_nodes(&nodes, 1, 3);
5319                 create_announced_chan_between_nodes(&nodes, 2, 3);
5320                 create_announced_chan_between_nodes(&nodes, 3, 4);
5321                 create_announced_chan_between_nodes(&nodes, 3, 5);
5322
5323                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5324
5325                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5326                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5327
5328                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5329                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5330
5331                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5332                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5333                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5334         }
5335
5336         #[derive(PartialEq)]
5337         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5338         /// Tests that the given node has broadcast transactions for the given Channel
5339         ///
5340         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5341         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5342         /// broadcast and the revoked outputs were claimed.
5343         ///
5344         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5345         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5346         ///
5347         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5348         /// also fail.
5349         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5350                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5351                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5352
5353                 let mut res = Vec::with_capacity(2);
5354                 node_txn.retain(|tx| {
5355                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5356                                 check_spends!(tx, chan.3.clone());
5357                                 if commitment_tx.is_none() {
5358                                         res.push(tx.clone());
5359                                 }
5360                                 false
5361                         } else { true }
5362                 });
5363                 if let Some(explicit_tx) = commitment_tx {
5364                         res.push(explicit_tx.clone());
5365                 }
5366
5367                 assert_eq!(res.len(), 1);
5368
5369                 if has_htlc_tx != HTLCType::NONE {
5370                         node_txn.retain(|tx| {
5371                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5372                                         check_spends!(tx, res[0].clone());
5373                                         if has_htlc_tx == HTLCType::TIMEOUT {
5374                                                 assert!(tx.lock_time != 0);
5375                                         } else {
5376                                                 assert!(tx.lock_time == 0);
5377                                         }
5378                                         res.push(tx.clone());
5379                                         false
5380                                 } else { true }
5381                         });
5382                         assert!(res.len() == 2 || res.len() == 3);
5383                         if res.len() == 3 {
5384                                 assert_eq!(res[1], res[2]);
5385                         }
5386                 }
5387
5388                 assert!(node_txn.is_empty());
5389                 res
5390         }
5391
5392         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5393         /// HTLC transaction.
5394         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5395                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5396                 assert_eq!(node_txn.len(), 1);
5397                 node_txn.retain(|tx| {
5398                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5399                                 check_spends!(tx, revoked_tx.clone());
5400                                 false
5401                         } else { true }
5402                 });
5403                 assert!(node_txn.is_empty());
5404         }
5405
5406         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5407                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5408
5409                 assert!(node_txn.len() >= 1);
5410                 assert_eq!(node_txn[0].input.len(), 1);
5411                 let mut found_prev = false;
5412
5413                 for tx in prev_txn {
5414                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5415                                 check_spends!(node_txn[0], tx.clone());
5416                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5417                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5418
5419                                 found_prev = true;
5420                                 break;
5421                         }
5422                 }
5423                 assert!(found_prev);
5424
5425                 let mut res = Vec::new();
5426                 mem::swap(&mut *node_txn, &mut res);
5427                 res
5428         }
5429
5430         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5431                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5432                 assert_eq!(events_1.len(), 1);
5433                 let as_update = match events_1[0] {
5434                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5435                                 msg.clone()
5436                         },
5437                         _ => panic!("Unexpected event"),
5438                 };
5439
5440                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5441                 assert_eq!(events_2.len(), 1);
5442                 let bs_update = match events_2[0] {
5443                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5444                                 msg.clone()
5445                         },
5446                         _ => panic!("Unexpected event"),
5447                 };
5448
5449                 for node in nodes {
5450                         node.router.handle_channel_update(&as_update).unwrap();
5451                         node.router.handle_channel_update(&bs_update).unwrap();
5452                 }
5453         }
5454
5455         macro_rules! expect_pending_htlcs_forwardable {
5456                 ($node: expr) => {{
5457                         let events = $node.node.get_and_clear_pending_events();
5458                         assert_eq!(events.len(), 1);
5459                         match events[0] {
5460                                 Event::PendingHTLCsForwardable { .. } => { },
5461                                 _ => panic!("Unexpected event"),
5462                         };
5463                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5464                         $node.node.process_pending_htlc_forwards();
5465                 }}
5466         }
5467
5468         fn do_channel_reserve_test(test_recv: bool) {
5469                 use util::rng;
5470                 use std::sync::atomic::Ordering;
5471                 use ln::msgs::HandleError;
5472
5473                 macro_rules! get_channel_value_stat {
5474                         ($node: expr, $channel_id: expr) => {{
5475                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5476                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5477                                 chan.get_value_stat()
5478                         }}
5479                 }
5480
5481                 let mut nodes = create_network(3);
5482                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5483                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5484
5485                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5486                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5487
5488                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5489                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5490
5491                 macro_rules! get_route_and_payment_hash {
5492                         ($recv_value: expr) => {{
5493                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5494                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5495                                 (route, payment_hash, payment_preimage)
5496                         }}
5497                 };
5498
5499                 macro_rules! expect_forward {
5500                         ($node: expr) => {{
5501                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5502                                 assert_eq!(events.len(), 1);
5503                                 check_added_monitors!($node, 1);
5504                                 let payment_event = SendEvent::from_event(events.remove(0));
5505                                 payment_event
5506                         }}
5507                 }
5508
5509                 macro_rules! expect_payment_received {
5510                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5511                                 let events = $node.node.get_and_clear_pending_events();
5512                                 assert_eq!(events.len(), 1);
5513                                 match events[0] {
5514                                         Event::PaymentReceived { ref payment_hash, amt } => {
5515                                                 assert_eq!($expected_payment_hash, *payment_hash);
5516                                                 assert_eq!($expected_recv_value, amt);
5517                                         },
5518                                         _ => panic!("Unexpected event"),
5519                                 }
5520                         }
5521                 };
5522
5523                 let feemsat = 239; // somehow we know?
5524                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5525
5526                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5527
5528                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5529                 {
5530                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5531                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5532                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5533                         match err {
5534                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5535                                 _ => panic!("Unknown error variants"),
5536                         }
5537                 }
5538
5539                 let mut htlc_id = 0;
5540                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5541                 // nodes[0]'s wealth
5542                 loop {
5543                         let amt_msat = recv_value_0 + total_fee_msat;
5544                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5545                                 break;
5546                         }
5547                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5548                         htlc_id += 1;
5549
5550                         let (stat01_, stat11_, stat12_, stat22_) = (
5551                                 get_channel_value_stat!(nodes[0], chan_1.2),
5552                                 get_channel_value_stat!(nodes[1], chan_1.2),
5553                                 get_channel_value_stat!(nodes[1], chan_2.2),
5554                                 get_channel_value_stat!(nodes[2], chan_2.2),
5555                         );
5556
5557                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5558                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5559                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5560                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5561                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5562                 }
5563
5564                 {
5565                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5566                         // attempt to get channel_reserve violation
5567                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5568                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5569                         match err {
5570                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5571                                 _ => panic!("Unknown error variants"),
5572                         }
5573                 }
5574
5575                 // adding pending output
5576                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5577                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5578
5579                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5580                 let payment_event_1 = {
5581                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5582                         check_added_monitors!(nodes[0], 1);
5583
5584                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5585                         assert_eq!(events.len(), 1);
5586                         SendEvent::from_event(events.remove(0))
5587                 };
5588                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5589
5590                 // channel reserve test with htlc pending output > 0
5591                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5592                 {
5593                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5594                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5595                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5596                                 _ => panic!("Unknown error variants"),
5597                         }
5598                 }
5599
5600                 {
5601                         // test channel_reserve test on nodes[1] side
5602                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5603
5604                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5605                         let secp_ctx = Secp256k1::new();
5606                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5607                                 let mut session_key = [0; 32];
5608                                 rng::fill_bytes(&mut session_key);
5609                                 session_key
5610                         }).expect("RNG is bad!");
5611
5612                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5613                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5614                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5615                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5616                         let msg = msgs::UpdateAddHTLC {
5617                                 channel_id: chan_1.2,
5618                                 htlc_id,
5619                                 amount_msat: htlc_msat,
5620                                 payment_hash: our_payment_hash,
5621                                 cltv_expiry: htlc_cltv,
5622                                 onion_routing_packet: onion_packet,
5623                         };
5624
5625                         if test_recv {
5626                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5627                                 match err {
5628                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5629                                 }
5630                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5631                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5632                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5633                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5634                                 assert_eq!(channel_close_broadcast.len(), 1);
5635                                 match channel_close_broadcast[0] {
5636                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5637                                                 assert_eq!(msg.contents.flags & 2, 2);
5638                                         },
5639                                         _ => panic!("Unexpected event"),
5640                                 }
5641                                 return;
5642                         }
5643                 }
5644
5645                 // split the rest to test holding cell
5646                 let recv_value_21 = recv_value_2/2;
5647                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5648                 {
5649                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5650                         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);
5651                 }
5652
5653                 // now see if they go through on both sides
5654                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5655                 // but this will stuck in the holding cell
5656                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5657                 check_added_monitors!(nodes[0], 0);
5658                 let events = nodes[0].node.get_and_clear_pending_events();
5659                 assert_eq!(events.len(), 0);
5660
5661                 // test with outbound holding cell amount > 0
5662                 {
5663                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5664                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5665                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5666                                 _ => panic!("Unknown error variants"),
5667                         }
5668                 }
5669
5670                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5671                 // this will also stuck in the holding cell
5672                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5673                 check_added_monitors!(nodes[0], 0);
5674                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5675                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5676
5677                 // flush the pending htlc
5678                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5679                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5680                 check_added_monitors!(nodes[1], 1);
5681
5682                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5683                 check_added_monitors!(nodes[0], 1);
5684                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5685
5686                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5687                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5688                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5689                 check_added_monitors!(nodes[0], 1);
5690
5691                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5692                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5693                 check_added_monitors!(nodes[1], 1);
5694
5695                 expect_pending_htlcs_forwardable!(nodes[1]);
5696
5697                 let ref payment_event_11 = expect_forward!(nodes[1]);
5698                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5699                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5700
5701                 expect_pending_htlcs_forwardable!(nodes[2]);
5702                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5703
5704                 // flush the htlcs in the holding cell
5705                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5706                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5707                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5708                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5709                 expect_pending_htlcs_forwardable!(nodes[1]);
5710
5711                 let ref payment_event_3 = expect_forward!(nodes[1]);
5712                 assert_eq!(payment_event_3.msgs.len(), 2);
5713                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5714                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5715
5716                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5717                 expect_pending_htlcs_forwardable!(nodes[2]);
5718
5719                 let events = nodes[2].node.get_and_clear_pending_events();
5720                 assert_eq!(events.len(), 2);
5721                 match events[0] {
5722                         Event::PaymentReceived { ref payment_hash, amt } => {
5723                                 assert_eq!(our_payment_hash_21, *payment_hash);
5724                                 assert_eq!(recv_value_21, amt);
5725                         },
5726                         _ => panic!("Unexpected event"),
5727                 }
5728                 match events[1] {
5729                         Event::PaymentReceived { ref payment_hash, amt } => {
5730                                 assert_eq!(our_payment_hash_22, *payment_hash);
5731                                 assert_eq!(recv_value_22, amt);
5732                         },
5733                         _ => panic!("Unexpected event"),
5734                 }
5735
5736                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5737                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5738                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5739
5740                 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);
5741                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5742                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5743                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5744
5745                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5746                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5747         }
5748
5749         #[test]
5750         fn channel_reserve_test() {
5751                 do_channel_reserve_test(false);
5752                 do_channel_reserve_test(true);
5753         }
5754
5755         #[test]
5756         fn channel_monitor_network_test() {
5757                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5758                 // tests that ChannelMonitor is able to recover from various states.
5759                 let nodes = create_network(5);
5760
5761                 // Create some initial channels
5762                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5763                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5764                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5765                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5766
5767                 // Rebalance the network a bit by relaying one payment through all the channels...
5768                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5769                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5770                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5771                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5772
5773                 // Simple case with no pending HTLCs:
5774                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5775                 {
5776                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5777                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5778                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5779                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5780                 }
5781                 get_announce_close_broadcast_events(&nodes, 0, 1);
5782                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5783                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5784
5785                 // One pending HTLC is discarded by the force-close:
5786                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5787
5788                 // Simple case of one pending HTLC to HTLC-Timeout
5789                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5790                 {
5791                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5792                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5793                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5794                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5795                 }
5796                 get_announce_close_broadcast_events(&nodes, 1, 2);
5797                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5798                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5799
5800                 macro_rules! claim_funds {
5801                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5802                                 {
5803                                         assert!($node.node.claim_funds($preimage));
5804                                         check_added_monitors!($node, 1);
5805
5806                                         let events = $node.node.get_and_clear_pending_msg_events();
5807                                         assert_eq!(events.len(), 1);
5808                                         match events[0] {
5809                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5810                                                         assert!(update_add_htlcs.is_empty());
5811                                                         assert!(update_fail_htlcs.is_empty());
5812                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5813                                                 },
5814                                                 _ => panic!("Unexpected event"),
5815                                         };
5816                                 }
5817                         }
5818                 }
5819
5820                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5821                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5822                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5823                 {
5824                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5825
5826                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5827                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5828
5829                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5830                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5831
5832                         check_preimage_claim(&nodes[3], &node_txn);
5833                 }
5834                 get_announce_close_broadcast_events(&nodes, 2, 3);
5835                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5836                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5837
5838                 { // Cheat and reset nodes[4]'s height to 1
5839                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5840                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5841                 }
5842
5843                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5844                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5845                 // One pending HTLC to time out:
5846                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5847                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5848                 // buffer space).
5849
5850                 {
5851                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5852                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5853                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5854                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5856                         }
5857
5858                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5859
5860                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5861                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5862
5863                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5864                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5865                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5866                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5867                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5868                         }
5869
5870                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5871
5872                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5873                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5874
5875                         check_preimage_claim(&nodes[4], &node_txn);
5876                 }
5877                 get_announce_close_broadcast_events(&nodes, 3, 4);
5878                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5879                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5880         }
5881
5882         #[test]
5883         fn test_justice_tx() {
5884                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5885
5886                 let nodes = create_network(2);
5887                 // Create some new channels:
5888                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5889
5890                 // A pending HTLC which will be revoked:
5891                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5892                 // Get the will-be-revoked local txn from nodes[0]
5893                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5894                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5895                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5896                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5897                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5898                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5899                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5900                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5901                 // Revoke the old state
5902                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5903
5904                 {
5905                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5906                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5907                         {
5908                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5909                                 assert_eq!(node_txn.len(), 3);
5910                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5911                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5912
5913                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5914                                 node_txn.swap_remove(0);
5915                         }
5916                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5917
5918                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5919                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5920                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5921                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5922                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5923                 }
5924                 get_announce_close_broadcast_events(&nodes, 0, 1);
5925
5926                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5927                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5928
5929                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5930                 // Create some new channels:
5931                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5932
5933                 // A pending HTLC which will be revoked:
5934                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5935                 // Get the will-be-revoked local txn from B
5936                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5937                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5938                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5939                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5940                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5941                 // Revoke the old state
5942                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5943                 {
5944                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5945                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5946                         {
5947                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5948                                 assert_eq!(node_txn.len(), 3);
5949                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5950                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5951
5952                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5953                                 node_txn.swap_remove(0);
5954                         }
5955                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5956
5957                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5958                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5959                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5960                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5961                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5962                 }
5963                 get_announce_close_broadcast_events(&nodes, 0, 1);
5964                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5965                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5966         }
5967
5968         #[test]
5969         fn revoked_output_claim() {
5970                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5971                 // transaction is broadcast by its counterparty
5972                 let nodes = create_network(2);
5973                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5974                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5975                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5976                 assert_eq!(revoked_local_txn.len(), 1);
5977                 // Only output is the full channel value back to nodes[0]:
5978                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5979                 // Send a payment through, updating everyone's latest commitment txn
5980                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5981
5982                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5983                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5984                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5985                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5986                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5987
5988                 assert_eq!(node_txn[0], node_txn[2]);
5989
5990                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5991                 check_spends!(node_txn[1], chan_1.3.clone());
5992
5993                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
5994                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5995                 get_announce_close_broadcast_events(&nodes, 0, 1);
5996         }
5997
5998         #[test]
5999         fn claim_htlc_outputs_shared_tx() {
6000                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6001                 let nodes = create_network(2);
6002
6003                 // Create some new channel:
6004                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6005
6006                 // Rebalance the network to generate htlc in the two directions
6007                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6008                 // 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
6009                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6010                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6011
6012                 // Get the will-be-revoked local txn from node[0]
6013                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6014                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6015                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6016                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6017                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6018                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6019                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6020                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6021
6022                 //Revoke the old state
6023                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6024
6025                 {
6026                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6027                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6028                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6029
6030                         let events = nodes[1].node.get_and_clear_pending_events();
6031                         assert_eq!(events.len(), 1);
6032                         match events[0] {
6033                                 Event::PaymentFailed { payment_hash, .. } => {
6034                                         assert_eq!(payment_hash, payment_hash_2);
6035                                 },
6036                                 _ => panic!("Unexpected event"),
6037                         }
6038
6039                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6040                         assert_eq!(node_txn.len(), 4);
6041
6042                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6043                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6044
6045                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6046
6047                         let mut witness_lens = BTreeSet::new();
6048                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6049                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6050                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6051                         assert_eq!(witness_lens.len(), 3);
6052                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6053                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6054                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6055
6056                         // Next nodes[1] broadcasts its current local tx state:
6057                         assert_eq!(node_txn[1].input.len(), 1);
6058                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6059
6060                         assert_eq!(node_txn[2].input.len(), 1);
6061                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6062                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6063                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6064                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6065                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6066                 }
6067                 get_announce_close_broadcast_events(&nodes, 0, 1);
6068                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6069                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6070         }
6071
6072         #[test]
6073         fn claim_htlc_outputs_single_tx() {
6074                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6075                 let nodes = create_network(2);
6076
6077                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6078
6079                 // Rebalance the network to generate htlc in the two directions
6080                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6081                 // 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
6082                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6083                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6084                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6085
6086                 // Get the will-be-revoked local txn from node[0]
6087                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6088
6089                 //Revoke the old state
6090                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6091
6092                 {
6093                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6094                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6095                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6096
6097                         let events = nodes[1].node.get_and_clear_pending_events();
6098                         assert_eq!(events.len(), 1);
6099                         match events[0] {
6100                                 Event::PaymentFailed { payment_hash, .. } => {
6101                                         assert_eq!(payment_hash, payment_hash_2);
6102                                 },
6103                                 _ => panic!("Unexpected event"),
6104                         }
6105
6106                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6107                         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)
6108
6109                         assert_eq!(node_txn[0], node_txn[7]);
6110                         assert_eq!(node_txn[1], node_txn[8]);
6111                         assert_eq!(node_txn[2], node_txn[9]);
6112                         assert_eq!(node_txn[3], node_txn[10]);
6113                         assert_eq!(node_txn[4], node_txn[11]);
6114                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6115                         assert_eq!(node_txn[4], node_txn[6]);
6116
6117                         assert_eq!(node_txn[0].input.len(), 1);
6118                         assert_eq!(node_txn[1].input.len(), 1);
6119                         assert_eq!(node_txn[2].input.len(), 1);
6120
6121                         let mut revoked_tx_map = HashMap::new();
6122                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6123                         node_txn[0].verify(&revoked_tx_map).unwrap();
6124                         node_txn[1].verify(&revoked_tx_map).unwrap();
6125                         node_txn[2].verify(&revoked_tx_map).unwrap();
6126
6127                         let mut witness_lens = BTreeSet::new();
6128                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6129                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6130                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6131                         assert_eq!(witness_lens.len(), 3);
6132                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6133                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6134                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6135
6136                         assert_eq!(node_txn[3].input.len(), 1);
6137                         check_spends!(node_txn[3], chan_1.3.clone());
6138
6139                         assert_eq!(node_txn[4].input.len(), 1);
6140                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6141                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6142                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6143                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6144                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6145                 }
6146                 get_announce_close_broadcast_events(&nodes, 0, 1);
6147                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6148                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6149         }
6150
6151         #[test]
6152         fn test_htlc_on_chain_success() {
6153                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6154                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6155                 // broadcasting the right event to other nodes in payment path.
6156                 // A --------------------> B ----------------------> C (preimage)
6157                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6158                 // commitment transaction was broadcast.
6159                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6160                 // towards B.
6161                 // B should be able to claim via preimage if A then broadcasts its local tx.
6162                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6163                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6164                 // PaymentSent event).
6165
6166                 let nodes = create_network(3);
6167
6168                 // Create some initial channels
6169                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6170                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6171
6172                 // Rebalance the network a bit by relaying one payment through all the channels...
6173                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6174                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6175
6176                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6177                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6178
6179                 // Broadcast legit commitment tx from C on B's chain
6180                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6181                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6182                 assert_eq!(commitment_tx.len(), 1);
6183                 check_spends!(commitment_tx[0], chan_2.3.clone());
6184                 nodes[2].node.claim_funds(our_payment_preimage);
6185                 check_added_monitors!(nodes[2], 1);
6186                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6187                 assert!(updates.update_add_htlcs.is_empty());
6188                 assert!(updates.update_fail_htlcs.is_empty());
6189                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6190                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6191
6192                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6193                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6194                 assert_eq!(events.len(), 1);
6195                 match events[0] {
6196                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6197                         _ => panic!("Unexpected event"),
6198                 }
6199                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6200                 assert_eq!(node_txn.len(), 3);
6201                 assert_eq!(node_txn[1], commitment_tx[0]);
6202                 assert_eq!(node_txn[0], node_txn[2]);
6203                 check_spends!(node_txn[0], commitment_tx[0].clone());
6204                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6205                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6206                 assert_eq!(node_txn[0].lock_time, 0);
6207
6208                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6209                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6210                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6211                 {
6212                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6213                         assert_eq!(added_monitors.len(), 1);
6214                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6215                         added_monitors.clear();
6216                 }
6217                 assert_eq!(events.len(), 2);
6218                 match events[0] {
6219                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6220                         _ => panic!("Unexpected event"),
6221                 }
6222                 match events[1] {
6223                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6224                                 assert!(update_add_htlcs.is_empty());
6225                                 assert!(update_fail_htlcs.is_empty());
6226                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6227                                 assert!(update_fail_malformed_htlcs.is_empty());
6228                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6229                         },
6230                         _ => panic!("Unexpected event"),
6231                 };
6232                 {
6233                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6234                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6235                         // timeout-claim of the output that nodes[2] just claimed via success.
6236                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 (timeout tx) * 2 (block-rescan)
6237                         assert_eq!(node_txn.len(), 4);
6238                         assert_eq!(node_txn[0], node_txn[3]);
6239                         check_spends!(node_txn[0], commitment_tx[0].clone());
6240                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6241                         assert_ne!(node_txn[0].lock_time, 0);
6242                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6243                         check_spends!(node_txn[1], chan_2.3.clone());
6244                         check_spends!(node_txn[2], node_txn[1].clone());
6245                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6246                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6247                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6248                         assert_ne!(node_txn[2].lock_time, 0);
6249                         node_txn.clear();
6250                 }
6251
6252                 // Broadcast legit commitment tx from A on B's chain
6253                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6254                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6255                 check_spends!(commitment_tx[0], chan_1.3.clone());
6256                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6257                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6258                 assert_eq!(events.len(), 1);
6259                 match events[0] {
6260                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6261                         _ => panic!("Unexpected event"),
6262                 }
6263                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6264                 assert_eq!(node_txn.len(), 3);
6265                 assert_eq!(node_txn[0], node_txn[2]);
6266                 check_spends!(node_txn[0], commitment_tx[0].clone());
6267                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6268                 assert_eq!(node_txn[0].lock_time, 0);
6269                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6270                 check_spends!(node_txn[1], chan_1.3.clone());
6271                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6272                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6273                 // we already checked the same situation with A.
6274
6275                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6276                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6277                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6278                 assert_eq!(events.len(), 1);
6279                 match events[0] {
6280                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6281                         _ => panic!("Unexpected event"),
6282                 }
6283                 let events = nodes[0].node.get_and_clear_pending_events();
6284                 assert_eq!(events.len(), 1);
6285                 match events[0] {
6286                         Event::PaymentSent { payment_preimage } => {
6287                                 assert_eq!(payment_preimage, our_payment_preimage);
6288                         },
6289                         _ => panic!("Unexpected event"),
6290                 }
6291                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 (HTLC-Timeout tx) * 2 (block-rescan)
6292                 assert_eq!(node_txn.len(), 4);
6293                 assert_eq!(node_txn[0], node_txn[3]);
6294                 check_spends!(node_txn[0], commitment_tx[0].clone());
6295                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6296                 assert_ne!(node_txn[0].lock_time, 0);
6297                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6298                 check_spends!(node_txn[1], chan_1.3.clone());
6299                 check_spends!(node_txn[2], node_txn[1].clone());
6300                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6301                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6302                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6303                 assert_ne!(node_txn[2].lock_time, 0);
6304         }
6305
6306         #[test]
6307         fn test_htlc_on_chain_timeout() {
6308                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6309                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6310                 // broadcasting the right event to other nodes in payment path.
6311                 // A ------------------> B ----------------------> C (timeout)
6312                 //    B's commitment tx                 C's commitment tx
6313                 //            \                                  \
6314                 //         B's HTLC timeout tx               B's timeout tx
6315
6316                 let nodes = create_network(3);
6317
6318                 // Create some intial channels
6319                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6320                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6321
6322                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6323                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6324                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6325
6326                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6327                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6328
6329                 // Brodacast legit commitment tx from C on B's chain
6330                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6331                 check_spends!(commitment_tx[0], chan_2.3.clone());
6332                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6333                 {
6334                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6335                         assert_eq!(added_monitors.len(), 1);
6336                         added_monitors.clear();
6337                 }
6338                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6339                 assert_eq!(events.len(), 1);
6340                 match events[0] {
6341                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6342                                 assert!(update_add_htlcs.is_empty());
6343                                 assert!(!update_fail_htlcs.is_empty());
6344                                 assert!(update_fulfill_htlcs.is_empty());
6345                                 assert!(update_fail_malformed_htlcs.is_empty());
6346                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6347                         },
6348                         _ => panic!("Unexpected event"),
6349                 };
6350                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6351                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6352                 assert_eq!(events.len(), 1);
6353                 match events[0] {
6354                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6355                         _ => panic!("Unexpected event"),
6356                 }
6357                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6358                 assert_eq!(node_txn.len(), 1);
6359                 check_spends!(node_txn[0], chan_2.3.clone());
6360                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6361
6362                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6363                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6364                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6365                 let timeout_tx;
6366                 {
6367                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6368                         assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
6369                         assert_eq!(node_txn[0], node_txn[5]);
6370                         assert_eq!(node_txn[1], node_txn[6]);
6371                         assert_eq!(node_txn[2], node_txn[7]);
6372                         check_spends!(node_txn[0], commitment_tx[0].clone());
6373                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6374                         check_spends!(node_txn[1], chan_2.3.clone());
6375                         check_spends!(node_txn[2], node_txn[1].clone());
6376                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6377                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6378                         check_spends!(node_txn[3], chan_2.3.clone());
6379                         check_spends!(node_txn[4], node_txn[3].clone());
6380                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6381                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6382                         timeout_tx = node_txn[0].clone();
6383                         node_txn.clear();
6384                 }
6385
6386                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6387                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6388                 check_added_monitors!(nodes[1], 1);
6389                 assert_eq!(events.len(), 2);
6390                 match events[0] {
6391                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6392                         _ => panic!("Unexpected event"),
6393                 }
6394                 match events[1] {
6395                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6396                                 assert!(update_add_htlcs.is_empty());
6397                                 assert!(!update_fail_htlcs.is_empty());
6398                                 assert!(update_fulfill_htlcs.is_empty());
6399                                 assert!(update_fail_malformed_htlcs.is_empty());
6400                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6401                         },
6402                         _ => panic!("Unexpected event"),
6403                 };
6404                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
6405                 assert_eq!(node_txn.len(), 0);
6406
6407                 // Broadcast legit commitment tx from B on A's chain
6408                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6409                 check_spends!(commitment_tx[0], chan_1.3.clone());
6410
6411                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6412                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6413                 assert_eq!(events.len(), 1);
6414                 match events[0] {
6415                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6416                         _ => panic!("Unexpected event"),
6417                 }
6418                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
6419                 assert_eq!(node_txn.len(), 4);
6420                 assert_eq!(node_txn[0], node_txn[3]);
6421                 check_spends!(node_txn[0], commitment_tx[0].clone());
6422                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6423                 check_spends!(node_txn[1], chan_1.3.clone());
6424                 check_spends!(node_txn[2], node_txn[1].clone());
6425                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6426                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6427         }
6428
6429         #[test]
6430         fn test_simple_commitment_revoked_fail_backward() {
6431                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6432                 // and fail backward accordingly.
6433
6434                 let nodes = create_network(3);
6435
6436                 // Create some initial channels
6437                 create_announced_chan_between_nodes(&nodes, 0, 1);
6438                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6439
6440                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6441                 // Get the will-be-revoked local txn from nodes[2]
6442                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6443                 // Revoke the old state
6444                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6445
6446                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6447
6448                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6449                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6450                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6451                 check_added_monitors!(nodes[1], 1);
6452                 assert_eq!(events.len(), 2);
6453                 match events[0] {
6454                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6455                         _ => panic!("Unexpected event"),
6456                 }
6457                 match events[1] {
6458                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
6459                                 assert!(update_add_htlcs.is_empty());
6460                                 assert_eq!(update_fail_htlcs.len(), 1);
6461                                 assert!(update_fulfill_htlcs.is_empty());
6462                                 assert!(update_fail_malformed_htlcs.is_empty());
6463                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6464
6465                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6466                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6467
6468                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6469                                 assert_eq!(events.len(), 1);
6470                                 match events[0] {
6471                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6472                                         _ => panic!("Unexpected event"),
6473                                 }
6474                                 let events = nodes[0].node.get_and_clear_pending_events();
6475                                 assert_eq!(events.len(), 1);
6476                                 match events[0] {
6477                                         Event::PaymentFailed { .. } => {},
6478                                         _ => panic!("Unexpected event"),
6479                                 }
6480                         },
6481                         _ => panic!("Unexpected event"),
6482                 }
6483         }
6484
6485         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6486                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6487                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6488                 // commitment transaction anymore.
6489                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6490                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6491                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6492                 // technically disallowed and we should probably handle it reasonably.
6493                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6494                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6495                 // transactions:
6496                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6497                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6498                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6499                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6500                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6501                 let mut nodes = create_network(3);
6502
6503                 // Create some initial channels
6504                 create_announced_chan_between_nodes(&nodes, 0, 1);
6505                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6506
6507                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6508                 // Get the will-be-revoked local txn from nodes[2]
6509                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6510                 // Revoke the old state
6511                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6512
6513                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6514                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6515                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6516
6517                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6518                 check_added_monitors!(nodes[2], 1);
6519                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6520                 assert!(updates.update_add_htlcs.is_empty());
6521                 assert!(updates.update_fulfill_htlcs.is_empty());
6522                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6523                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6524                 assert!(updates.update_fee.is_none());
6525                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6526                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6527                 // Drop the last RAA from 3 -> 2
6528
6529                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6530                 check_added_monitors!(nodes[2], 1);
6531                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6532                 assert!(updates.update_add_htlcs.is_empty());
6533                 assert!(updates.update_fulfill_htlcs.is_empty());
6534                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6535                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6536                 assert!(updates.update_fee.is_none());
6537                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6538                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6539                 check_added_monitors!(nodes[1], 1);
6540                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6541                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6542                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6543                 check_added_monitors!(nodes[2], 1);
6544
6545                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6546                 check_added_monitors!(nodes[2], 1);
6547                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6548                 assert!(updates.update_add_htlcs.is_empty());
6549                 assert!(updates.update_fulfill_htlcs.is_empty());
6550                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6551                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6552                 assert!(updates.update_fee.is_none());
6553                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6554                 // At this point first_payment_hash has dropped out of the latest two commitment
6555                 // transactions that nodes[1] is tracking...
6556                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6557                 check_added_monitors!(nodes[1], 1);
6558                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6559                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6560                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6561                 check_added_monitors!(nodes[2], 1);
6562
6563                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6564                 // on nodes[2]'s RAA.
6565                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6566                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6567                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6568                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6569                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6570                 check_added_monitors!(nodes[1], 0);
6571
6572                 if deliver_bs_raa {
6573                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6574                         // One monitor for the new revocation preimage, one as we generate a commitment for
6575                         // nodes[0] to fail first_payment_hash backwards.
6576                         check_added_monitors!(nodes[1], 2);
6577                 }
6578
6579                 let mut failed_htlcs = HashSet::new();
6580                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6581
6582                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6583                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6584
6585                 let events = nodes[1].node.get_and_clear_pending_events();
6586                 assert_eq!(events.len(), 1);
6587                 match events[0] {
6588                         Event::PaymentFailed { ref payment_hash, .. } => {
6589                                 assert_eq!(*payment_hash, fourth_payment_hash);
6590                         },
6591                         _ => panic!("Unexpected event"),
6592                 }
6593
6594                 if !deliver_bs_raa {
6595                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6596                         check_added_monitors!(nodes[1], 1);
6597                 }
6598
6599                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6600                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6601                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6602                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6603                         _ => panic!("Unexpected event"),
6604                 }
6605                 if deliver_bs_raa {
6606                         match events[0] {
6607                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
6608                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6609                                         assert_eq!(update_add_htlcs.len(), 1);
6610                                         assert!(update_fulfill_htlcs.is_empty());
6611                                         assert!(update_fail_htlcs.is_empty());
6612                                         assert!(update_fail_malformed_htlcs.is_empty());
6613                                 },
6614                                 _ => panic!("Unexpected event"),
6615                         }
6616                 }
6617                 // Due to the way backwards-failing occurs we do the updates in two steps.
6618                 let updates = match events[1] {
6619                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
6620                                 assert!(update_add_htlcs.is_empty());
6621                                 assert_eq!(update_fail_htlcs.len(), 1);
6622                                 assert!(update_fulfill_htlcs.is_empty());
6623                                 assert!(update_fail_malformed_htlcs.is_empty());
6624                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6625
6626                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6627                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6628                                 check_added_monitors!(nodes[0], 1);
6629                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6630                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6631                                 check_added_monitors!(nodes[1], 1);
6632                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6633                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6634                                 check_added_monitors!(nodes[1], 1);
6635                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6636                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6637                                 check_added_monitors!(nodes[0], 1);
6638
6639                                 if !deliver_bs_raa {
6640                                         // If we delievered B's RAA we got an unknown preimage error, not something
6641                                         // that we should update our routing table for.
6642                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6643                                         assert_eq!(events.len(), 1);
6644                                         match events[0] {
6645                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6646                                                 _ => panic!("Unexpected event"),
6647                                         }
6648                                 }
6649                                 let events = nodes[0].node.get_and_clear_pending_events();
6650                                 assert_eq!(events.len(), 1);
6651                                 match events[0] {
6652                                         Event::PaymentFailed { ref payment_hash, .. } => {
6653                                                 assert!(failed_htlcs.insert(payment_hash.0));
6654                                         },
6655                                         _ => panic!("Unexpected event"),
6656                                 }
6657
6658                                 bs_second_update
6659                         },
6660                         _ => panic!("Unexpected event"),
6661                 };
6662
6663                 assert!(updates.update_add_htlcs.is_empty());
6664                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6665                 assert!(updates.update_fulfill_htlcs.is_empty());
6666                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6667                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6668                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6669                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6670
6671                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6672                 assert_eq!(events.len(), 2);
6673                 for event in events {
6674                         match event {
6675                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6676                                 _ => panic!("Unexpected event"),
6677                         }
6678                 }
6679
6680                 let events = nodes[0].node.get_and_clear_pending_events();
6681                 assert_eq!(events.len(), 2);
6682                 match events[0] {
6683                         Event::PaymentFailed { ref payment_hash, .. } => {
6684                                 assert!(failed_htlcs.insert(payment_hash.0));
6685                         },
6686                         _ => panic!("Unexpected event"),
6687                 }
6688                 match events[1] {
6689                         Event::PaymentFailed { ref payment_hash, .. } => {
6690                                 assert!(failed_htlcs.insert(payment_hash.0));
6691                         },
6692                         _ => panic!("Unexpected event"),
6693                 }
6694
6695                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6696                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6697                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6698         }
6699
6700         #[test]
6701         fn test_commitment_revoked_fail_backward_exhaustive() {
6702                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6703                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6704         }
6705
6706         #[test]
6707         fn test_htlc_ignore_latest_remote_commitment() {
6708                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6709                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6710                 let nodes = create_network(2);
6711                 create_announced_chan_between_nodes(&nodes, 0, 1);
6712
6713                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6714                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6715                 {
6716                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6717                         assert_eq!(events.len(), 1);
6718                         match events[0] {
6719                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6720                                         assert_eq!(flags & 0b10, 0b10);
6721                                 },
6722                                 _ => panic!("Unexpected event"),
6723                         }
6724                 }
6725
6726                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6727                 assert_eq!(node_txn.len(), 2);
6728
6729                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6730                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6731
6732                 {
6733                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6734                         assert_eq!(events.len(), 1);
6735                         match events[0] {
6736                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6737                                         assert_eq!(flags & 0b10, 0b10);
6738                                 },
6739                                 _ => panic!("Unexpected event"),
6740                         }
6741                 }
6742
6743                 // Duplicate the block_connected call since this may happen due to other listeners
6744                 // registering new transactions
6745                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6746         }
6747
6748         #[test]
6749         fn test_force_close_fail_back() {
6750                 // Check which HTLCs are failed-backwards on channel force-closure
6751                 let mut nodes = create_network(3);
6752                 create_announced_chan_between_nodes(&nodes, 0, 1);
6753                 create_announced_chan_between_nodes(&nodes, 1, 2);
6754
6755                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6756
6757                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6758
6759                 let mut payment_event = {
6760                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6761                         check_added_monitors!(nodes[0], 1);
6762
6763                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6764                         assert_eq!(events.len(), 1);
6765                         SendEvent::from_event(events.remove(0))
6766                 };
6767
6768                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6769                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6770
6771                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6772                 assert_eq!(events_1.len(), 1);
6773                 match events_1[0] {
6774                         Event::PendingHTLCsForwardable { .. } => { },
6775                         _ => panic!("Unexpected event"),
6776                 };
6777
6778                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6779                 nodes[1].node.process_pending_htlc_forwards();
6780
6781                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6782                 assert_eq!(events_2.len(), 1);
6783                 payment_event = SendEvent::from_event(events_2.remove(0));
6784                 assert_eq!(payment_event.msgs.len(), 1);
6785
6786                 check_added_monitors!(nodes[1], 1);
6787                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6788                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6789                 check_added_monitors!(nodes[2], 1);
6790                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6791
6792                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6793                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6794                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6795
6796                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6797                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6798                 assert_eq!(events_3.len(), 1);
6799                 match events_3[0] {
6800                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6801                                 assert_eq!(flags & 0b10, 0b10);
6802                         },
6803                         _ => panic!("Unexpected event"),
6804                 }
6805
6806                 let tx = {
6807                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6808                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6809                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6810                         // back to nodes[1] upon timeout otherwise.
6811                         assert_eq!(node_txn.len(), 1);
6812                         node_txn.remove(0)
6813                 };
6814
6815                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6816                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6817
6818                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6819                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6820                 assert_eq!(events_4.len(), 1);
6821                 match events_4[0] {
6822                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6823                                 assert_eq!(flags & 0b10, 0b10);
6824                         },
6825                         _ => panic!("Unexpected event"),
6826                 }
6827
6828                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6829                 {
6830                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6831                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6832                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6833                 }
6834                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6835                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6836                 assert_eq!(node_txn.len(), 1);
6837                 assert_eq!(node_txn[0].input.len(), 1);
6838                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6839                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6840                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6841
6842                 check_spends!(node_txn[0], tx);
6843         }
6844
6845         #[test]
6846         fn test_unconf_chan() {
6847                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6848                 let nodes = create_network(2);
6849                 create_announced_chan_between_nodes(&nodes, 0, 1);
6850
6851                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6852                 assert_eq!(channel_state.by_id.len(), 1);
6853                 assert_eq!(channel_state.short_to_id.len(), 1);
6854                 mem::drop(channel_state);
6855
6856                 let mut headers = Vec::new();
6857                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6858                 headers.push(header.clone());
6859                 for _i in 2..100 {
6860                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6861                         headers.push(header.clone());
6862                 }
6863                 while !headers.is_empty() {
6864                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6865                 }
6866                 {
6867                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6868                         assert_eq!(events.len(), 1);
6869                         match events[0] {
6870                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6871                                         assert_eq!(flags & 0b10, 0b10);
6872                                 },
6873                                 _ => panic!("Unexpected event"),
6874                         }
6875                 }
6876                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6877                 assert_eq!(channel_state.by_id.len(), 0);
6878                 assert_eq!(channel_state.short_to_id.len(), 0);
6879         }
6880
6881         macro_rules! get_chan_reestablish_msgs {
6882                 ($src_node: expr, $dst_node: expr) => {
6883                         {
6884                                 let mut res = Vec::with_capacity(1);
6885                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6886                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6887                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6888                                                 res.push(msg.clone());
6889                                         } else {
6890                                                 panic!("Unexpected event")
6891                                         }
6892                                 }
6893                                 res
6894                         }
6895                 }
6896         }
6897
6898         macro_rules! handle_chan_reestablish_msgs {
6899                 ($src_node: expr, $dst_node: expr) => {
6900                         {
6901                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6902                                 let mut idx = 0;
6903                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6904                                         idx += 1;
6905                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6906                                         Some(msg.clone())
6907                                 } else {
6908                                         None
6909                                 };
6910
6911                                 let mut revoke_and_ack = None;
6912                                 let mut commitment_update = None;
6913                                 let order = if let Some(ev) = msg_events.get(idx) {
6914                                         idx += 1;
6915                                         match ev {
6916                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6917                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6918                                                         revoke_and_ack = Some(msg.clone());
6919                                                         RAACommitmentOrder::RevokeAndACKFirst
6920                                                 },
6921                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6922                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6923                                                         commitment_update = Some(updates.clone());
6924                                                         RAACommitmentOrder::CommitmentFirst
6925                                                 },
6926                                                 _ => panic!("Unexpected event"),
6927                                         }
6928                                 } else {
6929                                         RAACommitmentOrder::CommitmentFirst
6930                                 };
6931
6932                                 if let Some(ev) = msg_events.get(idx) {
6933                                         match ev {
6934                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6935                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6936                                                         assert!(revoke_and_ack.is_none());
6937                                                         revoke_and_ack = Some(msg.clone());
6938                                                 },
6939                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6940                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6941                                                         assert!(commitment_update.is_none());
6942                                                         commitment_update = Some(updates.clone());
6943                                                 },
6944                                                 _ => panic!("Unexpected event"),
6945                                         }
6946                                 }
6947
6948                                 (funding_locked, revoke_and_ack, commitment_update, order)
6949                         }
6950                 }
6951         }
6952
6953         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6954         /// for claims/fails they are separated out.
6955         fn reconnect_nodes(node_a: &Node, node_b: &Node, send_funding_locked: (bool, 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)) {
6956                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6957                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6958                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6959                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6960
6961                 if send_funding_locked.0 {
6962                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6963                         // from b
6964                         for reestablish in reestablish_1.iter() {
6965                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6966                         }
6967                 }
6968                 if send_funding_locked.1 {
6969                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6970                         // from a
6971                         for reestablish in reestablish_2.iter() {
6972                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6973                         }
6974                 }
6975                 if send_funding_locked.0 || send_funding_locked.1 {
6976                         // If we expect any funding_locked's, both sides better have set
6977                         // next_local_commitment_number to 1
6978                         for reestablish in reestablish_1.iter() {
6979                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6980                         }
6981                         for reestablish in reestablish_2.iter() {
6982                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6983                         }
6984                 }
6985
6986                 let mut resp_1 = Vec::new();
6987                 for msg in reestablish_1 {
6988                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6989                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6990                 }
6991                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6992                         check_added_monitors!(node_b, 1);
6993                 } else {
6994                         check_added_monitors!(node_b, 0);
6995                 }
6996
6997                 let mut resp_2 = Vec::new();
6998                 for msg in reestablish_2 {
6999                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7000                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7001                 }
7002                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7003                         check_added_monitors!(node_a, 1);
7004                 } else {
7005                         check_added_monitors!(node_a, 0);
7006                 }
7007
7008                 // We dont yet support both needing updates, as that would require a different commitment dance:
7009                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7010                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7011
7012                 for chan_msgs in resp_1.drain(..) {
7013                         if send_funding_locked.0 {
7014                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7015                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7016                                 if !announcement_event.is_empty() {
7017                                         assert_eq!(announcement_event.len(), 1);
7018                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7019                                                 //TODO: Test announcement_sigs re-sending
7020                                         } else { panic!("Unexpected event!"); }
7021                                 }
7022                         } else {
7023                                 assert!(chan_msgs.0.is_none());
7024                         }
7025                         if pending_raa.0 {
7026                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7027                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7028                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7029                                 check_added_monitors!(node_a, 1);
7030                         } else {
7031                                 assert!(chan_msgs.1.is_none());
7032                         }
7033                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7034                                 let commitment_update = chan_msgs.2.unwrap();
7035                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7036                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7037                                 } else {
7038                                         assert!(commitment_update.update_add_htlcs.is_empty());
7039                                 }
7040                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7041                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7042                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7043                                 for update_add in commitment_update.update_add_htlcs {
7044                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7045                                 }
7046                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7047                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7048                                 }
7049                                 for update_fail in commitment_update.update_fail_htlcs {
7050                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7051                                 }
7052
7053                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7054                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7055                                 } else {
7056                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7057                                         check_added_monitors!(node_a, 1);
7058                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7059                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7060                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7061                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7062                                         check_added_monitors!(node_b, 1);
7063                                 }
7064                         } else {
7065                                 assert!(chan_msgs.2.is_none());
7066                         }
7067                 }
7068
7069                 for chan_msgs in resp_2.drain(..) {
7070                         if send_funding_locked.1 {
7071                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7072                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7073                                 if !announcement_event.is_empty() {
7074                                         assert_eq!(announcement_event.len(), 1);
7075                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7076                                                 //TODO: Test announcement_sigs re-sending
7077                                         } else { panic!("Unexpected event!"); }
7078                                 }
7079                         } else {
7080                                 assert!(chan_msgs.0.is_none());
7081                         }
7082                         if pending_raa.1 {
7083                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7084                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7085                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7086                                 check_added_monitors!(node_b, 1);
7087                         } else {
7088                                 assert!(chan_msgs.1.is_none());
7089                         }
7090                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7091                                 let commitment_update = chan_msgs.2.unwrap();
7092                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7093                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7094                                 }
7095                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7096                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7097                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7098                                 for update_add in commitment_update.update_add_htlcs {
7099                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7100                                 }
7101                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7102                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7103                                 }
7104                                 for update_fail in commitment_update.update_fail_htlcs {
7105                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7106                                 }
7107
7108                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7109                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7110                                 } else {
7111                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7112                                         check_added_monitors!(node_b, 1);
7113                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7114                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7115                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7116                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7117                                         check_added_monitors!(node_a, 1);
7118                                 }
7119                         } else {
7120                                 assert!(chan_msgs.2.is_none());
7121                         }
7122                 }
7123         }
7124
7125         #[test]
7126         fn test_simple_peer_disconnect() {
7127                 // Test that we can reconnect when there are no lost messages
7128                 let nodes = create_network(3);
7129                 create_announced_chan_between_nodes(&nodes, 0, 1);
7130                 create_announced_chan_between_nodes(&nodes, 1, 2);
7131
7132                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7133                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7134                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7135
7136                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7137                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7138                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7139                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7140
7141                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7142                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7143                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7144
7145                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7146                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7147                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7148                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7149
7150                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7151                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7152
7153                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7154                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7155
7156                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7157                 {
7158                         let events = nodes[0].node.get_and_clear_pending_events();
7159                         assert_eq!(events.len(), 2);
7160                         match events[0] {
7161                                 Event::PaymentSent { payment_preimage } => {
7162                                         assert_eq!(payment_preimage, payment_preimage_3);
7163                                 },
7164                                 _ => panic!("Unexpected event"),
7165                         }
7166                         match events[1] {
7167                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7168                                         assert_eq!(payment_hash, payment_hash_5);
7169                                         assert!(rejected_by_dest);
7170                                 },
7171                                 _ => panic!("Unexpected event"),
7172                         }
7173                 }
7174
7175                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7176                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7177         }
7178
7179         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7180                 // Test that we can reconnect when in-flight HTLC updates get dropped
7181                 let mut nodes = create_network(2);
7182                 if messages_delivered == 0 {
7183                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7184                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7185                 } else {
7186                         create_announced_chan_between_nodes(&nodes, 0, 1);
7187                 }
7188
7189                 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();
7190                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7191
7192                 let payment_event = {
7193                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7194                         check_added_monitors!(nodes[0], 1);
7195
7196                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7197                         assert_eq!(events.len(), 1);
7198                         SendEvent::from_event(events.remove(0))
7199                 };
7200                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7201
7202                 if messages_delivered < 2 {
7203                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7204                 } else {
7205                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7206                         if messages_delivered >= 3 {
7207                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7208                                 check_added_monitors!(nodes[1], 1);
7209                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7210
7211                                 if messages_delivered >= 4 {
7212                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7213                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7214                                         check_added_monitors!(nodes[0], 1);
7215
7216                                         if messages_delivered >= 5 {
7217                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7218                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7219                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7220                                                 check_added_monitors!(nodes[0], 1);
7221
7222                                                 if messages_delivered >= 6 {
7223                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7224                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7225                                                         check_added_monitors!(nodes[1], 1);
7226                                                 }
7227                                         }
7228                                 }
7229                         }
7230                 }
7231
7232                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7233                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7234                 if messages_delivered < 3 {
7235                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7236                         // received on either side, both sides will need to resend them.
7237                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7238                 } else if messages_delivered == 3 {
7239                         // nodes[0] still wants its RAA + commitment_signed
7240                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7241                 } else if messages_delivered == 4 {
7242                         // nodes[0] still wants its commitment_signed
7243                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7244                 } else if messages_delivered == 5 {
7245                         // nodes[1] still wants its final RAA
7246                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7247                 } else if messages_delivered == 6 {
7248                         // Everything was delivered...
7249                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7250                 }
7251
7252                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7253                 assert_eq!(events_1.len(), 1);
7254                 match events_1[0] {
7255                         Event::PendingHTLCsForwardable { .. } => { },
7256                         _ => panic!("Unexpected event"),
7257                 };
7258
7259                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7260                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7261                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7262
7263                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7264                 nodes[1].node.process_pending_htlc_forwards();
7265
7266                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7267                 assert_eq!(events_2.len(), 1);
7268                 match events_2[0] {
7269                         Event::PaymentReceived { ref payment_hash, amt } => {
7270                                 assert_eq!(payment_hash_1, *payment_hash);
7271                                 assert_eq!(amt, 1000000);
7272                         },
7273                         _ => panic!("Unexpected event"),
7274                 }
7275
7276                 nodes[1].node.claim_funds(payment_preimage_1);
7277                 check_added_monitors!(nodes[1], 1);
7278
7279                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7280                 assert_eq!(events_3.len(), 1);
7281                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7282                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7283                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7284                                 assert!(updates.update_add_htlcs.is_empty());
7285                                 assert!(updates.update_fail_htlcs.is_empty());
7286                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7287                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7288                                 assert!(updates.update_fee.is_none());
7289                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7290                         },
7291                         _ => panic!("Unexpected event"),
7292                 };
7293
7294                 if messages_delivered >= 1 {
7295                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7296
7297                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7298                         assert_eq!(events_4.len(), 1);
7299                         match events_4[0] {
7300                                 Event::PaymentSent { ref payment_preimage } => {
7301                                         assert_eq!(payment_preimage_1, *payment_preimage);
7302                                 },
7303                                 _ => panic!("Unexpected event"),
7304                         }
7305
7306                         if messages_delivered >= 2 {
7307                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7308                                 check_added_monitors!(nodes[0], 1);
7309                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7310
7311                                 if messages_delivered >= 3 {
7312                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7313                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7314                                         check_added_monitors!(nodes[1], 1);
7315
7316                                         if messages_delivered >= 4 {
7317                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7318                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7319                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7320                                                 check_added_monitors!(nodes[1], 1);
7321
7322                                                 if messages_delivered >= 5 {
7323                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7324                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7325                                                         check_added_monitors!(nodes[0], 1);
7326                                                 }
7327                                         }
7328                                 }
7329                         }
7330                 }
7331
7332                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7333                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7334                 if messages_delivered < 2 {
7335                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7336                         //TODO: Deduplicate PaymentSent events, then enable this if:
7337                         //if messages_delivered < 1 {
7338                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7339                                 assert_eq!(events_4.len(), 1);
7340                                 match events_4[0] {
7341                                         Event::PaymentSent { ref payment_preimage } => {
7342                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7343                                         },
7344                                         _ => panic!("Unexpected event"),
7345                                 }
7346                         //}
7347                 } else if messages_delivered == 2 {
7348                         // nodes[0] still wants its RAA + commitment_signed
7349                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7350                 } else if messages_delivered == 3 {
7351                         // nodes[0] still wants its commitment_signed
7352                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7353                 } else if messages_delivered == 4 {
7354                         // nodes[1] still wants its final RAA
7355                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7356                 } else if messages_delivered == 5 {
7357                         // Everything was delivered...
7358                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7359                 }
7360
7361                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7362                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7363                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7364
7365                 // Channel should still work fine...
7366                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7367                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7368         }
7369
7370         #[test]
7371         fn test_drop_messages_peer_disconnect_a() {
7372                 do_test_drop_messages_peer_disconnect(0);
7373                 do_test_drop_messages_peer_disconnect(1);
7374                 do_test_drop_messages_peer_disconnect(2);
7375                 do_test_drop_messages_peer_disconnect(3);
7376         }
7377
7378         #[test]
7379         fn test_drop_messages_peer_disconnect_b() {
7380                 do_test_drop_messages_peer_disconnect(4);
7381                 do_test_drop_messages_peer_disconnect(5);
7382                 do_test_drop_messages_peer_disconnect(6);
7383         }
7384
7385         #[test]
7386         fn test_funding_peer_disconnect() {
7387                 // Test that we can lock in our funding tx while disconnected
7388                 let nodes = create_network(2);
7389                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7390
7391                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7392                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7393
7394                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7395                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7396                 assert_eq!(events_1.len(), 1);
7397                 match events_1[0] {
7398                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7399                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7400                         },
7401                         _ => panic!("Unexpected event"),
7402                 }
7403
7404                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7405
7406                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7407                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7408
7409                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7410                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7411                 assert_eq!(events_2.len(), 2);
7412                 match events_2[0] {
7413                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7414                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7415                         },
7416                         _ => panic!("Unexpected event"),
7417                 }
7418                 match events_2[1] {
7419                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7420                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7421                         },
7422                         _ => panic!("Unexpected event"),
7423                 }
7424
7425                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7426
7427                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7428                 // rebroadcasting announcement_signatures upon reconnect.
7429
7430                 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();
7431                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7432                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7433         }
7434
7435         #[test]
7436         fn test_drop_messages_peer_disconnect_dual_htlc() {
7437                 // Test that we can handle reconnecting when both sides of a channel have pending
7438                 // commitment_updates when we disconnect.
7439                 let mut nodes = create_network(2);
7440                 create_announced_chan_between_nodes(&nodes, 0, 1);
7441
7442                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7443
7444                 // Now try to send a second payment which will fail to send
7445                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7446                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7447
7448                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7449                 check_added_monitors!(nodes[0], 1);
7450
7451                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7452                 assert_eq!(events_1.len(), 1);
7453                 match events_1[0] {
7454                         MessageSendEvent::UpdateHTLCs { .. } => {},
7455                         _ => panic!("Unexpected event"),
7456                 }
7457
7458                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7459                 check_added_monitors!(nodes[1], 1);
7460
7461                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7462                 assert_eq!(events_2.len(), 1);
7463                 match events_2[0] {
7464                         MessageSendEvent::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 } } => {
7465                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7466                                 assert!(update_add_htlcs.is_empty());
7467                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7468                                 assert!(update_fail_htlcs.is_empty());
7469                                 assert!(update_fail_malformed_htlcs.is_empty());
7470                                 assert!(update_fee.is_none());
7471
7472                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7473                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7474                                 assert_eq!(events_3.len(), 1);
7475                                 match events_3[0] {
7476                                         Event::PaymentSent { ref payment_preimage } => {
7477                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7478                                         },
7479                                         _ => panic!("Unexpected event"),
7480                                 }
7481
7482                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7483                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7484                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7485                                 check_added_monitors!(nodes[0], 1);
7486                         },
7487                         _ => panic!("Unexpected event"),
7488                 }
7489
7490                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7491                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7492
7493                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7494                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7495                 assert_eq!(reestablish_1.len(), 1);
7496                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7497                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7498                 assert_eq!(reestablish_2.len(), 1);
7499
7500                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7501                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7502                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7503                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7504
7505                 assert!(as_resp.0.is_none());
7506                 assert!(bs_resp.0.is_none());
7507
7508                 assert!(bs_resp.1.is_none());
7509                 assert!(bs_resp.2.is_none());
7510
7511                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7512
7513                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7514                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7515                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7516                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7517                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7518                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
7519                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7520                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7521                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7522                 check_added_monitors!(nodes[1], 1);
7523
7524                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7525                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7526                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7527                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7528                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7529                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7530                 assert!(bs_second_commitment_signed.update_fee.is_none());
7531                 check_added_monitors!(nodes[1], 1);
7532
7533                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7534                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7535                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7536                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7537                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7538                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7539                 assert!(as_commitment_signed.update_fee.is_none());
7540                 check_added_monitors!(nodes[0], 1);
7541
7542                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7543                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7544                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7545                 check_added_monitors!(nodes[0], 1);
7546
7547                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7548                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7549                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7550                 check_added_monitors!(nodes[1], 1);
7551
7552                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7553                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7554                 check_added_monitors!(nodes[1], 1);
7555
7556                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7557                 assert_eq!(events_4.len(), 1);
7558                 match events_4[0] {
7559                         Event::PendingHTLCsForwardable { .. } => { },
7560                         _ => panic!("Unexpected event"),
7561                 };
7562
7563                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7564                 nodes[1].node.process_pending_htlc_forwards();
7565
7566                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7567                 assert_eq!(events_5.len(), 1);
7568                 match events_5[0] {
7569                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7570                                 assert_eq!(payment_hash_2, *payment_hash);
7571                         },
7572                         _ => panic!("Unexpected event"),
7573                 }
7574
7575                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7576                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7577                 check_added_monitors!(nodes[0], 1);
7578
7579                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7580         }
7581
7582         #[test]
7583         fn test_simple_monitor_permanent_update_fail() {
7584                 // Test that we handle a simple permanent monitor update failure
7585                 let mut nodes = create_network(2);
7586                 create_announced_chan_between_nodes(&nodes, 0, 1);
7587
7588                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7589                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7590
7591                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7592                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7593                 check_added_monitors!(nodes[0], 1);
7594
7595                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7596                 assert_eq!(events_1.len(), 2);
7597                 match events_1[0] {
7598                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7599                         _ => panic!("Unexpected event"),
7600                 };
7601                 match events_1[1] {
7602                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7603                         _ => panic!("Unexpected event"),
7604                 };
7605
7606                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7607                 // PaymentFailed event
7608
7609                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7610         }
7611
7612         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7613                 // Test that we can recover from a simple temporary monitor update failure optionally with
7614                 // a disconnect in between
7615                 let mut nodes = create_network(2);
7616                 create_announced_chan_between_nodes(&nodes, 0, 1);
7617
7618                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7619                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7620
7621                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7622                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7623                 check_added_monitors!(nodes[0], 1);
7624
7625                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7626                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7627                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7628
7629                 if disconnect {
7630                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7631                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7632                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7633                 }
7634
7635                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7636                 nodes[0].node.test_restore_channel_monitor();
7637                 check_added_monitors!(nodes[0], 1);
7638
7639                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7640                 assert_eq!(events_2.len(), 1);
7641                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7642                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7643                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7644                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7645
7646                 expect_pending_htlcs_forwardable!(nodes[1]);
7647
7648                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7649                 assert_eq!(events_3.len(), 1);
7650                 match events_3[0] {
7651                         Event::PaymentReceived { ref payment_hash, amt } => {
7652                                 assert_eq!(payment_hash_1, *payment_hash);
7653                                 assert_eq!(amt, 1000000);
7654                         },
7655                         _ => panic!("Unexpected event"),
7656                 }
7657
7658                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7659
7660                 // Now set it to failed again...
7661                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7662                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7663                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7664                 check_added_monitors!(nodes[0], 1);
7665
7666                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7667                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7668                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7669
7670                 if disconnect {
7671                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7672                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7673                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7674                 }
7675
7676                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7677                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7678                 nodes[0].node.test_restore_channel_monitor();
7679                 check_added_monitors!(nodes[0], 1);
7680
7681                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7682                 assert_eq!(events_5.len(), 1);
7683                 match events_5[0] {
7684                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7685                         _ => panic!("Unexpected event"),
7686                 }
7687
7688                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7689                 // PaymentFailed event
7690
7691                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7692         }
7693
7694         #[test]
7695         fn test_simple_monitor_temporary_update_fail() {
7696                 do_test_simple_monitor_temporary_update_fail(false);
7697                 do_test_simple_monitor_temporary_update_fail(true);
7698         }
7699
7700         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7701                 let disconnect_flags = 8 | 16;
7702
7703                 // Test that we can recover from a temporary monitor update failure with some in-flight
7704                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7705                 // * First we route a payment, then get a temporary monitor update failure when trying to
7706                 //   route a second payment. We then claim the first payment.
7707                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7708                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7709                 //   the ChannelMonitor on a watchtower).
7710                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7711                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7712                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7713                 //   disconnect_count & !disconnect_flags is 0).
7714                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7715                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7716                 //   disconnect_count, to get the update_fulfill_htlc through.
7717                 // * We then walk through more message exchanges to get the original update_add_htlc
7718                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7719                 //   disconnect/reconnecting based on disconnect_count.
7720                 let mut nodes = create_network(2);
7721                 create_announced_chan_between_nodes(&nodes, 0, 1);
7722
7723                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7724
7725                 // Now try to send a second payment which will fail to send
7726                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7727                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7728
7729                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7730                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7731                 check_added_monitors!(nodes[0], 1);
7732
7733                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7734                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7735                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7736
7737                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7738                 // but nodes[0] won't respond since it is frozen.
7739                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7740                 check_added_monitors!(nodes[1], 1);
7741                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7742                 assert_eq!(events_2.len(), 1);
7743                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7744                         MessageSendEvent::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 } } => {
7745                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7746                                 assert!(update_add_htlcs.is_empty());
7747                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7748                                 assert!(update_fail_htlcs.is_empty());
7749                                 assert!(update_fail_malformed_htlcs.is_empty());
7750                                 assert!(update_fee.is_none());
7751
7752                                 if (disconnect_count & 16) == 0 {
7753                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7754                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7755                                         assert_eq!(events_3.len(), 1);
7756                                         match events_3[0] {
7757                                                 Event::PaymentSent { ref payment_preimage } => {
7758                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7759                                                 },
7760                                                 _ => panic!("Unexpected event"),
7761                                         }
7762
7763                                         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed) {
7764                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7765                                         } else { panic!(); }
7766                                 }
7767
7768                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7769                         },
7770                         _ => panic!("Unexpected event"),
7771                 };
7772
7773                 if disconnect_count & !disconnect_flags > 0 {
7774                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7775                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7776                 }
7777
7778                 // Now fix monitor updating...
7779                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7780                 nodes[0].node.test_restore_channel_monitor();
7781                 check_added_monitors!(nodes[0], 1);
7782
7783                 macro_rules! disconnect_reconnect_peers { () => { {
7784                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7785                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7786
7787                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7788                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7789                         assert_eq!(reestablish_1.len(), 1);
7790                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7791                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7792                         assert_eq!(reestablish_2.len(), 1);
7793
7794                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7795                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7796                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7797                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7798
7799                         assert!(as_resp.0.is_none());
7800                         assert!(bs_resp.0.is_none());
7801
7802                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7803                 } } }
7804
7805                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7806                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7807                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7808
7809                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7810                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7811                         assert_eq!(reestablish_1.len(), 1);
7812                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7813                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7814                         assert_eq!(reestablish_2.len(), 1);
7815
7816                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7817                         check_added_monitors!(nodes[0], 0);
7818                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7819                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7820                         check_added_monitors!(nodes[1], 0);
7821                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7822
7823                         assert!(as_resp.0.is_none());
7824                         assert!(bs_resp.0.is_none());
7825
7826                         assert!(bs_resp.1.is_none());
7827                         if (disconnect_count & 16) == 0 {
7828                                 assert!(bs_resp.2.is_none());
7829
7830                                 assert!(as_resp.1.is_some());
7831                                 assert!(as_resp.2.is_some());
7832                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7833                         } else {
7834                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7835                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7836                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7837                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7838                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7839                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7840
7841                                 assert!(as_resp.1.is_none());
7842
7843                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().update_fulfill_htlcs[0]).unwrap();
7844                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7845                                 assert_eq!(events_3.len(), 1);
7846                                 match events_3[0] {
7847                                         Event::PaymentSent { ref payment_preimage } => {
7848                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7849                                         },
7850                                         _ => panic!("Unexpected event"),
7851                                 }
7852
7853                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7854                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7855                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7856                                 check_added_monitors!(nodes[0], 1);
7857
7858                                 as_resp.1 = Some(as_resp_raa);
7859                                 bs_resp.2 = None;
7860                         }
7861
7862                         if disconnect_count & !disconnect_flags > 1 {
7863                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7864
7865                                 if (disconnect_count & 16) == 0 {
7866                                         assert!(reestablish_1 == second_reestablish_1);
7867                                         assert!(reestablish_2 == second_reestablish_2);
7868                                 }
7869                                 assert!(as_resp == second_as_resp);
7870                                 assert!(bs_resp == second_bs_resp);
7871                         }
7872
7873                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7874                 } else {
7875                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7876                         assert_eq!(events_4.len(), 2);
7877                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7878                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7879                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7880                                         msg.clone()
7881                                 },
7882                                 _ => panic!("Unexpected event"),
7883                         })
7884                 };
7885
7886                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7887
7888                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7889                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7890                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7891                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7892                 check_added_monitors!(nodes[1], 1);
7893
7894                 if disconnect_count & !disconnect_flags > 2 {
7895                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7896
7897                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7898                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7899
7900                         assert!(as_resp.2.is_none());
7901                         assert!(bs_resp.2.is_none());
7902                 }
7903
7904                 let as_commitment_update;
7905                 let bs_second_commitment_update;
7906
7907                 macro_rules! handle_bs_raa { () => {
7908                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7909                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7910                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7911                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7912                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7913                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7914                         assert!(as_commitment_update.update_fee.is_none());
7915                         check_added_monitors!(nodes[0], 1);
7916                 } }
7917
7918                 macro_rules! handle_initial_raa { () => {
7919                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7920                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7921                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7922                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7923                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7924                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7925                         assert!(bs_second_commitment_update.update_fee.is_none());
7926                         check_added_monitors!(nodes[1], 1);
7927                 } }
7928
7929                 if (disconnect_count & 8) == 0 {
7930                         handle_bs_raa!();
7931
7932                         if disconnect_count & !disconnect_flags > 3 {
7933                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7934
7935                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7936                                 assert!(bs_resp.1.is_none());
7937
7938                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7939                                 assert!(bs_resp.2.is_none());
7940
7941                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7942                         }
7943
7944                         handle_initial_raa!();
7945
7946                         if disconnect_count & !disconnect_flags > 4 {
7947                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7948
7949                                 assert!(as_resp.1.is_none());
7950                                 assert!(bs_resp.1.is_none());
7951
7952                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7953                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7954                         }
7955                 } else {
7956                         handle_initial_raa!();
7957
7958                         if disconnect_count & !disconnect_flags > 3 {
7959                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7960
7961                                 assert!(as_resp.1.is_none());
7962                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7963
7964                                 assert!(as_resp.2.is_none());
7965                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7966
7967                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7968                         }
7969
7970                         handle_bs_raa!();
7971
7972                         if disconnect_count & !disconnect_flags > 4 {
7973                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7974
7975                                 assert!(as_resp.1.is_none());
7976                                 assert!(bs_resp.1.is_none());
7977
7978                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7979                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7980                         }
7981                 }
7982
7983                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7984                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7985                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7986                 check_added_monitors!(nodes[0], 1);
7987
7988                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7989                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7990                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7991                 check_added_monitors!(nodes[1], 1);
7992
7993                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7994                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7995                 check_added_monitors!(nodes[1], 1);
7996
7997                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7998                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7999                 check_added_monitors!(nodes[0], 1);
8000
8001                 expect_pending_htlcs_forwardable!(nodes[1]);
8002
8003                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8004                 assert_eq!(events_5.len(), 1);
8005                 match events_5[0] {
8006                         Event::PaymentReceived { ref payment_hash, amt } => {
8007                                 assert_eq!(payment_hash_2, *payment_hash);
8008                                 assert_eq!(amt, 1000000);
8009                         },
8010                         _ => panic!("Unexpected event"),
8011                 }
8012
8013                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8014         }
8015
8016         #[test]
8017         fn test_monitor_temporary_update_fail_a() {
8018                 do_test_monitor_temporary_update_fail(0);
8019                 do_test_monitor_temporary_update_fail(1);
8020                 do_test_monitor_temporary_update_fail(2);
8021                 do_test_monitor_temporary_update_fail(3);
8022                 do_test_monitor_temporary_update_fail(4);
8023                 do_test_monitor_temporary_update_fail(5);
8024         }
8025
8026         #[test]
8027         fn test_monitor_temporary_update_fail_b() {
8028                 do_test_monitor_temporary_update_fail(2 | 8);
8029                 do_test_monitor_temporary_update_fail(3 | 8);
8030                 do_test_monitor_temporary_update_fail(4 | 8);
8031                 do_test_monitor_temporary_update_fail(5 | 8);
8032         }
8033
8034         #[test]
8035         fn test_monitor_temporary_update_fail_c() {
8036                 do_test_monitor_temporary_update_fail(1 | 16);
8037                 do_test_monitor_temporary_update_fail(2 | 16);
8038                 do_test_monitor_temporary_update_fail(3 | 16);
8039                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8040                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8041         }
8042
8043         #[test]
8044         fn test_monitor_update_fail_cs() {
8045                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8046                 let mut nodes = create_network(2);
8047                 create_announced_chan_between_nodes(&nodes, 0, 1);
8048
8049                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8050                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8051                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8052                 check_added_monitors!(nodes[0], 1);
8053
8054                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8055                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8056
8057                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8058                 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event.commitment_msg).unwrap_err() {
8059                         assert_eq!(err, "Failed to update ChannelMonitor");
8060                 } else { panic!(); }
8061                 check_added_monitors!(nodes[1], 1);
8062                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8063
8064                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8065                 nodes[1].node.test_restore_channel_monitor();
8066                 check_added_monitors!(nodes[1], 1);
8067                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8068                 assert_eq!(responses.len(), 2);
8069
8070                 match responses[0] {
8071                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8072                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8073                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8074                                 check_added_monitors!(nodes[0], 1);
8075                         },
8076                         _ => panic!("Unexpected event"),
8077                 }
8078                 match responses[1] {
8079                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8080                                 assert!(updates.update_add_htlcs.is_empty());
8081                                 assert!(updates.update_fulfill_htlcs.is_empty());
8082                                 assert!(updates.update_fail_htlcs.is_empty());
8083                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8084                                 assert!(updates.update_fee.is_none());
8085                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8086
8087                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8088                                 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed).unwrap_err() {
8089                                         assert_eq!(err, "Failed to update ChannelMonitor");
8090                                 } else { panic!(); }
8091                                 check_added_monitors!(nodes[0], 1);
8092                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8093                         },
8094                         _ => panic!("Unexpected event"),
8095                 }
8096
8097                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8098                 nodes[0].node.test_restore_channel_monitor();
8099                 check_added_monitors!(nodes[0], 1);
8100
8101                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8102                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8103                 check_added_monitors!(nodes[1], 1);
8104
8105                 let mut events = nodes[1].node.get_and_clear_pending_events();
8106                 assert_eq!(events.len(), 1);
8107                 match events[0] {
8108                         Event::PendingHTLCsForwardable { .. } => { },
8109                         _ => panic!("Unexpected event"),
8110                 };
8111                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8112                 nodes[1].node.process_pending_htlc_forwards();
8113
8114                 events = nodes[1].node.get_and_clear_pending_events();
8115                 assert_eq!(events.len(), 1);
8116                 match events[0] {
8117                         Event::PaymentReceived { payment_hash, amt } => {
8118                                 assert_eq!(payment_hash, our_payment_hash);
8119                                 assert_eq!(amt, 1000000);
8120                         },
8121                         _ => panic!("Unexpected event"),
8122                 };
8123
8124                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8125         }
8126
8127         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8128                 // Tests handling of a monitor update failure when processing an incoming RAA
8129                 let mut nodes = create_network(3);
8130                 create_announced_chan_between_nodes(&nodes, 0, 1);
8131                 create_announced_chan_between_nodes(&nodes, 1, 2);
8132
8133                 // Rebalance a bit so that we can send backwards from 2 to 1.
8134                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8135
8136                 // Route a first payment that we'll fail backwards
8137                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8138
8139                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8140                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8141                 check_added_monitors!(nodes[2], 1);
8142
8143                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8144                 assert!(updates.update_add_htlcs.is_empty());
8145                 assert!(updates.update_fulfill_htlcs.is_empty());
8146                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8147                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8148                 assert!(updates.update_fee.is_none());
8149                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8150
8151                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8152                 check_added_monitors!(nodes[0], 0);
8153
8154                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8155                 // holding cell.
8156                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8157                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8158                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8159                 check_added_monitors!(nodes[0], 1);
8160
8161                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8162                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8163                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8164
8165                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8166                 assert_eq!(events_1.len(), 1);
8167                 match events_1[0] {
8168                         Event::PendingHTLCsForwardable { .. } => { },
8169                         _ => panic!("Unexpected event"),
8170                 };
8171
8172                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8173                 nodes[1].node.process_pending_htlc_forwards();
8174                 check_added_monitors!(nodes[1], 0);
8175                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8176
8177                 // Now fail monitor updating.
8178                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8179                 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap_err() {
8180                         assert_eq!(err, "Failed to update ChannelMonitor");
8181                 } else { panic!(); }
8182                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8183                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8184                 check_added_monitors!(nodes[1], 1);
8185
8186                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8187                 // for forwarding.
8188
8189                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8190                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8191                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8192                 check_added_monitors!(nodes[0], 1);
8193
8194                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8195                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8196                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8197                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8198                 check_added_monitors!(nodes[1], 0);
8199
8200                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8201                 assert_eq!(events_2.len(), 1);
8202                 match events_2.remove(0) {
8203                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8204                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8205                                 assert!(updates.update_fulfill_htlcs.is_empty());
8206                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8207                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8208                                 assert!(updates.update_add_htlcs.is_empty());
8209                                 assert!(updates.update_fee.is_none());
8210
8211                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8212                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8213
8214                                 let events = nodes[0].node.get_and_clear_pending_events();
8215                                 assert_eq!(events.len(), 1);
8216                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events[0] {
8217                                         assert_eq!(payment_hash, payment_hash_3);
8218                                         assert!(!rejected_by_dest);
8219                                 } else { panic!("Unexpected event!"); }
8220                         },
8221                         _ => panic!("Unexpected event type!"),
8222                 };
8223
8224                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8225                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8226                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8227                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8228                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8229                         check_added_monitors!(nodes[2], 1);
8230
8231                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8232                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8233                         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &send_event.commitment_msg) {
8234                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8235                         } else { panic!(); }
8236                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8237                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8238                         (Some(payment_preimage_4), Some(payment_hash_4))
8239                 } else { (None, None) };
8240
8241                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8242                 // update_add update.
8243                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8244                 nodes[1].node.test_restore_channel_monitor();
8245                 check_added_monitors!(nodes[1], 2);
8246
8247                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8248                 if test_ignore_second_cs {
8249                         assert_eq!(events_3.len(), 3);
8250                 } else {
8251                         assert_eq!(events_3.len(), 2);
8252                 }
8253
8254                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8255                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8256                 let messages_a = match events_3.pop().unwrap() {
8257                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8258                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8259                                 assert!(updates.update_fulfill_htlcs.is_empty());
8260                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8261                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8262                                 assert!(updates.update_add_htlcs.is_empty());
8263                                 assert!(updates.update_fee.is_none());
8264                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8265                         },
8266                         _ => panic!("Unexpected event type!"),
8267                 };
8268                 let raa = if test_ignore_second_cs {
8269                         match events_3.remove(1) {
8270                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8271                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8272                                         Some(msg.clone())
8273                                 },
8274                                 _ => panic!("Unexpected event"),
8275                         }
8276                 } else { None };
8277                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8278                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8279
8280                 // Now deliver the new messages...
8281
8282                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8283                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8284                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8285                 assert_eq!(events_4.len(), 1);
8286                 if let Event::PaymentFailed { payment_hash, rejected_by_dest } = events_4[0] {
8287                         assert_eq!(payment_hash, payment_hash_1);
8288                         assert!(rejected_by_dest);
8289                 } else { panic!("Unexpected event!"); }
8290
8291                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8292                 if test_ignore_second_cs {
8293                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8294                         check_added_monitors!(nodes[2], 1);
8295                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8296                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8297                         check_added_monitors!(nodes[2], 1);
8298                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8299                         assert!(bs_cs.update_add_htlcs.is_empty());
8300                         assert!(bs_cs.update_fail_htlcs.is_empty());
8301                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8302                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8303                         assert!(bs_cs.update_fee.is_none());
8304
8305                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8306                         check_added_monitors!(nodes[1], 1);
8307                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8308                         assert!(as_cs.update_add_htlcs.is_empty());
8309                         assert!(as_cs.update_fail_htlcs.is_empty());
8310                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8311                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8312                         assert!(as_cs.update_fee.is_none());
8313
8314                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8315                         check_added_monitors!(nodes[1], 1);
8316                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8317
8318                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8319                         check_added_monitors!(nodes[2], 1);
8320                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8321
8322                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8323                         check_added_monitors!(nodes[2], 1);
8324                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8325
8326                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8327                         check_added_monitors!(nodes[1], 1);
8328                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8329                 } else {
8330                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8331                 }
8332
8333                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8334                 assert_eq!(events_5.len(), 1);
8335                 match events_5[0] {
8336                         Event::PendingHTLCsForwardable { .. } => { },
8337                         _ => panic!("Unexpected event"),
8338                 };
8339
8340                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8341                 nodes[2].node.process_pending_htlc_forwards();
8342
8343                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8344                 assert_eq!(events_6.len(), 1);
8345                 match events_6[0] {
8346                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8347                         _ => panic!("Unexpected event"),
8348                 };
8349
8350                 if test_ignore_second_cs {
8351                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8352                         assert_eq!(events_7.len(), 1);
8353                         match events_7[0] {
8354                                 Event::PendingHTLCsForwardable { .. } => { },
8355                                 _ => panic!("Unexpected event"),
8356                         };
8357
8358                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8359                         nodes[1].node.process_pending_htlc_forwards();
8360                         check_added_monitors!(nodes[1], 1);
8361
8362                         send_event = SendEvent::from_node(&nodes[1]);
8363                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8364                         assert_eq!(send_event.msgs.len(), 1);
8365                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8366                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8367
8368                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8369                         assert_eq!(events_8.len(), 1);
8370                         match events_8[0] {
8371                                 Event::PendingHTLCsForwardable { .. } => { },
8372                                 _ => panic!("Unexpected event"),
8373                         };
8374
8375                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8376                         nodes[0].node.process_pending_htlc_forwards();
8377
8378                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8379                         assert_eq!(events_9.len(), 1);
8380                         match events_9[0] {
8381                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8382                                 _ => panic!("Unexpected event"),
8383                         };
8384                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8385                 }
8386
8387                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8388         }
8389
8390         #[test]
8391         fn test_monitor_update_fail_raa() {
8392                 do_test_monitor_update_fail_raa(false);
8393                 do_test_monitor_update_fail_raa(true);
8394         }
8395
8396         #[test]
8397         fn test_monitor_update_fail_reestablish() {
8398                 // Simple test for message retransmission after monitor update failure on
8399                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8400                 // HTLCs).
8401                 let mut nodes = create_network(3);
8402                 create_announced_chan_between_nodes(&nodes, 0, 1);
8403                 create_announced_chan_between_nodes(&nodes, 1, 2);
8404
8405                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8406
8407                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8408                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8409
8410                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8411                 check_added_monitors!(nodes[2], 1);
8412                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8413                 assert!(updates.update_add_htlcs.is_empty());
8414                 assert!(updates.update_fail_htlcs.is_empty());
8415                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8416                 assert!(updates.update_fee.is_none());
8417                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8418                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8419                 check_added_monitors!(nodes[1], 1);
8420                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8421                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8422
8423                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8424                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8425                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8426
8427                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8428                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8429
8430                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8431
8432                 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap_err() {
8433                         assert_eq!(err, "Failed to update ChannelMonitor");
8434                 } else { panic!(); }
8435                 check_added_monitors!(nodes[1], 1);
8436
8437                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8438                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8439
8440                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8441                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8442
8443                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8444                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8445
8446                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8447
8448                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8449                 check_added_monitors!(nodes[1], 0);
8450                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8451
8452                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8453                 nodes[1].node.test_restore_channel_monitor();
8454                 check_added_monitors!(nodes[1], 1);
8455
8456                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8457                 assert!(updates.update_add_htlcs.is_empty());
8458                 assert!(updates.update_fail_htlcs.is_empty());
8459                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8460                 assert!(updates.update_fee.is_none());
8461                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8462                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8463                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8464
8465                 let events = nodes[0].node.get_and_clear_pending_events();
8466                 assert_eq!(events.len(), 1);
8467                 match events[0] {
8468                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8469                         _ => panic!("Unexpected event"),
8470                 }
8471         }
8472
8473         #[test]
8474         fn test_invalid_channel_announcement() {
8475                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8476                 let secp_ctx = Secp256k1::new();
8477                 let nodes = create_network(2);
8478
8479                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8480
8481                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8482                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8483                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8484                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8485
8486                 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 } );
8487
8488                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8489                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8490
8491                 let as_network_key = nodes[0].node.get_our_node_id();
8492                 let bs_network_key = nodes[1].node.get_our_node_id();
8493
8494                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8495
8496                 let mut chan_announcement;
8497
8498                 macro_rules! dummy_unsigned_msg {
8499                         () => {
8500                                 msgs::UnsignedChannelAnnouncement {
8501                                         features: msgs::GlobalFeatures::new(),
8502                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8503                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8504                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8505                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8506                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8507                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8508                                         excess_data: Vec::new(),
8509                                 };
8510                         }
8511                 }
8512
8513                 macro_rules! sign_msg {
8514                         ($unsigned_msg: expr) => {
8515                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8516                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8517                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8518                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8519                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8520                                 chan_announcement = msgs::ChannelAnnouncement {
8521                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8522                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8523                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8524                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8525                                         contents: $unsigned_msg
8526                                 }
8527                         }
8528                 }
8529
8530                 let unsigned_msg = dummy_unsigned_msg!();
8531                 sign_msg!(unsigned_msg);
8532                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8533                 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 } );
8534
8535                 // Configured with Network::Testnet
8536                 let mut unsigned_msg = dummy_unsigned_msg!();
8537                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8538                 sign_msg!(unsigned_msg);
8539                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8540
8541                 let mut unsigned_msg = dummy_unsigned_msg!();
8542                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8543                 sign_msg!(unsigned_msg);
8544                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8545         }
8546
8547         struct VecWriter(Vec<u8>);
8548         impl Writer for VecWriter {
8549                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8550                         self.0.extend_from_slice(buf);
8551                         Ok(())
8552                 }
8553                 fn size_hint(&mut self, size: usize) {
8554                         self.0.reserve_exact(size);
8555                 }
8556         }
8557
8558         #[test]
8559         fn test_no_txn_manager_serialize_deserialize() {
8560                 let mut nodes = create_network(2);
8561
8562                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8563
8564                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8565
8566                 let nodes_0_serialized = nodes[0].node.encode();
8567                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8568                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8569
8570                 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8571                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8572                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8573                 assert!(chan_0_monitor_read.is_empty());
8574
8575                 let mut nodes_0_read = &nodes_0_serialized[..];
8576                 let config = UserConfig::new();
8577                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8578                 let (_, nodes_0_deserialized) = {
8579                         let mut channel_monitors = HashMap::new();
8580                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8581                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8582                                 default_config: config,
8583                                 keys_manager,
8584                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8585                                 monitor: nodes[0].chan_monitor.clone(),
8586                                 chain_monitor: nodes[0].chain_monitor.clone(),
8587                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8588                                 logger: Arc::new(test_utils::TestLogger::new()),
8589                                 channel_monitors: &channel_monitors,
8590                         }).unwrap()
8591                 };
8592                 assert!(nodes_0_read.is_empty());
8593
8594                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8595                 nodes[0].node = Arc::new(nodes_0_deserialized);
8596                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8597                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8598                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8599                 check_added_monitors!(nodes[0], 1);
8600
8601                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8602                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8603                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8604                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8605
8606                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8607                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8608                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8609                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8610
8611                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8612                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8613                 for node in nodes.iter() {
8614                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8615                         node.router.handle_channel_update(&as_update).unwrap();
8616                         node.router.handle_channel_update(&bs_update).unwrap();
8617                 }
8618
8619                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8620         }
8621
8622         #[test]
8623         fn test_simple_manager_serialize_deserialize() {
8624                 let mut nodes = create_network(2);
8625                 create_announced_chan_between_nodes(&nodes, 0, 1);
8626
8627                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8628                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8629
8630                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8631
8632                 let nodes_0_serialized = nodes[0].node.encode();
8633                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8634                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8635
8636                 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8637                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8638                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8639                 assert!(chan_0_monitor_read.is_empty());
8640
8641                 let mut nodes_0_read = &nodes_0_serialized[..];
8642                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8643                 let (_, nodes_0_deserialized) = {
8644                         let mut channel_monitors = HashMap::new();
8645                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8646                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8647                                 default_config: UserConfig::new(),
8648                                 keys_manager,
8649                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8650                                 monitor: nodes[0].chan_monitor.clone(),
8651                                 chain_monitor: nodes[0].chain_monitor.clone(),
8652                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8653                                 logger: Arc::new(test_utils::TestLogger::new()),
8654                                 channel_monitors: &channel_monitors,
8655                         }).unwrap()
8656                 };
8657                 assert!(nodes_0_read.is_empty());
8658
8659                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8660                 nodes[0].node = Arc::new(nodes_0_deserialized);
8661                 check_added_monitors!(nodes[0], 1);
8662
8663                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8664
8665                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8666                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8667         }
8668
8669         #[test]
8670         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8671                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8672                 let mut nodes = create_network(4);
8673                 create_announced_chan_between_nodes(&nodes, 0, 1);
8674                 create_announced_chan_between_nodes(&nodes, 2, 0);
8675                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8676
8677                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8678
8679                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8680                 let nodes_0_serialized = nodes[0].node.encode();
8681
8682                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8683                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8684                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8685                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8686
8687                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8688                 // nodes[3])
8689                 let mut node_0_monitors_serialized = Vec::new();
8690                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8691                         let mut writer = VecWriter(Vec::new());
8692                         monitor.1.write_for_disk(&mut writer).unwrap();
8693                         node_0_monitors_serialized.push(writer.0);
8694                 }
8695
8696                 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
8697                 let mut node_0_monitors = Vec::new();
8698                 for serialized in node_0_monitors_serialized.iter() {
8699                         let mut read = &serialized[..];
8700                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8701                         assert!(read.is_empty());
8702                         node_0_monitors.push(monitor);
8703                 }
8704
8705                 let mut nodes_0_read = &nodes_0_serialized[..];
8706                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8707                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8708                         default_config: UserConfig::new(),
8709                         keys_manager,
8710                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8711                         monitor: nodes[0].chan_monitor.clone(),
8712                         chain_monitor: nodes[0].chain_monitor.clone(),
8713                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8714                         logger: Arc::new(test_utils::TestLogger::new()),
8715                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8716                 }).unwrap();
8717                 assert!(nodes_0_read.is_empty());
8718
8719                 { // Channel close should result in a commitment tx and an HTLC tx
8720                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8721                         assert_eq!(txn.len(), 2);
8722                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8723                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8724                 }
8725
8726                 for monitor in node_0_monitors.drain(..) {
8727                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8728                         check_added_monitors!(nodes[0], 1);
8729                 }
8730                 nodes[0].node = Arc::new(nodes_0_deserialized);
8731
8732                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8733                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8734                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8735                 //... and we can even still claim the payment!
8736                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8737
8738                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8739                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8740                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8741                 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
8742                         assert_eq!(msg.channel_id, channel_id);
8743                 } else { panic!("Unexpected result"); }
8744         }
8745
8746         macro_rules! check_spendable_outputs {
8747                 ($node: expr, $der_idx: expr) => {
8748                         {
8749                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8750                                 let mut txn = Vec::new();
8751                                 for event in events {
8752                                         match event {
8753                                                 Event::SpendableOutputs { ref outputs } => {
8754                                                         for outp in outputs {
8755                                                                 match *outp {
8756                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8757                                                                                 let input = TxIn {
8758                                                                                         previous_output: outpoint.clone(),
8759                                                                                         script_sig: Script::new(),
8760                                                                                         sequence: 0,
8761                                                                                         witness: Vec::new(),
8762                                                                                 };
8763                                                                                 let outp = TxOut {
8764                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8765                                                                                         value: output.value,
8766                                                                                 };
8767                                                                                 let mut spend_tx = Transaction {
8768                                                                                         version: 2,
8769                                                                                         lock_time: 0,
8770                                                                                         input: vec![input],
8771                                                                                         output: vec![outp],
8772                                                                                 };
8773                                                                                 let secp_ctx = Secp256k1::new();
8774                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8775                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8776                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8777                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8778                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8779                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8780                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8781                                                                                 txn.push(spend_tx);
8782                                                                         },
8783                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8784                                                                                 let input = TxIn {
8785                                                                                         previous_output: outpoint.clone(),
8786                                                                                         script_sig: Script::new(),
8787                                                                                         sequence: *to_self_delay as u32,
8788                                                                                         witness: Vec::new(),
8789                                                                                 };
8790                                                                                 let outp = TxOut {
8791                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8792                                                                                         value: output.value,
8793                                                                                 };
8794                                                                                 let mut spend_tx = Transaction {
8795                                                                                         version: 2,
8796                                                                                         lock_time: 0,
8797                                                                                         input: vec![input],
8798                                                                                         output: vec![outp],
8799                                                                                 };
8800                                                                                 let secp_ctx = Secp256k1::new();
8801                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8802                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8803                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8804                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8805                                                                                 spend_tx.input[0].witness.push(vec!(0));
8806                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8807                                                                                 txn.push(spend_tx);
8808                                                                         },
8809                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8810                                                                                 let secp_ctx = Secp256k1::new();
8811                                                                                 let input = TxIn {
8812                                                                                         previous_output: outpoint.clone(),
8813                                                                                         script_sig: Script::new(),
8814                                                                                         sequence: 0,
8815                                                                                         witness: Vec::new(),
8816                                                                                 };
8817                                                                                 let outp = TxOut {
8818                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8819                                                                                         value: output.value,
8820                                                                                 };
8821                                                                                 let mut spend_tx = Transaction {
8822                                                                                         version: 2,
8823                                                                                         lock_time: 0,
8824                                                                                         input: vec![input],
8825                                                                                         output: vec![outp.clone()],
8826                                                                                 };
8827                                                                                 let secret = {
8828                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8829                                                                                                 Ok(master_key) => {
8830                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8831                                                                                                                 Ok(key) => key,
8832                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8833                                                                                                         }
8834                                                                                                 }
8835                                                                                                 Err(_) => panic!("Your rng is busted"),
8836                                                                                         }
8837                                                                                 };
8838                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8839                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8840                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8841                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8842                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8843                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8844                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8845                                                                                 txn.push(spend_tx);
8846                                                                         },
8847                                                                 }
8848                                                         }
8849                                                 },
8850                                                 _ => panic!("Unexpected event"),
8851                                         };
8852                                 }
8853                                 txn
8854                         }
8855                 }
8856         }
8857
8858         #[test]
8859         fn test_claim_sizeable_push_msat() {
8860                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8861                 let nodes = create_network(2);
8862
8863                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8864                 nodes[1].node.force_close_channel(&chan.2);
8865                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8866                 match events[0] {
8867                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8868                         _ => panic!("Unexpected event"),
8869                 }
8870                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8871                 assert_eq!(node_txn.len(), 1);
8872                 check_spends!(node_txn[0], chan.3.clone());
8873                 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
8874
8875                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8876                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8877                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8878                 assert_eq!(spend_txn.len(), 1);
8879                 check_spends!(spend_txn[0], node_txn[0].clone());
8880         }
8881
8882         #[test]
8883         fn test_claim_on_remote_sizeable_push_msat() {
8884                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8885                 // to_remote output is encumbered by a P2WPKH
8886
8887                 let nodes = create_network(2);
8888
8889                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8890                 nodes[0].node.force_close_channel(&chan.2);
8891                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8892                 match events[0] {
8893                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8894                         _ => panic!("Unexpected event"),
8895                 }
8896                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8897                 assert_eq!(node_txn.len(), 1);
8898                 check_spends!(node_txn[0], chan.3.clone());
8899                 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
8900
8901                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8902                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8903                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8904                 match events[0] {
8905                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8906                         _ => panic!("Unexpected event"),
8907                 }
8908                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8909                 assert_eq!(spend_txn.len(), 2);
8910                 assert_eq!(spend_txn[0], spend_txn[1]);
8911                 check_spends!(spend_txn[0], node_txn[0].clone());
8912         }
8913
8914         #[test]
8915         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8916                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8917                 // to_remote output is encumbered by a P2WPKH
8918
8919                 let nodes = create_network(2);
8920
8921                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8922                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8923                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8924                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8925                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8926
8927                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8928                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8929                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8930                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8931                 match events[0] {
8932                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8933                         _ => panic!("Unexpected event"),
8934                 }
8935                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8936                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8937                 assert_eq!(spend_txn.len(), 4);
8938                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8939                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8940                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8941                 check_spends!(spend_txn[1], node_txn[0].clone());
8942         }
8943
8944         #[test]
8945         fn test_static_spendable_outputs_preimage_tx() {
8946                 let nodes = create_network(2);
8947
8948                 // Create some initial channels
8949                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8950
8951                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8952
8953                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8954                 assert_eq!(commitment_tx[0].input.len(), 1);
8955                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8956
8957                 // Settle A's commitment tx on B's chain
8958                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8959                 assert!(nodes[1].node.claim_funds(payment_preimage));
8960                 check_added_monitors!(nodes[1], 1);
8961                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8962                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8963                 match events[0] {
8964                         MessageSendEvent::UpdateHTLCs { .. } => {},
8965                         _ => panic!("Unexpected event"),
8966                 }
8967                 match events[1] {
8968                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8969                         _ => panic!("Unexepected event"),
8970                 }
8971
8972                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8973                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8974                 check_spends!(node_txn[0], commitment_tx[0].clone());
8975                 assert_eq!(node_txn[0], node_txn[2]);
8976                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8977                 check_spends!(node_txn[1], chan_1.3.clone());
8978
8979                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8980                 assert_eq!(spend_txn.len(), 2);
8981                 assert_eq!(spend_txn[0], spend_txn[1]);
8982                 check_spends!(spend_txn[0], node_txn[0].clone());
8983         }
8984
8985         #[test]
8986         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
8987                 let nodes = create_network(2);
8988
8989                 // Create some initial channels
8990                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8991
8992                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8993                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
8994                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8995                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
8996
8997                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8998
8999                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9000                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9001                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9002                 match events[0] {
9003                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9004                         _ => panic!("Unexpected event"),
9005                 }
9006                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9007                 assert_eq!(node_txn.len(), 3);
9008                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9009                 assert_eq!(node_txn[0].input.len(), 2);
9010                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9011
9012                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9013                 assert_eq!(spend_txn.len(), 2);
9014                 assert_eq!(spend_txn[0], spend_txn[1]);
9015                 check_spends!(spend_txn[0], node_txn[0].clone());
9016         }
9017
9018         #[test]
9019         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9020                 let nodes = create_network(2);
9021
9022                 // Create some initial channels
9023                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9024
9025                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9026                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9027                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9028                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9029
9030                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9031
9032                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9033                 // A will generate HTLC-Timeout from revoked commitment tx
9034                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9035                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9036                 match events[0] {
9037                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9038                         _ => panic!("Unexpected event"),
9039                 }
9040                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9041                 assert_eq!(revoked_htlc_txn.len(), 3);
9042                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9043                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9044                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9045                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9046                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9047
9048                 // B will generate justice tx from A's revoked commitment/HTLC tx
9049                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9050                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9051                 match events[0] {
9052                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9053                         _ => panic!("Unexpected event"),
9054                 }
9055
9056                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9057                 assert_eq!(node_txn.len(), 4);
9058                 assert_eq!(node_txn[3].input.len(), 1);
9059                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9060
9061                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9062                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9063                 assert_eq!(spend_txn.len(), 3);
9064                 assert_eq!(spend_txn[0], spend_txn[1]);
9065                 check_spends!(spend_txn[0], node_txn[0].clone());
9066                 check_spends!(spend_txn[2], node_txn[3].clone());
9067         }
9068
9069         #[test]
9070         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9071                 let nodes = create_network(2);
9072
9073                 // Create some initial channels
9074                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9075
9076                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9077                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9078                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9079                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9080
9081                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9082
9083                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9084                 // B will generate HTLC-Success from revoked commitment tx
9085                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9086                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9087                 match events[0] {
9088                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9089                         _ => panic!("Unexpected event"),
9090                 }
9091                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9092
9093                 assert_eq!(revoked_htlc_txn.len(), 3);
9094                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9095                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9096                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9097                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9098
9099                 // A will generate justice tx from B's revoked commitment/HTLC tx
9100                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9101                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9102                 match events[0] {
9103                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9104                         _ => panic!("Unexpected event"),
9105                 }
9106
9107                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9108                 assert_eq!(node_txn.len(), 4);
9109                 assert_eq!(node_txn[3].input.len(), 1);
9110                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9111
9112                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9113                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9114                 assert_eq!(spend_txn.len(), 5);
9115                 assert_eq!(spend_txn[0], spend_txn[2]);
9116                 assert_eq!(spend_txn[1], spend_txn[3]);
9117                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9118                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9119                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9120         }
9121
9122         #[test]
9123         fn test_onchain_to_onchain_claim() {
9124                 // Test that in case of channel closure, we detect the state of output thanks to
9125                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9126                 // First, have C claim an HTLC against its own latest commitment transaction.
9127                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9128                 // channel.
9129                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9130                 // gets broadcast.
9131
9132                 let nodes = create_network(3);
9133
9134                 // Create some initial channels
9135                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9136                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9137
9138                 // Rebalance the network a bit by relaying one payment through all the channels ...
9139                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9140                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9141
9142                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9143                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9144                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9145                 check_spends!(commitment_tx[0], chan_2.3.clone());
9146                 nodes[2].node.claim_funds(payment_preimage);
9147                 check_added_monitors!(nodes[2], 1);
9148                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9149                 assert!(updates.update_add_htlcs.is_empty());
9150                 assert!(updates.update_fail_htlcs.is_empty());
9151                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9152                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9153
9154                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9155                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9156                 assert_eq!(events.len(), 1);
9157                 match events[0] {
9158                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9159                         _ => panic!("Unexpected event"),
9160                 }
9161
9162                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9163                 assert_eq!(c_txn.len(), 3);
9164                 assert_eq!(c_txn[0], c_txn[2]);
9165                 assert_eq!(commitment_tx[0], c_txn[1]);
9166                 check_spends!(c_txn[1], chan_2.3.clone());
9167                 check_spends!(c_txn[2], c_txn[1].clone());
9168                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9169                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9170                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9171                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9172
9173                 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
9174                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9175                 {
9176                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9177                         assert_eq!(b_txn.len(), 4);
9178                         assert_eq!(b_txn[0], b_txn[3]);
9179                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9180                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9181                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9182                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9183                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9184                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9185                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9186                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9187                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9188                         b_txn.clear();
9189                 }
9190                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9191                 check_added_monitors!(nodes[1], 1);
9192                 match msg_events[0] {
9193                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9194                         _ => panic!("Unexpected event"),
9195                 }
9196                 match msg_events[1] {
9197                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
9198                                 assert!(update_add_htlcs.is_empty());
9199                                 assert!(update_fail_htlcs.is_empty());
9200                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9201                                 assert!(update_fail_malformed_htlcs.is_empty());
9202                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9203                         },
9204                         _ => panic!("Unexpected event"),
9205                 };
9206                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9207                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9208                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9209                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9210                 assert_eq!(b_txn.len(), 3);
9211                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9212                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9213                 check_spends!(b_txn[0], commitment_tx[0].clone());
9214                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9215                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9216                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9217                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9218                 match msg_events[0] {
9219                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9220                         _ => panic!("Unexpected event"),
9221                 }
9222         }
9223
9224         #[test]
9225         fn test_duplicate_payment_hash_one_failure_one_success() {
9226                 // Topology : A --> B --> C
9227                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9228                 let mut nodes = create_network(3);
9229
9230                 create_announced_chan_between_nodes(&nodes, 0, 1);
9231                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9232
9233                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9234                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9235                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9236
9237                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9238                 assert_eq!(commitment_txn[0].input.len(), 1);
9239                 check_spends!(commitment_txn[0], chan_2.3.clone());
9240
9241                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9242                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9243                 let htlc_timeout_tx;
9244                 { // Extract one of the two HTLC-Timeout transaction
9245                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9246                         assert_eq!(node_txn.len(), 7);
9247                         assert_eq!(node_txn[0], node_txn[5]);
9248                         assert_eq!(node_txn[1], node_txn[6]);
9249                         check_spends!(node_txn[0], commitment_txn[0].clone());
9250                         assert_eq!(node_txn[0].input.len(), 1);
9251                         check_spends!(node_txn[1], commitment_txn[0].clone());
9252                         assert_eq!(node_txn[1].input.len(), 1);
9253                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9254                         check_spends!(node_txn[2], chan_2.3.clone());
9255                         check_spends!(node_txn[3], node_txn[2].clone());
9256                         check_spends!(node_txn[4], node_txn[2].clone());
9257                         htlc_timeout_tx = node_txn[1].clone();
9258                 }
9259
9260                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9261                 match events[0] {
9262                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9263                         _ => panic!("Unexepected event"),
9264                 }
9265
9266                 nodes[2].node.claim_funds(our_payment_preimage);
9267                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9268                 check_added_monitors!(nodes[2], 2);
9269                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9270                 match events[0] {
9271                         MessageSendEvent::UpdateHTLCs { .. } => {},
9272                         _ => panic!("Unexpected event"),
9273                 }
9274                 match events[1] {
9275                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9276                         _ => panic!("Unexepected event"),
9277                 }
9278                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9279                 assert_eq!(htlc_success_txn.len(), 5);
9280                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9281                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9282                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9283                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9284                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9285                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9286                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9287                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9288                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9289                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9290
9291                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9292                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9293                 assert!(htlc_updates.update_add_htlcs.is_empty());
9294                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9295                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9296                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9297                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9298                 check_added_monitors!(nodes[1], 1);
9299
9300                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9301                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9302                 {
9303                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9304                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9305                         assert_eq!(events.len(), 1);
9306                         match events[0] {
9307                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9308                                 },
9309                                 _ => { panic!("Unexpected event"); }
9310                         }
9311                 }
9312                 let events = nodes[0].node.get_and_clear_pending_events();
9313                 match events[0] {
9314                         Event::PaymentFailed { ref payment_hash, .. } => {
9315                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9316                         }
9317                         _ => panic!("Unexpected event"),
9318                 }
9319
9320                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9321                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9322                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9323                 assert!(updates.update_add_htlcs.is_empty());
9324                 assert!(updates.update_fail_htlcs.is_empty());
9325                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9326                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9327                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9328                 check_added_monitors!(nodes[1], 1);
9329
9330                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9331                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9332
9333                 let events = nodes[0].node.get_and_clear_pending_events();
9334                 match events[0] {
9335                         Event::PaymentSent { ref payment_preimage } => {
9336                                 assert_eq!(*payment_preimage, our_payment_preimage);
9337                         }
9338                         _ => panic!("Unexpected event"),
9339                 }
9340         }
9341
9342         #[test]
9343         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9344                 let nodes = create_network(2);
9345
9346                 // Create some initial channels
9347                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9348
9349                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9350                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9351                 assert_eq!(local_txn[0].input.len(), 1);
9352                 check_spends!(local_txn[0], chan_1.3.clone());
9353
9354                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9355                 nodes[1].node.claim_funds(payment_preimage);
9356                 check_added_monitors!(nodes[1], 1);
9357                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9358                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9359                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9360                 match events[0] {
9361                         MessageSendEvent::UpdateHTLCs { .. } => {},
9362                         _ => panic!("Unexpected event"),
9363                 }
9364                 match events[1] {
9365                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9366                         _ => panic!("Unexepected event"),
9367                 }
9368                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9369                 assert_eq!(node_txn[0].input.len(), 1);
9370                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9371                 check_spends!(node_txn[0], local_txn[0].clone());
9372
9373                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9374                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9375                 assert_eq!(spend_txn.len(), 2);
9376                 check_spends!(spend_txn[0], node_txn[0].clone());
9377                 check_spends!(spend_txn[1], node_txn[2].clone());
9378         }
9379
9380         #[test]
9381         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9382                 let nodes = create_network(2);
9383
9384                 // Create some initial channels
9385                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9386
9387                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9388                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9389                 assert_eq!(local_txn[0].input.len(), 1);
9390                 check_spends!(local_txn[0], chan_1.3.clone());
9391
9392                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9393                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9394                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9395                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9396                 match events[0] {
9397                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9398                         _ => panic!("Unexepected event"),
9399                 }
9400                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9401                 assert_eq!(node_txn[0].input.len(), 1);
9402                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9403                 check_spends!(node_txn[0], local_txn[0].clone());
9404
9405                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9406                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9407                 assert_eq!(spend_txn.len(), 8);
9408                 assert_eq!(spend_txn[0], spend_txn[2]);
9409                 assert_eq!(spend_txn[0], spend_txn[4]);
9410                 assert_eq!(spend_txn[0], spend_txn[6]);
9411                 assert_eq!(spend_txn[1], spend_txn[3]);
9412                 assert_eq!(spend_txn[1], spend_txn[5]);
9413                 assert_eq!(spend_txn[1], spend_txn[7]);
9414                 check_spends!(spend_txn[0], local_txn[0].clone());
9415                 check_spends!(spend_txn[1], node_txn[0].clone());
9416         }
9417
9418         #[test]
9419         fn test_static_output_closing_tx() {
9420                 let nodes = create_network(2);
9421
9422                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9423
9424                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9425                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9426
9427                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9428                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9429                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9430                 assert_eq!(spend_txn.len(), 1);
9431                 check_spends!(spend_txn[0], closing_tx.clone());
9432
9433                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9434                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9435                 assert_eq!(spend_txn.len(), 1);
9436                 check_spends!(spend_txn[0], closing_tx);
9437         }
9438 }