Rewrite most of process_onion_failure
[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, HTLC_FAIL_ANTI_REORG_DELAY};
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 use util::errors;
38
39 use crypto;
40 use crypto::mac::{Mac,MacResult};
41 use crypto::hmac::Hmac;
42 use crypto::digest::Digest;
43 use crypto::symmetriccipher::SynchronousStreamCipher;
44
45 use std::{cmp, ptr, mem};
46 use std::collections::{HashMap, hash_map, HashSet};
47 use std::io::Cursor;
48 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
49 use std::sync::atomic::{AtomicUsize, Ordering};
50 use std::time::{Instant,Duration};
51
52 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
53 ///
54 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
55 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
56 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
57 ///
58 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
59 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
60 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
61 /// the HTLC backwards along the relevant path).
62 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
63 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
64 mod channel_held_info {
65         use ln::msgs;
66         use ln::router::Route;
67         use ln::channelmanager::PaymentHash;
68         use secp256k1::key::SecretKey;
69
70         /// Stores the info we will need to send when we want to forward an HTLC onwards
71         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
72         pub struct PendingForwardHTLCInfo {
73                 pub(super) onion_packet: Option<msgs::OnionPacket>,
74                 pub(super) incoming_shared_secret: [u8; 32],
75                 pub(super) payment_hash: PaymentHash,
76                 pub(super) short_channel_id: u64,
77                 pub(super) amt_to_forward: u64,
78                 pub(super) outgoing_cltv_value: u32,
79         }
80
81         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
82         pub enum HTLCFailureMsg {
83                 Relay(msgs::UpdateFailHTLC),
84                 Malformed(msgs::UpdateFailMalformedHTLC),
85         }
86
87         /// Stores whether we can't forward an HTLC or relevant forwarding info
88         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
89         pub enum PendingHTLCStatus {
90                 Forward(PendingForwardHTLCInfo),
91                 Fail(HTLCFailureMsg),
92         }
93
94         /// Tracks the inbound corresponding to an outbound HTLC
95         #[derive(Clone, PartialEq)]
96         pub struct HTLCPreviousHopData {
97                 pub(super) short_channel_id: u64,
98                 pub(super) htlc_id: u64,
99                 pub(super) incoming_packet_shared_secret: [u8; 32],
100         }
101
102         /// Tracks the inbound corresponding to an outbound HTLC
103         #[derive(Clone, PartialEq)]
104         pub enum HTLCSource {
105                 PreviousHopData(HTLCPreviousHopData),
106                 OutboundRoute {
107                         route: Route,
108                         session_priv: SecretKey,
109                         /// Technically we can recalculate this from the route, but we cache it here to avoid
110                         /// doing a double-pass on route when we get a failure back
111                         first_hop_htlc_msat: u64,
112                 },
113         }
114         #[cfg(test)]
115         impl HTLCSource {
116                 pub fn dummy() -> Self {
117                         HTLCSource::OutboundRoute {
118                                 route: Route { hops: Vec::new() },
119                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
120                                 first_hop_htlc_msat: 0,
121                         }
122                 }
123         }
124
125         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126         pub(crate) enum HTLCFailReason {
127                 ErrorPacket {
128                         err: msgs::OnionErrorPacket,
129                 },
130                 Reason {
131                         failure_code: u16,
132                         data: Vec<u8>,
133                 }
134         }
135 }
136 pub(super) use self::channel_held_info::*;
137
138 /// payment_hash type, use to cross-lock hop
139 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
140 pub struct PaymentHash(pub [u8;32]);
141 /// payment_preimage type, use to route payment between hop
142 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
143 pub struct PaymentPreimage(pub [u8;32]);
144
145 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
146
147 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
148 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
149 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
150 /// channel_state lock. We then return the set of things that need to be done outside the lock in
151 /// this struct and call handle_error!() on it.
152
153 struct MsgHandleErrInternal {
154         err: msgs::HandleError,
155         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
156 }
157 impl MsgHandleErrInternal {
158         #[inline]
159         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
160                 Self {
161                         err: HandleError {
162                                 err,
163                                 action: Some(msgs::ErrorAction::SendErrorMessage {
164                                         msg: msgs::ErrorMessage {
165                                                 channel_id,
166                                                 data: err.to_string()
167                                         },
168                                 }),
169                         },
170                         shutdown_finish: None,
171                 }
172         }
173         #[inline]
174         fn from_no_close(err: msgs::HandleError) -> Self {
175                 Self { err, shutdown_finish: None }
176         }
177         #[inline]
178         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
179                 Self {
180                         err: HandleError {
181                                 err,
182                                 action: Some(msgs::ErrorAction::SendErrorMessage {
183                                         msg: msgs::ErrorMessage {
184                                                 channel_id,
185                                                 data: err.to_string()
186                                         },
187                                 }),
188                         },
189                         shutdown_finish: Some((shutdown_res, channel_update)),
190                 }
191         }
192         #[inline]
193         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
194                 Self {
195                         err: match err {
196                                 ChannelError::Ignore(msg) => HandleError {
197                                         err: msg,
198                                         action: Some(msgs::ErrorAction::IgnoreError),
199                                 },
200                                 ChannelError::Close(msg) => HandleError {
201                                         err: msg,
202                                         action: Some(msgs::ErrorAction::SendErrorMessage {
203                                                 msg: msgs::ErrorMessage {
204                                                         channel_id,
205                                                         data: msg.to_string()
206                                                 },
207                                         }),
208                                 },
209                         },
210                         shutdown_finish: None,
211                 }
212         }
213 }
214
215 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
216 /// after a PaymentReceived event.
217 #[derive(PartialEq)]
218 pub enum PaymentFailReason {
219         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
220         PreimageUnknown,
221         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
222         AmountMismatch,
223 }
224
225 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
226 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
227 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
228 /// probably increase this significantly.
229 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
230
231 struct HTLCForwardInfo {
232         prev_short_channel_id: u64,
233         prev_htlc_id: u64,
234         forward_info: PendingForwardHTLCInfo,
235 }
236
237 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
238 /// be sent in the order they appear in the return value, however sometimes the order needs to be
239 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
240 /// they were originally sent). In those cases, this enum is also returned.
241 #[derive(Clone, PartialEq)]
242 pub(super) enum RAACommitmentOrder {
243         /// Send the CommitmentUpdate messages first
244         CommitmentFirst,
245         /// Send the RevokeAndACK message first
246         RevokeAndACKFirst,
247 }
248
249 struct ChannelHolder {
250         by_id: HashMap<[u8; 32], Channel>,
251         short_to_id: HashMap<u64, [u8; 32]>,
252         next_forward: Instant,
253         /// short channel id -> forward infos. Key of 0 means payments received
254         /// Note that while this is held in the same mutex as the channels themselves, no consistency
255         /// guarantees are made about there existing a channel with the short id here, nor the short
256         /// ids in the PendingForwardHTLCInfo!
257         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
258         /// Note that while this is held in the same mutex as the channels themselves, no consistency
259         /// guarantees are made about the channels given here actually existing anymore by the time you
260         /// go to read them!
261         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
263         /// for broadcast messages, where ordering isn't as strict).
264         pending_msg_events: Vec<events::MessageSendEvent>,
265 }
266 struct MutChannelHolder<'a> {
267         by_id: &'a mut HashMap<[u8; 32], Channel>,
268         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
269         next_forward: &'a mut Instant,
270         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
271         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
272         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
273 }
274 impl ChannelHolder {
275         fn borrow_parts(&mut self) -> MutChannelHolder {
276                 MutChannelHolder {
277                         by_id: &mut self.by_id,
278                         short_to_id: &mut self.short_to_id,
279                         next_forward: &mut self.next_forward,
280                         forward_htlcs: &mut self.forward_htlcs,
281                         claimable_htlcs: &mut self.claimable_htlcs,
282                         pending_msg_events: &mut self.pending_msg_events,
283                 }
284         }
285 }
286
287 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
288 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
289
290 /// Manager which keeps track of a number of channels and sends messages to the appropriate
291 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
292 ///
293 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
294 /// to individual Channels.
295 ///
296 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
297 /// all peers during write/read (though does not modify this instance, only the instance being
298 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
299 /// called funding_transaction_generated for outbound channels).
300 ///
301 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
302 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
303 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
304 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
305 /// the serialization process). If the deserialized version is out-of-date compared to the
306 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
307 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
308 ///
309 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
310 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
311 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
312 /// block_connected() to step towards your best block) upon deserialization before using the
313 /// object!
314 pub struct ChannelManager {
315         default_configuration: UserConfig,
316         genesis_hash: Sha256dHash,
317         fee_estimator: Arc<FeeEstimator>,
318         monitor: Arc<ManyChannelMonitor>,
319         chain_monitor: Arc<ChainWatchInterface>,
320         tx_broadcaster: Arc<BroadcasterInterface>,
321
322         latest_block_height: AtomicUsize,
323         last_block_hash: Mutex<Sha256dHash>,
324         secp_ctx: Secp256k1<secp256k1::All>,
325
326         channel_state: Mutex<ChannelHolder>,
327         our_network_key: SecretKey,
328
329         pending_events: Mutex<Vec<events::Event>>,
330         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
331         /// Essentially just when we're serializing ourselves out.
332         /// Taken first everywhere where we are making changes before any other locks.
333         total_consistency_lock: RwLock<()>,
334
335         keys_manager: Arc<KeysInterface>,
336
337         logger: Arc<Logger>,
338 }
339
340 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
341 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
342 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
343 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
344 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
345 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
346 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
347
348 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
349 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
350 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
351 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
352 // on-chain to time out the HTLC.
353 #[deny(const_err)]
354 #[allow(dead_code)]
355 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
356
357 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
358 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
359 #[deny(const_err)]
360 #[allow(dead_code)]
361 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
362
363 macro_rules! secp_call {
364         ( $res: expr, $err: expr ) => {
365                 match $res {
366                         Ok(key) => key,
367                         Err(_) => return Err($err),
368                 }
369         };
370 }
371
372 struct OnionKeys {
373         #[cfg(test)]
374         shared_secret: SharedSecret,
375         #[cfg(test)]
376         blinding_factor: [u8; 32],
377         ephemeral_pubkey: PublicKey,
378         rho: [u8; 32],
379         mu: [u8; 32],
380 }
381
382 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
383 pub struct ChannelDetails {
384         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
385         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
386         /// Note that this means this value is *not* persistent - it can change once during the
387         /// lifetime of the channel.
388         pub channel_id: [u8; 32],
389         /// The position of the funding transaction in the chain. None if the funding transaction has
390         /// not yet been confirmed and the channel fully opened.
391         pub short_channel_id: Option<u64>,
392         /// The node_id of our counterparty
393         pub remote_network_id: PublicKey,
394         /// The value, in satoshis, of this channel as appears in the funding output
395         pub channel_value_satoshis: u64,
396         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
397         pub user_id: u64,
398 }
399
400 macro_rules! handle_error {
401         ($self: ident, $internal: expr, $their_node_id: expr) => {
402                 match $internal {
403                         Ok(msg) => Ok(msg),
404                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
405                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
406                                         $self.finish_force_close_channel(shutdown_res);
407                                         if let Some(update) = update_option {
408                                                 let mut channel_state = $self.channel_state.lock().unwrap();
409                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
410                                                         msg: update
411                                                 });
412                                         }
413                                 }
414                                 Err(err)
415                         },
416                 }
417         }
418 }
419
420 macro_rules! break_chan_entry {
421         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
422                 match $res {
423                         Ok(res) => res,
424                         Err(ChannelError::Ignore(msg)) => {
425                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
426                         },
427                         Err(ChannelError::Close(msg)) => {
428                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
429                                 let (channel_id, mut chan) = $entry.remove_entry();
430                                 if let Some(short_id) = chan.get_short_channel_id() {
431                                         $channel_state.short_to_id.remove(&short_id);
432                                 }
433                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
434                         },
435                 }
436         }
437 }
438
439 macro_rules! try_chan_entry {
440         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
441                 match $res {
442                         Ok(res) => res,
443                         Err(ChannelError::Ignore(msg)) => {
444                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
445                         },
446                         Err(ChannelError::Close(msg)) => {
447                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
448                                 let (channel_id, mut chan) = $entry.remove_entry();
449                                 if let Some(short_id) = chan.get_short_channel_id() {
450                                         $channel_state.short_to_id.remove(&short_id);
451                                 }
452                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
453                         },
454                 }
455         }
456 }
457
458 macro_rules! return_monitor_err {
459         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
460                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
461         };
462         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
463                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
464                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
465         };
466         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
467                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
468         };
469         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
470                 match $err {
471                         ChannelMonitorUpdateErr::PermanentFailure => {
472                                 let (channel_id, mut chan) = $entry.remove_entry();
473                                 if let Some(short_id) = chan.get_short_channel_id() {
474                                         $channel_state.short_to_id.remove(&short_id);
475                                 }
476                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
477                                 // chain in a confused state! We need to move them into the ChannelMonitor which
478                                 // will be responsible for failing backwards once things confirm on-chain.
479                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
480                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
481                                 // us bother trying to claim it just to forward on to another peer. If we're
482                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
483                                 // given up the preimage yet, so might as well just wait until the payment is
484                                 // retried, avoiding the on-chain fees.
485                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
486                         },
487                         ChannelMonitorUpdateErr::TemporaryFailure => {
488                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
489                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
490                         },
491                 }
492         }
493 }
494
495 // Does not break in case of TemporaryFailure!
496 macro_rules! maybe_break_monitor_err {
497         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
498                 match $err {
499                         ChannelMonitorUpdateErr::PermanentFailure => {
500                                 let (channel_id, mut chan) = $entry.remove_entry();
501                                 if let Some(short_id) = chan.get_short_channel_id() {
502                                         $channel_state.short_to_id.remove(&short_id);
503                                 }
504                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
505                         },
506                         ChannelMonitorUpdateErr::TemporaryFailure => {
507                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
508                         },
509                 }
510         }
511 }
512
513 impl ChannelManager {
514         /// Constructs a new ChannelManager to hold several channels and route between them.
515         ///
516         /// This is the main "logic hub" for all channel-related actions, and implements
517         /// ChannelMessageHandler.
518         ///
519         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
520         ///
521         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
522         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> {
523                 let secp_ctx = Secp256k1::new();
524
525                 let res = Arc::new(ChannelManager {
526                         default_configuration: config.clone(),
527                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
528                         fee_estimator: feeest.clone(),
529                         monitor: monitor.clone(),
530                         chain_monitor,
531                         tx_broadcaster,
532
533                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
534                         last_block_hash: Mutex::new(Default::default()),
535                         secp_ctx,
536
537                         channel_state: Mutex::new(ChannelHolder{
538                                 by_id: HashMap::new(),
539                                 short_to_id: HashMap::new(),
540                                 next_forward: Instant::now(),
541                                 forward_htlcs: HashMap::new(),
542                                 claimable_htlcs: HashMap::new(),
543                                 pending_msg_events: Vec::new(),
544                         }),
545                         our_network_key: keys_manager.get_node_secret(),
546
547                         pending_events: Mutex::new(Vec::new()),
548                         total_consistency_lock: RwLock::new(()),
549
550                         keys_manager,
551
552                         logger,
553                 });
554                 let weak_res = Arc::downgrade(&res);
555                 res.chain_monitor.register_listener(weak_res);
556                 Ok(res)
557         }
558
559         /// Creates a new outbound channel to the given remote node and with the given value.
560         ///
561         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
562         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
563         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
564         /// may wish to avoid using 0 for user_id here.
565         ///
566         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
567         /// PeerManager::process_events afterwards.
568         ///
569         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
570         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
571         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
572                 if channel_value_satoshis < 1000 {
573                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
574                 }
575
576                 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)?;
577                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
578
579                 let _ = self.total_consistency_lock.read().unwrap();
580                 let mut channel_state = self.channel_state.lock().unwrap();
581                 match channel_state.by_id.entry(channel.channel_id()) {
582                         hash_map::Entry::Occupied(_) => {
583                                 if cfg!(feature = "fuzztarget") {
584                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
585                                 } else {
586                                         panic!("RNG is bad???");
587                                 }
588                         },
589                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
590                 }
591                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
592                         node_id: their_network_key,
593                         msg: res,
594                 });
595                 Ok(())
596         }
597
598         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
599         /// more information.
600         pub fn list_channels(&self) -> Vec<ChannelDetails> {
601                 let channel_state = self.channel_state.lock().unwrap();
602                 let mut res = Vec::with_capacity(channel_state.by_id.len());
603                 for (channel_id, channel) in channel_state.by_id.iter() {
604                         res.push(ChannelDetails {
605                                 channel_id: (*channel_id).clone(),
606                                 short_channel_id: channel.get_short_channel_id(),
607                                 remote_network_id: channel.get_their_node_id(),
608                                 channel_value_satoshis: channel.get_value_satoshis(),
609                                 user_id: channel.get_user_id(),
610                         });
611                 }
612                 res
613         }
614
615         /// Gets the list of usable channels, in random order. Useful as an argument to
616         /// Router::get_route to ensure non-announced channels are used.
617         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
618                 let channel_state = self.channel_state.lock().unwrap();
619                 let mut res = Vec::with_capacity(channel_state.by_id.len());
620                 for (channel_id, channel) in channel_state.by_id.iter() {
621                         // Note we use is_live here instead of usable which leads to somewhat confused
622                         // internal/external nomenclature, but that's ok cause that's probably what the user
623                         // really wanted anyway.
624                         if channel.is_live() {
625                                 res.push(ChannelDetails {
626                                         channel_id: (*channel_id).clone(),
627                                         short_channel_id: channel.get_short_channel_id(),
628                                         remote_network_id: channel.get_their_node_id(),
629                                         channel_value_satoshis: channel.get_value_satoshis(),
630                                         user_id: channel.get_user_id(),
631                                 });
632                         }
633                 }
634                 res
635         }
636
637         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
638         /// will be accepted on the given channel, and after additional timeout/the closing of all
639         /// pending HTLCs, the channel will be closed on chain.
640         ///
641         /// May generate a SendShutdown message event on success, which should be relayed.
642         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
643                 let _ = self.total_consistency_lock.read().unwrap();
644
645                 let (mut failed_htlcs, chan_option) = {
646                         let mut channel_state_lock = self.channel_state.lock().unwrap();
647                         let channel_state = channel_state_lock.borrow_parts();
648                         match channel_state.by_id.entry(channel_id.clone()) {
649                                 hash_map::Entry::Occupied(mut chan_entry) => {
650                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
651                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
652                                                 node_id: chan_entry.get().get_their_node_id(),
653                                                 msg: shutdown_msg
654                                         });
655                                         if chan_entry.get().is_shutdown() {
656                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
657                                                         channel_state.short_to_id.remove(&short_id);
658                                                 }
659                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
660                                         } else { (failed_htlcs, None) }
661                                 },
662                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
663                         }
664                 };
665                 for htlc_source in failed_htlcs.drain(..) {
666                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
667                 }
668                 let chan_update = if let Some(chan) = chan_option {
669                         if let Ok(update) = self.get_channel_update(&chan) {
670                                 Some(update)
671                         } else { None }
672                 } else { None };
673
674                 if let Some(update) = chan_update {
675                         let mut channel_state = self.channel_state.lock().unwrap();
676                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
677                                 msg: update
678                         });
679                 }
680
681                 Ok(())
682         }
683
684         #[inline]
685         fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
686                 let (local_txn, mut failed_htlcs) = shutdown_res;
687                 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
688                 for htlc_source in failed_htlcs.drain(..) {
689                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
690                 }
691                 for tx in local_txn {
692                         self.tx_broadcaster.broadcast_transaction(&tx);
693                 }
694         }
695
696         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
697         /// the chain and rejecting new HTLCs on the given channel.
698         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
699                 let _ = self.total_consistency_lock.read().unwrap();
700
701                 let mut chan = {
702                         let mut channel_state_lock = self.channel_state.lock().unwrap();
703                         let channel_state = channel_state_lock.borrow_parts();
704                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
705                                 if let Some(short_id) = chan.get_short_channel_id() {
706                                         channel_state.short_to_id.remove(&short_id);
707                                 }
708                                 chan
709                         } else {
710                                 return;
711                         }
712                 };
713                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
714                 self.finish_force_close_channel(chan.force_shutdown());
715                 if let Ok(update) = self.get_channel_update(&chan) {
716                         let mut channel_state = self.channel_state.lock().unwrap();
717                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
718                                 msg: update
719                         });
720                 }
721         }
722
723         /// Force close all channels, immediately broadcasting the latest local commitment transaction
724         /// for each to the chain and rejecting new HTLCs on each.
725         pub fn force_close_all_channels(&self) {
726                 for chan in self.list_channels() {
727                         self.force_close_channel(&chan.channel_id);
728                 }
729         }
730
731         #[inline]
732         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
733                 assert_eq!(shared_secret.len(), 32);
734                 ({
735                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
736                         hmac.input(&shared_secret[..]);
737                         let mut res = [0; 32];
738                         hmac.raw_result(&mut res);
739                         res
740                 },
741                 {
742                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
743                         hmac.input(&shared_secret[..]);
744                         let mut res = [0; 32];
745                         hmac.raw_result(&mut res);
746                         res
747                 })
748         }
749
750         #[inline]
751         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
752                 assert_eq!(shared_secret.len(), 32);
753                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
754                 hmac.input(&shared_secret[..]);
755                 let mut res = [0; 32];
756                 hmac.raw_result(&mut res);
757                 res
758         }
759
760         #[inline]
761         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
762                 assert_eq!(shared_secret.len(), 32);
763                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
764                 hmac.input(&shared_secret[..]);
765                 let mut res = [0; 32];
766                 hmac.raw_result(&mut res);
767                 res
768         }
769
770         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
771         #[inline]
772         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> {
773                 let mut blinded_priv = session_priv.clone();
774                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
775
776                 for hop in route.hops.iter() {
777                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
778
779                         let mut sha = Sha256::new();
780                         sha.input(&blinded_pub.serialize()[..]);
781                         sha.input(&shared_secret[..]);
782                         let mut blinding_factor = [0u8; 32];
783                         sha.result(&mut blinding_factor);
784
785                         let ephemeral_pubkey = blinded_pub;
786
787                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
788                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
789
790                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
791                 }
792
793                 Ok(())
794         }
795
796         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
797         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
798                 let mut res = Vec::with_capacity(route.hops.len());
799
800                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
801                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
802
803                         res.push(OnionKeys {
804                                 #[cfg(test)]
805                                 shared_secret,
806                                 #[cfg(test)]
807                                 blinding_factor: _blinding_factor,
808                                 ephemeral_pubkey,
809                                 rho,
810                                 mu,
811                         });
812                 })?;
813
814                 Ok(res)
815         }
816
817         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
818         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
819                 let mut cur_value_msat = 0u64;
820                 let mut cur_cltv = starting_htlc_offset;
821                 let mut last_short_channel_id = 0;
822                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
823                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
824                 unsafe { res.set_len(route.hops.len()); }
825
826                 for (idx, hop) in route.hops.iter().enumerate().rev() {
827                         // First hop gets special values so that it can check, on receipt, that everything is
828                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
829                         // the intended recipient).
830                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
831                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
832                         res[idx] = msgs::OnionHopData {
833                                 realm: 0,
834                                 data: msgs::OnionRealm0HopData {
835                                         short_channel_id: last_short_channel_id,
836                                         amt_to_forward: value_msat,
837                                         outgoing_cltv_value: cltv,
838                                 },
839                                 hmac: [0; 32],
840                         };
841                         cur_value_msat += hop.fee_msat;
842                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
843                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
844                         }
845                         cur_cltv += hop.cltv_expiry_delta as u32;
846                         if cur_cltv >= 500000000 {
847                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
848                         }
849                         last_short_channel_id = hop.short_channel_id;
850                 }
851                 Ok((res, cur_value_msat, cur_cltv))
852         }
853
854         #[inline]
855         fn shift_arr_right(arr: &mut [u8; 20*65]) {
856                 unsafe {
857                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
858                 }
859                 for i in 0..65 {
860                         arr[i] = 0;
861                 }
862         }
863
864         #[inline]
865         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
866                 assert_eq!(dst.len(), src.len());
867
868                 for i in 0..dst.len() {
869                         dst[i] ^= src[i];
870                 }
871         }
872
873         const ZERO:[u8; 21*65] = [0; 21*65];
874         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
875                 let mut buf = Vec::with_capacity(21*65);
876                 buf.resize(21*65, 0);
877
878                 let filler = {
879                         let iters = payloads.len() - 1;
880                         let end_len = iters * 65;
881                         let mut res = Vec::with_capacity(end_len);
882                         res.resize(end_len, 0);
883
884                         for (i, keys) in onion_keys.iter().enumerate() {
885                                 if i == payloads.len() - 1 { continue; }
886                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
887                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
888                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
889                         }
890                         res
891                 };
892
893                 let mut packet_data = [0; 20*65];
894                 let mut hmac_res = [0; 32];
895
896                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
897                         ChannelManager::shift_arr_right(&mut packet_data);
898                         payload.hmac = hmac_res;
899                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
900
901                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
902                         chacha.process(&packet_data, &mut buf[0..20*65]);
903                         packet_data[..].copy_from_slice(&buf[0..20*65]);
904
905                         if i == 0 {
906                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
907                         }
908
909                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
910                         hmac.input(&packet_data);
911                         hmac.input(&associated_data.0[..]);
912                         hmac.raw_result(&mut hmac_res);
913                 }
914
915                 msgs::OnionPacket{
916                         version: 0,
917                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
918                         hop_data: packet_data,
919                         hmac: hmac_res,
920                 }
921         }
922
923         /// Encrypts a failure packet. raw_packet can either be a
924         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
925         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
926                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
927
928                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
929                 packet_crypted.resize(raw_packet.len(), 0);
930                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
931                 chacha.process(&raw_packet, &mut packet_crypted[..]);
932                 msgs::OnionErrorPacket {
933                         data: packet_crypted,
934                 }
935         }
936
937         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
938                 assert_eq!(shared_secret.len(), 32);
939                 assert!(failure_data.len() <= 256 - 2);
940
941                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
942
943                 let failuremsg = {
944                         let mut res = Vec::with_capacity(2 + failure_data.len());
945                         res.push(((failure_type >> 8) & 0xff) as u8);
946                         res.push(((failure_type >> 0) & 0xff) as u8);
947                         res.extend_from_slice(&failure_data[..]);
948                         res
949                 };
950                 let pad = {
951                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
952                         res.resize(256 - 2 - failure_data.len(), 0);
953                         res
954                 };
955                 let mut packet = msgs::DecodedOnionErrorPacket {
956                         hmac: [0; 32],
957                         failuremsg: failuremsg,
958                         pad: pad,
959                 };
960
961                 let mut hmac = Hmac::new(Sha256::new(), &um);
962                 hmac.input(&packet.encode()[32..]);
963                 hmac.raw_result(&mut packet.hmac);
964
965                 packet
966         }
967
968         #[inline]
969         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
970                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
971                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
972         }
973
974         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
975                 macro_rules! get_onion_hash {
976                         () => {
977                                 {
978                                         let mut sha = Sha256::new();
979                                         sha.input(&msg.onion_routing_packet.hop_data);
980                                         let mut onion_hash = [0; 32];
981                                         sha.result(&mut onion_hash);
982                                         onion_hash
983                                 }
984                         }
985                 }
986
987                 if let Err(_) = msg.onion_routing_packet.public_key {
988                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
989                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
990                                 channel_id: msg.channel_id,
991                                 htlc_id: msg.htlc_id,
992                                 sha256_of_onion: get_onion_hash!(),
993                                 failure_code: 0x8000 | 0x4000 | 6,
994                         })), self.channel_state.lock().unwrap());
995                 }
996
997                 let shared_secret = {
998                         let mut arr = [0; 32];
999                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1000                         arr
1001                 };
1002                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1003
1004                 let mut channel_state = None;
1005                 macro_rules! return_err {
1006                         ($msg: expr, $err_code: expr, $data: expr) => {
1007                                 {
1008                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1009                                         if channel_state.is_none() {
1010                                                 channel_state = Some(self.channel_state.lock().unwrap());
1011                                         }
1012                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1013                                                 channel_id: msg.channel_id,
1014                                                 htlc_id: msg.htlc_id,
1015                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1016                                         })), channel_state.unwrap());
1017                                 }
1018                         }
1019                 }
1020
1021                 if msg.onion_routing_packet.version != 0 {
1022                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1023                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1024                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1025                         //receiving node would have to brute force to figure out which version was put in the
1026                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1027                         //node knows the HMAC matched, so they already know what is there...
1028                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1029                 }
1030
1031                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1032                 hmac.input(&msg.onion_routing_packet.hop_data);
1033                 hmac.input(&msg.payment_hash.0[..]);
1034                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1035                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1036                 }
1037
1038                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1039                 let next_hop_data = {
1040                         let mut decoded = [0; 65];
1041                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1042                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1043                                 Err(err) => {
1044                                         let error_code = match err {
1045                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1046                                                 _ => 0x2000 | 2, // Should never happen
1047                                         };
1048                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1049                                 },
1050                                 Ok(msg) => msg
1051                         }
1052                 };
1053
1054                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1055                                 // OUR PAYMENT!
1056                                 // final_expiry_too_soon
1057                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1058                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1059                                 }
1060                                 // final_incorrect_htlc_amount
1061                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1062                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1063                                 }
1064                                 // final_incorrect_cltv_expiry
1065                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1066                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1067                                 }
1068
1069                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1070                                 // message, however that would leak that we are the recipient of this payment, so
1071                                 // instead we stay symmetric with the forwarding case, only responding (after a
1072                                 // delay) once they've send us a commitment_signed!
1073
1074                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1075                                         onion_packet: None,
1076                                         payment_hash: msg.payment_hash.clone(),
1077                                         short_channel_id: 0,
1078                                         incoming_shared_secret: shared_secret,
1079                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1080                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1081                                 })
1082                         } else {
1083                                 let mut new_packet_data = [0; 20*65];
1084                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1085                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1086
1087                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1088
1089                                 let blinding_factor = {
1090                                         let mut sha = Sha256::new();
1091                                         sha.input(&new_pubkey.serialize()[..]);
1092                                         sha.input(&shared_secret);
1093                                         let mut res = [0u8; 32];
1094                                         sha.result(&mut res);
1095                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1096                                                 Err(_) => {
1097                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1098                                                 },
1099                                                 Ok(key) => key
1100                                         }
1101                                 };
1102
1103                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1104                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1105                                 }
1106
1107                                 let outgoing_packet = msgs::OnionPacket {
1108                                         version: 0,
1109                                         public_key: Ok(new_pubkey),
1110                                         hop_data: new_packet_data,
1111                                         hmac: next_hop_data.hmac.clone(),
1112                                 };
1113
1114                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1115                                         onion_packet: Some(outgoing_packet),
1116                                         payment_hash: msg.payment_hash.clone(),
1117                                         short_channel_id: next_hop_data.data.short_channel_id,
1118                                         incoming_shared_secret: shared_secret,
1119                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1120                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1121                                 })
1122                         };
1123
1124                 channel_state = Some(self.channel_state.lock().unwrap());
1125                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1126                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1127                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1128                                 let forwarding_id = match id_option {
1129                                         None => { // unknown_next_peer
1130                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1131                                         },
1132                                         Some(id) => id.clone(),
1133                                 };
1134                                 if let Some((err, code, chan_update)) = loop {
1135                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1136
1137                                         // Note that we could technically not return an error yet here and just hope
1138                                         // that the connection is reestablished or monitor updated by the time we get
1139                                         // around to doing the actual forward, but better to fail early if we can and
1140                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1141                                         // on a small/per-node/per-channel scale.
1142                                         if !chan.is_live() { // channel_disabled
1143                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1144                                         }
1145                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1146                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1147                                         }
1148                                         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) });
1149                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1150                                                 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())));
1151                                         }
1152                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1153                                                 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())));
1154                                         }
1155                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1156                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1157                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1158                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1159                                         }
1160                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1161                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1162                                         }
1163                                         break None;
1164                                 }
1165                                 {
1166                                         let mut res = Vec::with_capacity(8 + 128);
1167                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1168                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1169                                         }
1170                                         else if code == 0x1000 | 13 {
1171                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1172                                         }
1173                                         if let Some(chan_update) = chan_update {
1174                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1175                                         }
1176                                         return_err!(err, code, &res[..]);
1177                                 }
1178                         }
1179                 }
1180
1181                 (pending_forward_info, channel_state.unwrap())
1182         }
1183
1184         /// only fails if the channel does not yet have an assigned short_id
1185         /// May be called with channel_state already locked!
1186         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1187                 let short_channel_id = match chan.get_short_channel_id() {
1188                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1189                         Some(id) => id,
1190                 };
1191
1192                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1193
1194                 let unsigned = msgs::UnsignedChannelUpdate {
1195                         chain_hash: self.genesis_hash,
1196                         short_channel_id: short_channel_id,
1197                         timestamp: chan.get_channel_update_count(),
1198                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1199                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1200                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1201                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1202                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1203                         excess_data: Vec::new(),
1204                 };
1205
1206                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1207                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1208
1209                 Ok(msgs::ChannelUpdate {
1210                         signature: sig,
1211                         contents: unsigned
1212                 })
1213         }
1214
1215         /// Sends a payment along a given route.
1216         ///
1217         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1218         /// fields for more info.
1219         ///
1220         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1221         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1222         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1223         /// specified in the last hop in the route! Thus, you should probably do your own
1224         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1225         /// payment") and prevent double-sends yourself.
1226         ///
1227         /// May generate a SendHTLCs message event on success, which should be relayed.
1228         ///
1229         /// Raises APIError::RoutError when invalid route or forward parameter
1230         /// (cltv_delta, fee, node public key) is specified.
1231         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1232         /// (including due to previous monitor update failure or new permanent monitor update failure).
1233         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1234         /// relevant updates.
1235         ///
1236         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1237         /// and you may wish to retry via a different route immediately.
1238         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1239         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1240         /// the payment via a different route unless you intend to pay twice!
1241         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1242                 if route.hops.len() < 1 || route.hops.len() > 20 {
1243                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1244                 }
1245                 let our_node_id = self.get_our_node_id();
1246                 for (idx, hop) in route.hops.iter().enumerate() {
1247                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1248                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1249                         }
1250                 }
1251
1252                 let session_priv = self.keys_manager.get_session_key();
1253
1254                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1255
1256                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1257                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1258                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1259                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1260
1261                 let _ = self.total_consistency_lock.read().unwrap();
1262
1263                 let err: Result<(), _> = loop {
1264                         let mut channel_lock = self.channel_state.lock().unwrap();
1265
1266                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1267                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1268                                 Some(id) => id.clone(),
1269                         };
1270
1271                         let channel_state = channel_lock.borrow_parts();
1272                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1273                                 match {
1274                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1275                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1276                                         }
1277                                         if !chan.get().is_live() {
1278                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1279                                         }
1280                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1281                                                 route: route.clone(),
1282                                                 session_priv: session_priv.clone(),
1283                                                 first_hop_htlc_msat: htlc_msat,
1284                                         }, onion_packet), channel_state, chan)
1285                                 } {
1286                                         Some((update_add, commitment_signed, chan_monitor)) => {
1287                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1288                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1289                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1290                                                         // that we will resent the commitment update once we unfree monitor
1291                                                         // updating, so we have to take special care that we don't return
1292                                                         // something else in case we will resend later!
1293                                                         return Err(APIError::MonitorUpdateFailed);
1294                                                 }
1295
1296                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1297                                                         node_id: route.hops.first().unwrap().pubkey,
1298                                                         updates: msgs::CommitmentUpdate {
1299                                                                 update_add_htlcs: vec![update_add],
1300                                                                 update_fulfill_htlcs: Vec::new(),
1301                                                                 update_fail_htlcs: Vec::new(),
1302                                                                 update_fail_malformed_htlcs: Vec::new(),
1303                                                                 update_fee: None,
1304                                                                 commitment_signed,
1305                                                         },
1306                                                 });
1307                                         },
1308                                         None => {},
1309                                 }
1310                         } else { unreachable!(); }
1311                         return Ok(());
1312                 };
1313
1314                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1315                         Ok(_) => unreachable!(),
1316                         Err(e) => {
1317                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1318                                 } else {
1319                                         log_error!(self, "Got bad keys: {}!", e.err);
1320                                         let mut channel_state = self.channel_state.lock().unwrap();
1321                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1322                                                 node_id: route.hops.first().unwrap().pubkey,
1323                                                 action: e.action,
1324                                         });
1325                                 }
1326                                 Err(APIError::ChannelUnavailable { err: e.err })
1327                         },
1328                 }
1329         }
1330
1331         /// Call this upon creation of a funding transaction for the given channel.
1332         ///
1333         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1334         /// or your counterparty can steal your funds!
1335         ///
1336         /// Panics if a funding transaction has already been provided for this channel.
1337         ///
1338         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1339         /// be trivially prevented by using unique funding transaction keys per-channel).
1340         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1341                 let _ = self.total_consistency_lock.read().unwrap();
1342
1343                 let (chan, msg, chan_monitor) = {
1344                         let (res, chan) = {
1345                                 let mut channel_state = self.channel_state.lock().unwrap();
1346                                 match channel_state.by_id.remove(temporary_channel_id) {
1347                                         Some(mut chan) => {
1348                                                 (chan.get_outbound_funding_created(funding_txo)
1349                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1350                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1351                                                         } else { unreachable!(); })
1352                                                 , chan)
1353                                         },
1354                                         None => return
1355                                 }
1356                         };
1357                         match handle_error!(self, res, chan.get_their_node_id()) {
1358                                 Ok(funding_msg) => {
1359                                         (chan, funding_msg.0, funding_msg.1)
1360                                 },
1361                                 Err(e) => {
1362                                         log_error!(self, "Got bad signatures: {}!", e.err);
1363                                         let mut channel_state = self.channel_state.lock().unwrap();
1364                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1365                                                 node_id: chan.get_their_node_id(),
1366                                                 action: e.action,
1367                                         });
1368                                         return;
1369                                 },
1370                         }
1371                 };
1372                 // Because we have exclusive ownership of the channel here we can release the channel_state
1373                 // lock before add_update_monitor
1374                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1375                         unimplemented!();
1376                 }
1377
1378                 let mut channel_state = self.channel_state.lock().unwrap();
1379                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1380                         node_id: chan.get_their_node_id(),
1381                         msg: msg,
1382                 });
1383                 match channel_state.by_id.entry(chan.channel_id()) {
1384                         hash_map::Entry::Occupied(_) => {
1385                                 panic!("Generated duplicate funding txid?");
1386                         },
1387                         hash_map::Entry::Vacant(e) => {
1388                                 e.insert(chan);
1389                         }
1390                 }
1391         }
1392
1393         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1394                 if !chan.should_announce() { return None }
1395
1396                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1397                         Ok(res) => res,
1398                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1399                 };
1400                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1401                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1402
1403                 Some(msgs::AnnouncementSignatures {
1404                         channel_id: chan.channel_id(),
1405                         short_channel_id: chan.get_short_channel_id().unwrap(),
1406                         node_signature: our_node_sig,
1407                         bitcoin_signature: our_bitcoin_sig,
1408                 })
1409         }
1410
1411         /// Processes HTLCs which are pending waiting on random forward delay.
1412         ///
1413         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1414         /// Will likely generate further events.
1415         pub fn process_pending_htlc_forwards(&self) {
1416                 let _ = self.total_consistency_lock.read().unwrap();
1417
1418                 let mut new_events = Vec::new();
1419                 let mut failed_forwards = Vec::new();
1420                 {
1421                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1422                         let channel_state = channel_state_lock.borrow_parts();
1423
1424                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1425                                 return;
1426                         }
1427
1428                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1429                                 if short_chan_id != 0 {
1430                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1431                                                 Some(chan_id) => chan_id.clone(),
1432                                                 None => {
1433                                                         failed_forwards.reserve(pending_forwards.len());
1434                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1435                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1436                                                                         short_channel_id: prev_short_channel_id,
1437                                                                         htlc_id: prev_htlc_id,
1438                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1439                                                                 });
1440                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1441                                                         }
1442                                                         continue;
1443                                                 }
1444                                         };
1445                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1446
1447                                         let mut add_htlc_msgs = Vec::new();
1448                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1449                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1450                                                         short_channel_id: prev_short_channel_id,
1451                                                         htlc_id: prev_htlc_id,
1452                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1453                                                 });
1454                                                 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()) {
1455                                                         Err(_e) => {
1456                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1457                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1458                                                                 continue;
1459                                                         },
1460                                                         Ok(update_add) => {
1461                                                                 match update_add {
1462                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1463                                                                         None => {
1464                                                                                 // Nothing to do here...we're waiting on a remote
1465                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1466                                                                                 // will automatically handle building the update_add_htlc and
1467                                                                                 // commitment_signed messages when we can.
1468                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1469                                                                                 // as we don't really want others relying on us relaying through
1470                                                                                 // this channel currently :/.
1471                                                                         }
1472                                                                 }
1473                                                         }
1474                                                 }
1475                                         }
1476
1477                                         if !add_htlc_msgs.is_empty() {
1478                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1479                                                         Ok(res) => res,
1480                                                         Err(e) => {
1481                                                                 if let ChannelError::Ignore(_) = e {
1482                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1483                                                                 }
1484                                                                 //TODO: Handle...this is bad!
1485                                                                 continue;
1486                                                         },
1487                                                 };
1488                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1489                                                         unimplemented!();
1490                                                 }
1491                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1492                                                         node_id: forward_chan.get_their_node_id(),
1493                                                         updates: msgs::CommitmentUpdate {
1494                                                                 update_add_htlcs: add_htlc_msgs,
1495                                                                 update_fulfill_htlcs: Vec::new(),
1496                                                                 update_fail_htlcs: Vec::new(),
1497                                                                 update_fail_malformed_htlcs: Vec::new(),
1498                                                                 update_fee: None,
1499                                                                 commitment_signed: commitment_msg,
1500                                                         },
1501                                                 });
1502                                         }
1503                                 } else {
1504                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1505                                                 let prev_hop_data = HTLCPreviousHopData {
1506                                                         short_channel_id: prev_short_channel_id,
1507                                                         htlc_id: prev_htlc_id,
1508                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1509                                                 };
1510                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1511                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1512                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1513                                                 };
1514                                                 new_events.push(events::Event::PaymentReceived {
1515                                                         payment_hash: forward_info.payment_hash,
1516                                                         amt: forward_info.amt_to_forward,
1517                                                 });
1518                                         }
1519                                 }
1520                         }
1521                 }
1522
1523                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1524                         match update {
1525                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1526                                 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() }),
1527                         };
1528                 }
1529
1530                 if new_events.is_empty() { return }
1531                 let mut events = self.pending_events.lock().unwrap();
1532                 events.append(&mut new_events);
1533         }
1534
1535         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1536         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1537                 let _ = self.total_consistency_lock.read().unwrap();
1538
1539                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1540                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1541                 if let Some(mut sources) = removed_source {
1542                         for htlc_with_hash in sources.drain(..) {
1543                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1544                                 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() });
1545                         }
1546                         true
1547                 } else { false }
1548         }
1549
1550         /// Fails an HTLC backwards to the sender of it to us.
1551         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1552         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1553         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1554         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1555         /// still-available channels.
1556         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1557                 match source {
1558                         HTLCSource::OutboundRoute { ref route, .. } => {
1559                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1560                                 mem::drop(channel_state_lock);
1561                                 match &onion_error {
1562                                         &HTLCFailReason::ErrorPacket { ref err } => {
1563 #[cfg(test)]
1564                                                 let (channel_update, payment_retryable, onion_error_code) = self.process_onion_failure(&source, err.data.clone());
1565 #[cfg(not(test))]
1566                                                 let (channel_update, payment_retryable, _) = self.process_onion_failure(&source, err.data.clone());
1567                                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1568                                                 // process_onion_failure we should close that channel as it implies our
1569                                                 // next-hop is needlessly blaming us!
1570                                                 if let Some(update) = channel_update {
1571                                                         self.channel_state.lock().unwrap().pending_msg_events.push(
1572                                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1573                                                                         update,
1574                                                                 }
1575                                                         );
1576                                                 }
1577                                                 self.pending_events.lock().unwrap().push(
1578                                                         events::Event::PaymentFailed {
1579                                                                 payment_hash: payment_hash.clone(),
1580                                                                 rejected_by_dest: !payment_retryable,
1581 #[cfg(test)]
1582                                                                 error_code: onion_error_code
1583                                                         }
1584                                                 );
1585                                         },
1586                                         &HTLCFailReason::Reason {
1587 #[cfg(test)]
1588                                                         ref failure_code,
1589                                                         .. } => {
1590                                                 // we get a fail_malformed_htlc from the first hop
1591                                                 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1592                                                 // failures here, but that would be insufficient as Router::get_route
1593                                                 // generally ignores its view of our own channels as we provide them via
1594                                                 // ChannelDetails.
1595                                                 // TODO: For non-temporary failures, we really should be closing the
1596                                                 // channel here as we apparently can't relay through them anyway.
1597                                                 self.pending_events.lock().unwrap().push(
1598                                                         events::Event::PaymentFailed {
1599                                                                 payment_hash: payment_hash.clone(),
1600                                                                 rejected_by_dest: route.hops.len() == 1,
1601 #[cfg(test)]
1602                                                                 error_code: Some(*failure_code),
1603                                                         }
1604                                                 );
1605                                         }
1606                                 }
1607                         },
1608                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1609                                 let err_packet = match onion_error {
1610                                         HTLCFailReason::Reason { failure_code, data } => {
1611                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1612                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1613                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1614                                         },
1615                                         HTLCFailReason::ErrorPacket { err } => {
1616                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1617                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1618                                         }
1619                                 };
1620
1621                                 let channel_state = channel_state_lock.borrow_parts();
1622
1623                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1624                                         Some(chan_id) => chan_id.clone(),
1625                                         None => return
1626                                 };
1627
1628                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1629                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1630                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1631                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1632                                                         unimplemented!();
1633                                                 }
1634                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1635                                                         node_id: chan.get_their_node_id(),
1636                                                         updates: msgs::CommitmentUpdate {
1637                                                                 update_add_htlcs: Vec::new(),
1638                                                                 update_fulfill_htlcs: Vec::new(),
1639                                                                 update_fail_htlcs: vec![msg],
1640                                                                 update_fail_malformed_htlcs: Vec::new(),
1641                                                                 update_fee: None,
1642                                                                 commitment_signed: commitment_msg,
1643                                                         },
1644                                                 });
1645                                         },
1646                                         Ok(None) => {},
1647                                         Err(_e) => {
1648                                                 //TODO: Do something with e?
1649                                                 return;
1650                                         },
1651                                 }
1652                         },
1653                 }
1654         }
1655
1656         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1657         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1658         /// should probably kick the net layer to go send messages if this returns true!
1659         ///
1660         /// May panic if called except in response to a PaymentReceived event.
1661         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1662                 let mut sha = Sha256::new();
1663                 sha.input(&payment_preimage.0[..]);
1664                 let mut payment_hash = PaymentHash([0; 32]);
1665                 sha.result(&mut payment_hash.0[..]);
1666
1667                 let _ = self.total_consistency_lock.read().unwrap();
1668
1669                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1670                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1671                 if let Some(mut sources) = removed_source {
1672                         for htlc_with_hash in sources.drain(..) {
1673                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1674                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1675                         }
1676                         true
1677                 } else { false }
1678         }
1679         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1680                 match source {
1681                         HTLCSource::OutboundRoute { .. } => {
1682                                 mem::drop(channel_state_lock);
1683                                 let mut pending_events = self.pending_events.lock().unwrap();
1684                                 pending_events.push(events::Event::PaymentSent {
1685                                         payment_preimage
1686                                 });
1687                         },
1688                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1689                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1690                                 let channel_state = channel_state_lock.borrow_parts();
1691
1692                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1693                                         Some(chan_id) => chan_id.clone(),
1694                                         None => {
1695                                                 // TODO: There is probably a channel manager somewhere that needs to
1696                                                 // learn the preimage as the channel already hit the chain and that's
1697                                                 // why its missing.
1698                                                 return
1699                                         }
1700                                 };
1701
1702                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1703                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1704                                         Ok((msgs, monitor_option)) => {
1705                                                 if let Some(chan_monitor) = monitor_option {
1706                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1707                                                                 unimplemented!();// but def dont push the event...
1708                                                         }
1709                                                 }
1710                                                 if let Some((msg, commitment_signed)) = msgs {
1711                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1712                                                                 node_id: chan.get_their_node_id(),
1713                                                                 updates: msgs::CommitmentUpdate {
1714                                                                         update_add_htlcs: Vec::new(),
1715                                                                         update_fulfill_htlcs: vec![msg],
1716                                                                         update_fail_htlcs: Vec::new(),
1717                                                                         update_fail_malformed_htlcs: Vec::new(),
1718                                                                         update_fee: None,
1719                                                                         commitment_signed,
1720                                                                 }
1721                                                         });
1722                                                 }
1723                                         },
1724                                         Err(_e) => {
1725                                                 // TODO: There is probably a channel manager somewhere that needs to
1726                                                 // learn the preimage as the channel may be about to hit the chain.
1727                                                 //TODO: Do something with e?
1728                                                 return
1729                                         },
1730                                 }
1731                         },
1732                 }
1733         }
1734
1735         /// Gets the node_id held by this ChannelManager
1736         pub fn get_our_node_id(&self) -> PublicKey {
1737                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1738         }
1739
1740         /// Used to restore channels to normal operation after a
1741         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1742         /// operation.
1743         pub fn test_restore_channel_monitor(&self) {
1744                 let mut close_results = Vec::new();
1745                 let mut htlc_forwards = Vec::new();
1746                 let mut htlc_failures = Vec::new();
1747                 let _ = self.total_consistency_lock.read().unwrap();
1748
1749                 {
1750                         let mut channel_lock = self.channel_state.lock().unwrap();
1751                         let channel_state = channel_lock.borrow_parts();
1752                         let short_to_id = channel_state.short_to_id;
1753                         let pending_msg_events = channel_state.pending_msg_events;
1754                         channel_state.by_id.retain(|_, channel| {
1755                                 if channel.is_awaiting_monitor_update() {
1756                                         let chan_monitor = channel.channel_monitor();
1757                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1758                                                 match e {
1759                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1760                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1761                                                                 // backwards when a monitor update failed. We should make sure
1762                                                                 // knowledge of those gets moved into the appropriate in-memory
1763                                                                 // ChannelMonitor and they get failed backwards once we get
1764                                                                 // on-chain confirmations.
1765                                                                 // Note I think #198 addresses this, so once its merged a test
1766                                                                 // should be written.
1767                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1768                                                                         short_to_id.remove(&short_id);
1769                                                                 }
1770                                                                 close_results.push(channel.force_shutdown());
1771                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1772                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1773                                                                                 msg: update
1774                                                                         });
1775                                                                 }
1776                                                                 false
1777                                                         },
1778                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1779                                                 }
1780                                         } else {
1781                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1782                                                 if !pending_forwards.is_empty() {
1783                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1784                                                 }
1785                                                 htlc_failures.append(&mut pending_failures);
1786
1787                                                 macro_rules! handle_cs { () => {
1788                                                         if let Some(update) = commitment_update {
1789                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1790                                                                         node_id: channel.get_their_node_id(),
1791                                                                         updates: update,
1792                                                                 });
1793                                                         }
1794                                                 } }
1795                                                 macro_rules! handle_raa { () => {
1796                                                         if let Some(revoke_and_ack) = raa {
1797                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1798                                                                         node_id: channel.get_their_node_id(),
1799                                                                         msg: revoke_and_ack,
1800                                                                 });
1801                                                         }
1802                                                 } }
1803                                                 match order {
1804                                                         RAACommitmentOrder::CommitmentFirst => {
1805                                                                 handle_cs!();
1806                                                                 handle_raa!();
1807                                                         },
1808                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1809                                                                 handle_raa!();
1810                                                                 handle_cs!();
1811                                                         },
1812                                                 }
1813                                                 true
1814                                         }
1815                                 } else { true }
1816                         });
1817                 }
1818
1819                 for failure in htlc_failures.drain(..) {
1820                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1821                 }
1822                 self.forward_htlcs(&mut htlc_forwards[..]);
1823
1824                 for res in close_results.drain(..) {
1825                         self.finish_force_close_channel(res);
1826                 }
1827         }
1828
1829         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1830                 if msg.chain_hash != self.genesis_hash {
1831                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1832                 }
1833
1834                 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)
1835                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1836                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1837                 let channel_state = channel_state_lock.borrow_parts();
1838                 match channel_state.by_id.entry(channel.channel_id()) {
1839                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1840                         hash_map::Entry::Vacant(entry) => {
1841                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1842                                         node_id: their_node_id.clone(),
1843                                         msg: channel.get_accept_channel(),
1844                                 });
1845                                 entry.insert(channel);
1846                         }
1847                 }
1848                 Ok(())
1849         }
1850
1851         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1852                 let (value, output_script, user_id) = {
1853                         let mut channel_lock = self.channel_state.lock().unwrap();
1854                         let channel_state = channel_lock.borrow_parts();
1855                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1856                                 hash_map::Entry::Occupied(mut chan) => {
1857                                         if chan.get().get_their_node_id() != *their_node_id {
1858                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1859                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1860                                         }
1861                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1862                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1863                                 },
1864                                 //TODO: same as above
1865                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1866                         }
1867                 };
1868                 let mut pending_events = self.pending_events.lock().unwrap();
1869                 pending_events.push(events::Event::FundingGenerationReady {
1870                         temporary_channel_id: msg.temporary_channel_id,
1871                         channel_value_satoshis: value,
1872                         output_script: output_script,
1873                         user_channel_id: user_id,
1874                 });
1875                 Ok(())
1876         }
1877
1878         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1879                 let ((funding_msg, monitor_update), chan) = {
1880                         let mut channel_lock = self.channel_state.lock().unwrap();
1881                         let channel_state = channel_lock.borrow_parts();
1882                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1883                                 hash_map::Entry::Occupied(mut chan) => {
1884                                         if chan.get().get_their_node_id() != *their_node_id {
1885                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1886                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1887                                         }
1888                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1889                                 },
1890                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1891                         }
1892                 };
1893                 // Because we have exclusive ownership of the channel here we can release the channel_state
1894                 // lock before add_update_monitor
1895                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1896                         unimplemented!();
1897                 }
1898                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1899                 let channel_state = channel_state_lock.borrow_parts();
1900                 match channel_state.by_id.entry(funding_msg.channel_id) {
1901                         hash_map::Entry::Occupied(_) => {
1902                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1903                         },
1904                         hash_map::Entry::Vacant(e) => {
1905                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1906                                         node_id: their_node_id.clone(),
1907                                         msg: funding_msg,
1908                                 });
1909                                 e.insert(chan);
1910                         }
1911                 }
1912                 Ok(())
1913         }
1914
1915         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1916                 let (funding_txo, user_id) = {
1917                         let mut channel_lock = self.channel_state.lock().unwrap();
1918                         let channel_state = channel_lock.borrow_parts();
1919                         match channel_state.by_id.entry(msg.channel_id) {
1920                                 hash_map::Entry::Occupied(mut chan) => {
1921                                         if chan.get().get_their_node_id() != *their_node_id {
1922                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1923                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1924                                         }
1925                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1926                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1927                                                 unimplemented!();
1928                                         }
1929                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1930                                 },
1931                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1932                         }
1933                 };
1934                 let mut pending_events = self.pending_events.lock().unwrap();
1935                 pending_events.push(events::Event::FundingBroadcastSafe {
1936                         funding_txo: funding_txo,
1937                         user_channel_id: user_id,
1938                 });
1939                 Ok(())
1940         }
1941
1942         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1943                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1944                 let channel_state = channel_state_lock.borrow_parts();
1945                 match channel_state.by_id.entry(msg.channel_id) {
1946                         hash_map::Entry::Occupied(mut chan) => {
1947                                 if chan.get().get_their_node_id() != *their_node_id {
1948                                         //TODO: here and below MsgHandleErrInternal, #153 case
1949                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1950                                 }
1951                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1952                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1953                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1954                                                 node_id: their_node_id.clone(),
1955                                                 msg: announcement_sigs,
1956                                         });
1957                                 }
1958                                 Ok(())
1959                         },
1960                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1961                 }
1962         }
1963
1964         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1965                 let (mut dropped_htlcs, chan_option) = {
1966                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1967                         let channel_state = channel_state_lock.borrow_parts();
1968
1969                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1970                                 hash_map::Entry::Occupied(mut chan_entry) => {
1971                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1972                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1973                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1974                                         }
1975                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1976                                         if let Some(msg) = shutdown {
1977                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1978                                                         node_id: their_node_id.clone(),
1979                                                         msg,
1980                                                 });
1981                                         }
1982                                         if let Some(msg) = closing_signed {
1983                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1984                                                         node_id: their_node_id.clone(),
1985                                                         msg,
1986                                                 });
1987                                         }
1988                                         if chan_entry.get().is_shutdown() {
1989                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1990                                                         channel_state.short_to_id.remove(&short_id);
1991                                                 }
1992                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1993                                         } else { (dropped_htlcs, None) }
1994                                 },
1995                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1996                         }
1997                 };
1998                 for htlc_source in dropped_htlcs.drain(..) {
1999                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2000                 }
2001                 if let Some(chan) = chan_option {
2002                         if let Ok(update) = self.get_channel_update(&chan) {
2003                                 let mut channel_state = self.channel_state.lock().unwrap();
2004                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2005                                         msg: update
2006                                 });
2007                         }
2008                 }
2009                 Ok(())
2010         }
2011
2012         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
2013                 let (tx, chan_option) = {
2014                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2015                         let channel_state = channel_state_lock.borrow_parts();
2016                         match channel_state.by_id.entry(msg.channel_id.clone()) {
2017                                 hash_map::Entry::Occupied(mut chan_entry) => {
2018                                         if chan_entry.get().get_their_node_id() != *their_node_id {
2019                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2020                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2021                                         }
2022                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
2023                                         if let Some(msg) = closing_signed {
2024                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2025                                                         node_id: their_node_id.clone(),
2026                                                         msg,
2027                                                 });
2028                                         }
2029                                         if tx.is_some() {
2030                                                 // We're done with this channel, we've got a signed closing transaction and
2031                                                 // will send the closing_signed back to the remote peer upon return. This
2032                                                 // also implies there are no pending HTLCs left on the channel, so we can
2033                                                 // fully delete it from tracking (the channel monitor is still around to
2034                                                 // watch for old state broadcasts)!
2035                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2036                                                         channel_state.short_to_id.remove(&short_id);
2037                                                 }
2038                                                 (tx, Some(chan_entry.remove_entry().1))
2039                                         } else { (tx, None) }
2040                                 },
2041                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2042                         }
2043                 };
2044                 if let Some(broadcast_tx) = tx {
2045                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2046                 }
2047                 if let Some(chan) = chan_option {
2048                         if let Ok(update) = self.get_channel_update(&chan) {
2049                                 let mut channel_state = self.channel_state.lock().unwrap();
2050                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2051                                         msg: update
2052                                 });
2053                         }
2054                 }
2055                 Ok(())
2056         }
2057
2058         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2059                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2060                 //determine the state of the payment based on our response/if we forward anything/the time
2061                 //we take to respond. We should take care to avoid allowing such an attack.
2062                 //
2063                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2064                 //us repeatedly garbled in different ways, and compare our error messages, which are
2065                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2066                 //but we should prevent it anyway.
2067
2068                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2069                 let channel_state = channel_state_lock.borrow_parts();
2070
2071                 match channel_state.by_id.entry(msg.channel_id) {
2072                         hash_map::Entry::Occupied(mut chan) => {
2073                                 if chan.get().get_their_node_id() != *their_node_id {
2074                                         //TODO: here MsgHandleErrInternal, #153 case
2075                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2076                                 }
2077                                 if !chan.get().is_usable() {
2078                                         // If the update_add is completely bogus, the call will Err and we will close,
2079                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2080                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2081                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2082                                                 let chan_update = self.get_channel_update(chan.get());
2083                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2084                                                         channel_id: msg.channel_id,
2085                                                         htlc_id: msg.htlc_id,
2086                                                         reason: if let Ok(update) = chan_update {
2087                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2088                                                         } else {
2089                                                                 // This can only happen if the channel isn't in the fully-funded
2090                                                                 // state yet, implying our counterparty is trying to route payments
2091                                                                 // over the channel back to themselves (cause no one else should
2092                                                                 // know the short_id is a lightning channel yet). We should have no
2093                                                                 // problem just calling this unknown_next_peer
2094                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2095                                                         },
2096                                                 }));
2097                                         }
2098                                 }
2099                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2100                         },
2101                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2102                 }
2103                 Ok(())
2104         }
2105
2106         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2107                 let mut channel_lock = self.channel_state.lock().unwrap();
2108                 let htlc_source = {
2109                         let channel_state = channel_lock.borrow_parts();
2110                         match channel_state.by_id.entry(msg.channel_id) {
2111                                 hash_map::Entry::Occupied(mut chan) => {
2112                                         if chan.get().get_their_node_id() != *their_node_id {
2113                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2114                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2115                                         }
2116                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2117                                 },
2118                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2119                         }
2120                 };
2121                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2122                 Ok(())
2123         }
2124
2125         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2126         // indicating that the payment itself failed
2127         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>) {
2128                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2129
2130                         let mut res = None;
2131                         let mut htlc_msat = *first_hop_htlc_msat;
2132                         let mut error_code_ret = None;
2133                         let mut next_route_hop_ix = 0;
2134                         let mut is_from_final_node = false;
2135
2136                         // Handle packed channel/node updates for passing back for the route handler
2137                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2138                                 next_route_hop_ix += 1;
2139                                 if res.is_some() { return; }
2140
2141                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2142                                 htlc_msat = amt_to_forward;
2143
2144                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2145
2146                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2147                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2148                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2149                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2150                                 packet_decrypted = decryption_tmp;
2151
2152                                 is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2153
2154                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2155                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2156                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2157                                         hmac.input(&err_packet.encode()[32..]);
2158                                         let mut calc_tag = [0u8; 32];
2159                                         hmac.raw_result(&mut calc_tag);
2160
2161                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2162                                                 if let Some(error_code_slice) = err_packet.failuremsg.get(0..2) {
2163                                                         const PERM: u16 = 0x4000;
2164                                                         const NODE: u16 = 0x2000;
2165                                                         const UPDATE: u16 = 0x1000;
2166
2167                                                         let error_code = byte_utils::slice_to_be16(&error_code_slice);
2168                                                         error_code_ret = Some(error_code);
2169
2170                                                         let (debug_field, debug_field_size) = errors::get_onion_debug_field(error_code);
2171
2172                                                         // indicate that payment parameter has failed and no need to
2173                                                         // update Route object
2174                                                         let payment_failed = (match error_code & 0xff {
2175                                                                 15|16|17|18|19 => true,
2176                                                                 _ => false,
2177                                                         } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
2178                                                         || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
2179
2180                                                         let mut fail_channel_update = None;
2181
2182                                                         if error_code & NODE == NODE {
2183                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
2184                                                         }
2185                                                         else if error_code & PERM == PERM {
2186                                                                 fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2187                                                                         short_channel_id: route.hops[next_route_hop_ix - if next_route_hop_ix == route.hops.len() { 1 } else { 0 }].short_channel_id,
2188                                                                         is_permanent: true,
2189                                                                 })};
2190                                                         }
2191                                                         else if error_code & UPDATE == UPDATE {
2192                                                                 if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
2193                                                                         let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
2194                                                                         if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
2195                                                                                 if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
2196                                                                                         // if channel_update should NOT have caused the failure:
2197                                                                                         // MAY treat the channel_update as invalid.
2198                                                                                         let is_chan_update_invalid = match error_code & 0xff {
2199                                                                                                 7 => false,
2200                                                                                                 11 => amt_to_forward > chan_update.contents.htlc_minimum_msat,
2201                                                                                                 12 => {
2202                                                                                                         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) });
2203                                                                                                         new_fee.is_some() && route_hop.fee_msat >= new_fee.unwrap()
2204                                                                                                 }
2205                                                                                                 13 => route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta,
2206                                                                                                 14 => false, // expiry_too_soon; always valid?
2207                                                                                                 20 => chan_update.contents.flags & 2 == 0,
2208                                                                                                 _ => false, // unknown error code; take channel_update as valid
2209                                                                                         };
2210                                                                                         fail_channel_update = if is_chan_update_invalid {
2211                                                                                                 // This probably indicates the node which forwarded
2212                                                                                                 // to the node in question corrupted something.
2213                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2214                                                                                                         short_channel_id: route_hop.short_channel_id,
2215                                                                                                         is_permanent: true,
2216                                                                                                 })
2217                                                                                         } else {
2218                                                                                                 Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2219                                                                                                         msg: chan_update,
2220                                                                                                 })
2221                                                                                         };
2222                                                                                 }
2223                                                                         }
2224                                                                 }
2225                                                                 if fail_channel_update.is_none() {
2226                                                                         // They provided an UPDATE which was obviously bogus, not worth
2227                                                                         // trying to relay through them anymore.
2228                                                                         fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2229                                                                                 node_id: route_hop.pubkey,
2230                                                                                 is_permanent: true,
2231                                                                         });
2232                                                                 }
2233                                                         } else if !payment_failed {
2234                                                                 // We can't understand their error messages and they failed to
2235                                                                 // forward...they probably can't understand our forwards so its
2236                                                                 // really not worth trying any further.
2237                                                                 fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2238                                                                         node_id: route_hop.pubkey,
2239                                                                         is_permanent: true,
2240                                                                 });
2241                                                         }
2242
2243                                                         // TODO: Here (and a few other places) we assume that BADONION errors
2244                                                         // are always "sourced" from the node previous to the one which failed
2245                                                         // to decode the onion.
2246                                                         res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
2247
2248                                                         let (description, title) = errors::get_onion_error_description(error_code);
2249                                                         if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
2250                                                                 log_warn!(self, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
2251                                                         }
2252                                                         else {
2253                                                                 log_warn!(self, "Onion Error[{}({:#x})] {}", title, error_code, description);
2254                                                         }
2255                                                 } else {
2256                                                         // Useless packet that we can't use but it passed HMAC, so it
2257                                                         // definitely came from the peer in question
2258                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2259                                                                 node_id: route_hop.pubkey,
2260                                                                 is_permanent: true,
2261                                                         }), !is_from_final_node));
2262                                                 }
2263                                         }
2264                                 }
2265                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2266                         if let Some((channel_update, payment_retryable)) = res {
2267                                 (channel_update, payment_retryable, error_code_ret)
2268                         } else {
2269                                 // only not set either packet unparseable or hmac does not match with any
2270                                 // payment not retryable only when garbage is from the final node
2271                                 (None, !is_from_final_node, None)
2272                         }
2273                 } else { unreachable!(); }
2274         }
2275
2276         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2277                 let mut channel_lock = self.channel_state.lock().unwrap();
2278                 let channel_state = channel_lock.borrow_parts();
2279                 match channel_state.by_id.entry(msg.channel_id) {
2280                         hash_map::Entry::Occupied(mut chan) => {
2281                                 if chan.get().get_their_node_id() != *their_node_id {
2282                                         //TODO: here and below MsgHandleErrInternal, #153 case
2283                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2284                                 }
2285                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2286                         },
2287                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2288                 }
2289                 Ok(())
2290         }
2291
2292         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2293                 let mut channel_lock = self.channel_state.lock().unwrap();
2294                 let channel_state = channel_lock.borrow_parts();
2295                 match channel_state.by_id.entry(msg.channel_id) {
2296                         hash_map::Entry::Occupied(mut chan) => {
2297                                 if chan.get().get_their_node_id() != *their_node_id {
2298                                         //TODO: here and below MsgHandleErrInternal, #153 case
2299                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2300                                 }
2301                                 if (msg.failure_code & 0x8000) == 0 {
2302                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2303                                 }
2304                                 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);
2305                                 Ok(())
2306                         },
2307                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2308                 }
2309         }
2310
2311         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2312                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2313                 let channel_state = channel_state_lock.borrow_parts();
2314                 match channel_state.by_id.entry(msg.channel_id) {
2315                         hash_map::Entry::Occupied(mut chan) => {
2316                                 if chan.get().get_their_node_id() != *their_node_id {
2317                                         //TODO: here and below MsgHandleErrInternal, #153 case
2318                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2319                                 }
2320                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2321                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2322                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2323                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2324                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2325                                 }
2326                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2327                                         node_id: their_node_id.clone(),
2328                                         msg: revoke_and_ack,
2329                                 });
2330                                 if let Some(msg) = commitment_signed {
2331                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2332                                                 node_id: their_node_id.clone(),
2333                                                 updates: msgs::CommitmentUpdate {
2334                                                         update_add_htlcs: Vec::new(),
2335                                                         update_fulfill_htlcs: Vec::new(),
2336                                                         update_fail_htlcs: Vec::new(),
2337                                                         update_fail_malformed_htlcs: Vec::new(),
2338                                                         update_fee: None,
2339                                                         commitment_signed: msg,
2340                                                 },
2341                                         });
2342                                 }
2343                                 if let Some(msg) = closing_signed {
2344                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2345                                                 node_id: their_node_id.clone(),
2346                                                 msg,
2347                                         });
2348                                 }
2349                                 Ok(())
2350                         },
2351                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2352                 }
2353         }
2354
2355         #[inline]
2356         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2357                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2358                         let mut forward_event = None;
2359                         if !pending_forwards.is_empty() {
2360                                 let mut channel_state = self.channel_state.lock().unwrap();
2361                                 if channel_state.forward_htlcs.is_empty() {
2362                                         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));
2363                                         channel_state.next_forward = forward_event.unwrap();
2364                                 }
2365                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2366                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2367                                                 hash_map::Entry::Occupied(mut entry) => {
2368                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2369                                                 },
2370                                                 hash_map::Entry::Vacant(entry) => {
2371                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2372                                                 }
2373                                         }
2374                                 }
2375                         }
2376                         match forward_event {
2377                                 Some(time) => {
2378                                         let mut pending_events = self.pending_events.lock().unwrap();
2379                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2380                                                 time_forwardable: time
2381                                         });
2382                                 }
2383                                 None => {},
2384                         }
2385                 }
2386         }
2387
2388         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2389                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2390                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2391                         let channel_state = channel_state_lock.borrow_parts();
2392                         match channel_state.by_id.entry(msg.channel_id) {
2393                                 hash_map::Entry::Occupied(mut chan) => {
2394                                         if chan.get().get_their_node_id() != *their_node_id {
2395                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2396                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2397                                         }
2398                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2399                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2400                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2401                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2402                                         }
2403                                         if let Some(updates) = commitment_update {
2404                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2405                                                         node_id: their_node_id.clone(),
2406                                                         updates,
2407                                                 });
2408                                         }
2409                                         if let Some(msg) = closing_signed {
2410                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2411                                                         node_id: their_node_id.clone(),
2412                                                         msg,
2413                                                 });
2414                                         }
2415                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2416                                 },
2417                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2418                         }
2419                 };
2420                 for failure in pending_failures.drain(..) {
2421                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2422                 }
2423                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2424
2425                 Ok(())
2426         }
2427
2428         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2429                 let mut channel_lock = self.channel_state.lock().unwrap();
2430                 let channel_state = channel_lock.borrow_parts();
2431                 match channel_state.by_id.entry(msg.channel_id) {
2432                         hash_map::Entry::Occupied(mut chan) => {
2433                                 if chan.get().get_their_node_id() != *their_node_id {
2434                                         //TODO: here and below MsgHandleErrInternal, #153 case
2435                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2436                                 }
2437                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2438                         },
2439                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2440                 }
2441                 Ok(())
2442         }
2443
2444         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2445                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2446                 let channel_state = channel_state_lock.borrow_parts();
2447
2448                 match channel_state.by_id.entry(msg.channel_id) {
2449                         hash_map::Entry::Occupied(mut chan) => {
2450                                 if chan.get().get_their_node_id() != *their_node_id {
2451                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2452                                 }
2453                                 if !chan.get().is_usable() {
2454                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2455                                 }
2456
2457                                 let our_node_id = self.get_our_node_id();
2458                                 let (announcement, our_bitcoin_sig) =
2459                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2460
2461                                 let were_node_one = announcement.node_id_1 == our_node_id;
2462                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2463                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2464                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2465                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2466                                 }
2467
2468                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2469
2470                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2471                                         msg: msgs::ChannelAnnouncement {
2472                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2473                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2474                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2475                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2476                                                 contents: announcement,
2477                                         },
2478                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2479                                 });
2480                         },
2481                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2482                 }
2483                 Ok(())
2484         }
2485
2486         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2487                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2488                 let channel_state = channel_state_lock.borrow_parts();
2489
2490                 match channel_state.by_id.entry(msg.channel_id) {
2491                         hash_map::Entry::Occupied(mut chan) => {
2492                                 if chan.get().get_their_node_id() != *their_node_id {
2493                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2494                                 }
2495                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2496                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2497                                 if let Some(monitor) = channel_monitor {
2498                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2499                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2500                                                 // for the messages it returns, but if we're setting what messages to
2501                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2502                                                 if revoke_and_ack.is_none() {
2503                                                         order = RAACommitmentOrder::CommitmentFirst;
2504                                                 }
2505                                                 if commitment_update.is_none() {
2506                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2507                                                 }
2508                                                 return_monitor_err!(self, e, channel_state, chan, order);
2509                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2510                                         }
2511                                 }
2512                                 if let Some(msg) = funding_locked {
2513                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2514                                                 node_id: their_node_id.clone(),
2515                                                 msg
2516                                         });
2517                                 }
2518                                 macro_rules! send_raa { () => {
2519                                         if let Some(msg) = revoke_and_ack {
2520                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2521                                                         node_id: their_node_id.clone(),
2522                                                         msg
2523                                                 });
2524                                         }
2525                                 } }
2526                                 macro_rules! send_cu { () => {
2527                                         if let Some(updates) = commitment_update {
2528                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2529                                                         node_id: their_node_id.clone(),
2530                                                         updates
2531                                                 });
2532                                         }
2533                                 } }
2534                                 match order {
2535                                         RAACommitmentOrder::RevokeAndACKFirst => {
2536                                                 send_raa!();
2537                                                 send_cu!();
2538                                         },
2539                                         RAACommitmentOrder::CommitmentFirst => {
2540                                                 send_cu!();
2541                                                 send_raa!();
2542                                         },
2543                                 }
2544                                 if let Some(msg) = shutdown {
2545                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2546                                                 node_id: their_node_id.clone(),
2547                                                 msg,
2548                                         });
2549                                 }
2550                                 Ok(())
2551                         },
2552                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2553                 }
2554         }
2555
2556         /// Begin Update fee process. Allowed only on an outbound channel.
2557         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2558         /// PeerManager::process_events afterwards.
2559         /// Note: This API is likely to change!
2560         #[doc(hidden)]
2561         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2562                 let _ = self.total_consistency_lock.read().unwrap();
2563                 let their_node_id;
2564                 let err: Result<(), _> = loop {
2565                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2566                         let channel_state = channel_state_lock.borrow_parts();
2567
2568                         match channel_state.by_id.entry(channel_id) {
2569                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2570                                 hash_map::Entry::Occupied(mut chan) => {
2571                                         if !chan.get().is_outbound() {
2572                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2573                                         }
2574                                         if chan.get().is_awaiting_monitor_update() {
2575                                                 return Err(APIError::MonitorUpdateFailed);
2576                                         }
2577                                         if !chan.get().is_live() {
2578                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2579                                         }
2580                                         their_node_id = chan.get().get_their_node_id();
2581                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2582                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2583                                         {
2584                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2585                                                         unimplemented!();
2586                                                 }
2587                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2588                                                         node_id: chan.get().get_their_node_id(),
2589                                                         updates: msgs::CommitmentUpdate {
2590                                                                 update_add_htlcs: Vec::new(),
2591                                                                 update_fulfill_htlcs: Vec::new(),
2592                                                                 update_fail_htlcs: Vec::new(),
2593                                                                 update_fail_malformed_htlcs: Vec::new(),
2594                                                                 update_fee: Some(update_fee),
2595                                                                 commitment_signed,
2596                                                         },
2597                                                 });
2598                                         }
2599                                 },
2600                         }
2601                         return Ok(())
2602                 };
2603
2604                 match handle_error!(self, err, their_node_id) {
2605                         Ok(_) => unreachable!(),
2606                         Err(e) => {
2607                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2608                                 } else {
2609                                         log_error!(self, "Got bad keys: {}!", e.err);
2610                                         let mut channel_state = self.channel_state.lock().unwrap();
2611                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2612                                                 node_id: their_node_id,
2613                                                 action: e.action,
2614                                         });
2615                                 }
2616                                 Err(APIError::APIMisuseError { err: e.err })
2617                         },
2618                 }
2619         }
2620 }
2621
2622 impl events::MessageSendEventsProvider for ChannelManager {
2623         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2624                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2625                 // user to serialize a ChannelManager with pending events in it and lose those events on
2626                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2627                 {
2628                         //TODO: This behavior should be documented.
2629                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2630                                 if let Some(preimage) = htlc_update.payment_preimage {
2631                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2632                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2633                                 } else {
2634                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2635                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2636                                 }
2637                         }
2638                 }
2639
2640                 let mut ret = Vec::new();
2641                 let mut channel_state = self.channel_state.lock().unwrap();
2642                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2643                 ret
2644         }
2645 }
2646
2647 impl events::EventsProvider for ChannelManager {
2648         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2649                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2650                 // user to serialize a ChannelManager with pending events in it and lose those events on
2651                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2652                 {
2653                         //TODO: This behavior should be documented.
2654                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2655                                 if let Some(preimage) = htlc_update.payment_preimage {
2656                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2657                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2658                                 } else {
2659                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2660                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2661                                 }
2662                         }
2663                 }
2664
2665                 let mut ret = Vec::new();
2666                 let mut pending_events = self.pending_events.lock().unwrap();
2667                 mem::swap(&mut ret, &mut *pending_events);
2668                 ret
2669         }
2670 }
2671
2672 impl ChainListener for ChannelManager {
2673         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2674                 let header_hash = header.bitcoin_hash();
2675                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2676                 let _ = self.total_consistency_lock.read().unwrap();
2677                 let mut failed_channels = Vec::new();
2678                 {
2679                         let mut channel_lock = self.channel_state.lock().unwrap();
2680                         let channel_state = channel_lock.borrow_parts();
2681                         let short_to_id = channel_state.short_to_id;
2682                         let pending_msg_events = channel_state.pending_msg_events;
2683                         channel_state.by_id.retain(|_, channel| {
2684                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2685                                 if let Ok(Some(funding_locked)) = chan_res {
2686                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2687                                                 node_id: channel.get_their_node_id(),
2688                                                 msg: funding_locked,
2689                                         });
2690                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2691                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2692                                                         node_id: channel.get_their_node_id(),
2693                                                         msg: announcement_sigs,
2694                                                 });
2695                                         }
2696                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2697                                 } else if let Err(e) = chan_res {
2698                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2699                                                 node_id: channel.get_their_node_id(),
2700                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2701                                         });
2702                                         return false;
2703                                 }
2704                                 if let Some(funding_txo) = channel.get_funding_txo() {
2705                                         for tx in txn_matched {
2706                                                 for inp in tx.input.iter() {
2707                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2708                                                                 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2709                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2710                                                                         short_to_id.remove(&short_id);
2711                                                                 }
2712                                                                 // It looks like our counterparty went on-chain. We go ahead and
2713                                                                 // broadcast our latest local state as well here, just in case its
2714                                                                 // some kind of SPV attack, though we expect these to be dropped.
2715                                                                 failed_channels.push(channel.force_shutdown());
2716                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2717                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2718                                                                                 msg: update
2719                                                                         });
2720                                                                 }
2721                                                                 return false;
2722                                                         }
2723                                                 }
2724                                         }
2725                                 }
2726                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2727                                         if let Some(short_id) = channel.get_short_channel_id() {
2728                                                 short_to_id.remove(&short_id);
2729                                         }
2730                                         failed_channels.push(channel.force_shutdown());
2731                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2732                                         // the latest local tx for us, so we should skip that here (it doesn't really
2733                                         // hurt anything, but does make tests a bit simpler).
2734                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2735                                         if let Ok(update) = self.get_channel_update(&channel) {
2736                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2737                                                         msg: update
2738                                                 });
2739                                         }
2740                                         return false;
2741                                 }
2742                                 true
2743                         });
2744                 }
2745                 for failure in failed_channels.drain(..) {
2746                         self.finish_force_close_channel(failure);
2747                 }
2748                 self.latest_block_height.store(height as usize, Ordering::Release);
2749                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2750         }
2751
2752         /// We force-close the channel without letting our counterparty participate in the shutdown
2753         fn block_disconnected(&self, header: &BlockHeader) {
2754                 let _ = self.total_consistency_lock.read().unwrap();
2755                 let mut failed_channels = Vec::new();
2756                 {
2757                         let mut channel_lock = self.channel_state.lock().unwrap();
2758                         let channel_state = channel_lock.borrow_parts();
2759                         let short_to_id = channel_state.short_to_id;
2760                         let pending_msg_events = channel_state.pending_msg_events;
2761                         channel_state.by_id.retain(|_,  v| {
2762                                 if v.block_disconnected(header) {
2763                                         if let Some(short_id) = v.get_short_channel_id() {
2764                                                 short_to_id.remove(&short_id);
2765                                         }
2766                                         failed_channels.push(v.force_shutdown());
2767                                         if let Ok(update) = self.get_channel_update(&v) {
2768                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2769                                                         msg: update
2770                                                 });
2771                                         }
2772                                         false
2773                                 } else {
2774                                         true
2775                                 }
2776                         });
2777                 }
2778                 for failure in failed_channels.drain(..) {
2779                         self.finish_force_close_channel(failure);
2780                 }
2781                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2782                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2783         }
2784 }
2785
2786 impl ChannelMessageHandler for ChannelManager {
2787         //TODO: Handle errors and close channel (or so)
2788         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2789                 let _ = self.total_consistency_lock.read().unwrap();
2790                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2791         }
2792
2793         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2794                 let _ = self.total_consistency_lock.read().unwrap();
2795                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2796         }
2797
2798         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2799                 let _ = self.total_consistency_lock.read().unwrap();
2800                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2801         }
2802
2803         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2804                 let _ = self.total_consistency_lock.read().unwrap();
2805                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2806         }
2807
2808         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2809                 let _ = self.total_consistency_lock.read().unwrap();
2810                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2811         }
2812
2813         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2814                 let _ = self.total_consistency_lock.read().unwrap();
2815                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2816         }
2817
2818         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2819                 let _ = self.total_consistency_lock.read().unwrap();
2820                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2821         }
2822
2823         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2824                 let _ = self.total_consistency_lock.read().unwrap();
2825                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2826         }
2827
2828         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2829                 let _ = self.total_consistency_lock.read().unwrap();
2830                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2831         }
2832
2833         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2834                 let _ = self.total_consistency_lock.read().unwrap();
2835                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2836         }
2837
2838         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2839                 let _ = self.total_consistency_lock.read().unwrap();
2840                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2841         }
2842
2843         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2844                 let _ = self.total_consistency_lock.read().unwrap();
2845                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2846         }
2847
2848         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2849                 let _ = self.total_consistency_lock.read().unwrap();
2850                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2851         }
2852
2853         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2854                 let _ = self.total_consistency_lock.read().unwrap();
2855                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2856         }
2857
2858         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2859                 let _ = self.total_consistency_lock.read().unwrap();
2860                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2861         }
2862
2863         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2864                 let _ = self.total_consistency_lock.read().unwrap();
2865                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2866         }
2867
2868         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2869                 let _ = self.total_consistency_lock.read().unwrap();
2870                 let mut failed_channels = Vec::new();
2871                 let mut failed_payments = Vec::new();
2872                 {
2873                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2874                         let channel_state = channel_state_lock.borrow_parts();
2875                         let short_to_id = channel_state.short_to_id;
2876                         let pending_msg_events = channel_state.pending_msg_events;
2877                         if no_connection_possible {
2878                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2879                                 channel_state.by_id.retain(|_, chan| {
2880                                         if chan.get_their_node_id() == *their_node_id {
2881                                                 if let Some(short_id) = chan.get_short_channel_id() {
2882                                                         short_to_id.remove(&short_id);
2883                                                 }
2884                                                 failed_channels.push(chan.force_shutdown());
2885                                                 if let Ok(update) = self.get_channel_update(&chan) {
2886                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2887                                                                 msg: update
2888                                                         });
2889                                                 }
2890                                                 false
2891                                         } else {
2892                                                 true
2893                                         }
2894                                 });
2895                         } else {
2896                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2897                                 channel_state.by_id.retain(|_, chan| {
2898                                         if chan.get_their_node_id() == *their_node_id {
2899                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2900                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2901                                                 if !failed_adds.is_empty() {
2902                                                         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
2903                                                         failed_payments.push((chan_update, failed_adds));
2904                                                 }
2905                                                 if chan.is_shutdown() {
2906                                                         if let Some(short_id) = chan.get_short_channel_id() {
2907                                                                 short_to_id.remove(&short_id);
2908                                                         }
2909                                                         return false;
2910                                                 }
2911                                         }
2912                                         true
2913                                 })
2914                         }
2915                 }
2916                 for failure in failed_channels.drain(..) {
2917                         self.finish_force_close_channel(failure);
2918                 }
2919                 for (chan_update, mut htlc_sources) in failed_payments {
2920                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2921                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2922                         }
2923                 }
2924         }
2925
2926         fn peer_connected(&self, their_node_id: &PublicKey) {
2927                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2928
2929                 let _ = self.total_consistency_lock.read().unwrap();
2930                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2931                 let channel_state = channel_state_lock.borrow_parts();
2932                 let pending_msg_events = channel_state.pending_msg_events;
2933                 channel_state.by_id.retain(|_, chan| {
2934                         if chan.get_their_node_id() == *their_node_id {
2935                                 if !chan.have_received_message() {
2936                                         // If we created this (outbound) channel while we were disconnected from the
2937                                         // peer we probably failed to send the open_channel message, which is now
2938                                         // lost. We can't have had anything pending related to this channel, so we just
2939                                         // drop it.
2940                                         false
2941                                 } else {
2942                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2943                                                 node_id: chan.get_their_node_id(),
2944                                                 msg: chan.get_channel_reestablish(),
2945                                         });
2946                                         true
2947                                 }
2948                         } else { true }
2949                 });
2950                 //TODO: Also re-broadcast announcement_signatures
2951         }
2952
2953         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2954                 let _ = self.total_consistency_lock.read().unwrap();
2955
2956                 if msg.channel_id == [0; 32] {
2957                         for chan in self.list_channels() {
2958                                 if chan.remote_network_id == *their_node_id {
2959                                         self.force_close_channel(&chan.channel_id);
2960                                 }
2961                         }
2962                 } else {
2963                         self.force_close_channel(&msg.channel_id);
2964                 }
2965         }
2966 }
2967
2968 const SERIALIZATION_VERSION: u8 = 1;
2969 const MIN_SERIALIZATION_VERSION: u8 = 1;
2970
2971 impl Writeable for PendingForwardHTLCInfo {
2972         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2973                 if let &Some(ref onion) = &self.onion_packet {
2974                         1u8.write(writer)?;
2975                         onion.write(writer)?;
2976                 } else {
2977                         0u8.write(writer)?;
2978                 }
2979                 self.incoming_shared_secret.write(writer)?;
2980                 self.payment_hash.write(writer)?;
2981                 self.short_channel_id.write(writer)?;
2982                 self.amt_to_forward.write(writer)?;
2983                 self.outgoing_cltv_value.write(writer)?;
2984                 Ok(())
2985         }
2986 }
2987
2988 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2989         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2990                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2991                         0 => None,
2992                         1 => Some(msgs::OnionPacket::read(reader)?),
2993                         _ => return Err(DecodeError::InvalidValue),
2994                 };
2995                 Ok(PendingForwardHTLCInfo {
2996                         onion_packet,
2997                         incoming_shared_secret: Readable::read(reader)?,
2998                         payment_hash: Readable::read(reader)?,
2999                         short_channel_id: Readable::read(reader)?,
3000                         amt_to_forward: Readable::read(reader)?,
3001                         outgoing_cltv_value: Readable::read(reader)?,
3002                 })
3003         }
3004 }
3005
3006 impl Writeable for HTLCFailureMsg {
3007         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3008                 match self {
3009                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3010                                 0u8.write(writer)?;
3011                                 fail_msg.write(writer)?;
3012                         },
3013                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3014                                 1u8.write(writer)?;
3015                                 fail_msg.write(writer)?;
3016                         }
3017                 }
3018                 Ok(())
3019         }
3020 }
3021
3022 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3023         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3024                 match <u8 as Readable<R>>::read(reader)? {
3025                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3026                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3027                         _ => Err(DecodeError::InvalidValue),
3028                 }
3029         }
3030 }
3031
3032 impl Writeable for PendingHTLCStatus {
3033         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3034                 match self {
3035                         &PendingHTLCStatus::Forward(ref forward_info) => {
3036                                 0u8.write(writer)?;
3037                                 forward_info.write(writer)?;
3038                         },
3039                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3040                                 1u8.write(writer)?;
3041                                 fail_msg.write(writer)?;
3042                         }
3043                 }
3044                 Ok(())
3045         }
3046 }
3047
3048 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3049         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3050                 match <u8 as Readable<R>>::read(reader)? {
3051                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3052                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3053                         _ => Err(DecodeError::InvalidValue),
3054                 }
3055         }
3056 }
3057
3058 impl_writeable!(HTLCPreviousHopData, 0, {
3059         short_channel_id,
3060         htlc_id,
3061         incoming_packet_shared_secret
3062 });
3063
3064 impl Writeable for HTLCSource {
3065         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3066                 match self {
3067                         &HTLCSource::PreviousHopData(ref hop_data) => {
3068                                 0u8.write(writer)?;
3069                                 hop_data.write(writer)?;
3070                         },
3071                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3072                                 1u8.write(writer)?;
3073                                 route.write(writer)?;
3074                                 session_priv.write(writer)?;
3075                                 first_hop_htlc_msat.write(writer)?;
3076                         }
3077                 }
3078                 Ok(())
3079         }
3080 }
3081
3082 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3083         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3084                 match <u8 as Readable<R>>::read(reader)? {
3085                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3086                         1 => Ok(HTLCSource::OutboundRoute {
3087                                 route: Readable::read(reader)?,
3088                                 session_priv: Readable::read(reader)?,
3089                                 first_hop_htlc_msat: Readable::read(reader)?,
3090                         }),
3091                         _ => Err(DecodeError::InvalidValue),
3092                 }
3093         }
3094 }
3095
3096 impl Writeable for HTLCFailReason {
3097         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3098                 match self {
3099                         &HTLCFailReason::ErrorPacket { ref err } => {
3100                                 0u8.write(writer)?;
3101                                 err.write(writer)?;
3102                         },
3103                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3104                                 1u8.write(writer)?;
3105                                 failure_code.write(writer)?;
3106                                 data.write(writer)?;
3107                         }
3108                 }
3109                 Ok(())
3110         }
3111 }
3112
3113 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3114         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3115                 match <u8 as Readable<R>>::read(reader)? {
3116                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3117                         1 => Ok(HTLCFailReason::Reason {
3118                                 failure_code: Readable::read(reader)?,
3119                                 data: Readable::read(reader)?,
3120                         }),
3121                         _ => Err(DecodeError::InvalidValue),
3122                 }
3123         }
3124 }
3125
3126 impl_writeable!(HTLCForwardInfo, 0, {
3127         prev_short_channel_id,
3128         prev_htlc_id,
3129         forward_info
3130 });
3131
3132 impl Writeable for ChannelManager {
3133         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3134                 let _ = self.total_consistency_lock.write().unwrap();
3135
3136                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3137                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3138
3139                 self.genesis_hash.write(writer)?;
3140                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3141                 self.last_block_hash.lock().unwrap().write(writer)?;
3142
3143                 let channel_state = self.channel_state.lock().unwrap();
3144                 let mut unfunded_channels = 0;
3145                 for (_, channel) in channel_state.by_id.iter() {
3146                         if !channel.is_funding_initiated() {
3147                                 unfunded_channels += 1;
3148                         }
3149                 }
3150                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3151                 for (_, channel) in channel_state.by_id.iter() {
3152                         if channel.is_funding_initiated() {
3153                                 channel.write(writer)?;
3154                         }
3155                 }
3156
3157                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3158                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3159                         short_channel_id.write(writer)?;
3160                         (pending_forwards.len() as u64).write(writer)?;
3161                         for forward in pending_forwards {
3162                                 forward.write(writer)?;
3163                         }
3164                 }
3165
3166                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3167                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3168                         payment_hash.write(writer)?;
3169                         (previous_hops.len() as u64).write(writer)?;
3170                         for previous_hop in previous_hops {
3171                                 previous_hop.write(writer)?;
3172                         }
3173                 }
3174
3175                 Ok(())
3176         }
3177 }
3178
3179 /// Arguments for the creation of a ChannelManager that are not deserialized.
3180 ///
3181 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3182 /// is:
3183 /// 1) Deserialize all stored ChannelMonitors.
3184 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3185 ///    ChannelManager)>::read(reader, args).
3186 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3187 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3188 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3189 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3190 /// 4) Reconnect blocks on your ChannelMonitors.
3191 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3192 /// 6) Disconnect/connect blocks on the ChannelManager.
3193 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3194 ///    automatically as it does in ChannelManager::new()).
3195 pub struct ChannelManagerReadArgs<'a> {
3196         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3197         /// deserialization.
3198         pub keys_manager: Arc<KeysInterface>,
3199
3200         /// The fee_estimator for use in the ChannelManager in the future.
3201         ///
3202         /// No calls to the FeeEstimator will be made during deserialization.
3203         pub fee_estimator: Arc<FeeEstimator>,
3204         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3205         ///
3206         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3207         /// you have deserialized ChannelMonitors separately and will add them to your
3208         /// ManyChannelMonitor after deserializing this ChannelManager.
3209         pub monitor: Arc<ManyChannelMonitor>,
3210         /// The ChainWatchInterface for use in the ChannelManager in the future.
3211         ///
3212         /// No calls to the ChainWatchInterface will be made during deserialization.
3213         pub chain_monitor: Arc<ChainWatchInterface>,
3214         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3215         /// used to broadcast the latest local commitment transactions of channels which must be
3216         /// force-closed during deserialization.
3217         pub tx_broadcaster: Arc<BroadcasterInterface>,
3218         /// The Logger for use in the ChannelManager and which may be used to log information during
3219         /// deserialization.
3220         pub logger: Arc<Logger>,
3221         /// Default settings used for new channels. Any existing channels will continue to use the
3222         /// runtime settings which were stored when the ChannelManager was serialized.
3223         pub default_config: UserConfig,
3224
3225         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3226         /// value.get_funding_txo() should be the key).
3227         ///
3228         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3229         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3230         /// is true for missing channels as well. If there is a monitor missing for which we find
3231         /// channel data Err(DecodeError::InvalidValue) will be returned.
3232         ///
3233         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3234         /// this struct.
3235         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3236 }
3237
3238 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3239         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3240                 let _ver: u8 = Readable::read(reader)?;
3241                 let min_ver: u8 = Readable::read(reader)?;
3242                 if min_ver > SERIALIZATION_VERSION {
3243                         return Err(DecodeError::UnknownVersion);
3244                 }
3245
3246                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3247                 let latest_block_height: u32 = Readable::read(reader)?;
3248                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3249
3250                 let mut closed_channels = Vec::new();
3251
3252                 let channel_count: u64 = Readable::read(reader)?;
3253                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3254                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3255                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3256                 for _ in 0..channel_count {
3257                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3258                         if channel.last_block_connected != last_block_hash {
3259                                 return Err(DecodeError::InvalidValue);
3260                         }
3261
3262                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3263                         funding_txo_set.insert(funding_txo.clone());
3264                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3265                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3266                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3267                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3268                                         let mut force_close_res = channel.force_shutdown();
3269                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3270                                         closed_channels.push(force_close_res);
3271                                 } else {
3272                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3273                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3274                                         }
3275                                         by_id.insert(channel.channel_id(), channel);
3276                                 }
3277                         } else {
3278                                 return Err(DecodeError::InvalidValue);
3279                         }
3280                 }
3281
3282                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3283                         if !funding_txo_set.contains(funding_txo) {
3284                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3285                         }
3286                 }
3287
3288                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3289                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3290                 for _ in 0..forward_htlcs_count {
3291                         let short_channel_id = Readable::read(reader)?;
3292                         let pending_forwards_count: u64 = Readable::read(reader)?;
3293                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3294                         for _ in 0..pending_forwards_count {
3295                                 pending_forwards.push(Readable::read(reader)?);
3296                         }
3297                         forward_htlcs.insert(short_channel_id, pending_forwards);
3298                 }
3299
3300                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3301                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3302                 for _ in 0..claimable_htlcs_count {
3303                         let payment_hash = Readable::read(reader)?;
3304                         let previous_hops_len: u64 = Readable::read(reader)?;
3305                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3306                         for _ in 0..previous_hops_len {
3307                                 previous_hops.push(Readable::read(reader)?);
3308                         }
3309                         claimable_htlcs.insert(payment_hash, previous_hops);
3310                 }
3311
3312                 let channel_manager = ChannelManager {
3313                         genesis_hash,
3314                         fee_estimator: args.fee_estimator,
3315                         monitor: args.monitor,
3316                         chain_monitor: args.chain_monitor,
3317                         tx_broadcaster: args.tx_broadcaster,
3318
3319                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3320                         last_block_hash: Mutex::new(last_block_hash),
3321                         secp_ctx: Secp256k1::new(),
3322
3323                         channel_state: Mutex::new(ChannelHolder {
3324                                 by_id,
3325                                 short_to_id,
3326                                 next_forward: Instant::now(),
3327                                 forward_htlcs,
3328                                 claimable_htlcs,
3329                                 pending_msg_events: Vec::new(),
3330                         }),
3331                         our_network_key: args.keys_manager.get_node_secret(),
3332
3333                         pending_events: Mutex::new(Vec::new()),
3334                         total_consistency_lock: RwLock::new(()),
3335                         keys_manager: args.keys_manager,
3336                         logger: args.logger,
3337                         default_configuration: args.default_config,
3338                 };
3339
3340                 for close_res in closed_channels.drain(..) {
3341                         channel_manager.finish_force_close_channel(close_res);
3342                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3343                         //connection or two.
3344                 }
3345
3346                 Ok((last_block_hash.clone(), channel_manager))
3347         }
3348 }
3349
3350 #[cfg(test)]
3351 mod tests {
3352         use chain::chaininterface;
3353         use chain::transaction::OutPoint;
3354         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3355         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3356         use chain::keysinterface;
3357         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3358         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3359         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3360         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3361         use ln::router::{Route, RouteHop, Router};
3362         use ln::msgs;
3363         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3364         use util::test_utils;
3365         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3366         use util::errors::APIError;
3367         use util::logger::Logger;
3368         use util::ser::{Writeable, Writer, ReadableArgs};
3369         use util::config::UserConfig;
3370
3371         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3372         use bitcoin::util::bip143;
3373         use bitcoin::util::address::Address;
3374         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3375         use bitcoin::blockdata::block::{Block, BlockHeader};
3376         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3377         use bitcoin::blockdata::script::{Builder, Script};
3378         use bitcoin::blockdata::opcodes;
3379         use bitcoin::blockdata::constants::genesis_block;
3380         use bitcoin::network::constants::Network;
3381
3382         use hex;
3383
3384         use secp256k1::{Secp256k1, Message};
3385         use secp256k1::key::{PublicKey,SecretKey};
3386
3387         use crypto::sha2::Sha256;
3388         use crypto::digest::Digest;
3389
3390         use rand::{thread_rng,Rng};
3391
3392         use std::cell::RefCell;
3393         use std::collections::{BTreeSet, HashMap, HashSet};
3394         use std::default::Default;
3395         use std::rc::Rc;
3396         use std::sync::{Arc, Mutex};
3397         use std::sync::atomic::Ordering;
3398         use std::time::Instant;
3399         use std::mem;
3400
3401         fn build_test_onion_keys() -> Vec<OnionKeys> {
3402                 // Keys from BOLT 4, used in both test vector tests
3403                 let secp_ctx = Secp256k1::new();
3404
3405                 let route = Route {
3406                         hops: vec!(
3407                                         RouteHop {
3408                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3409                                                 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
3410                                         },
3411                                         RouteHop {
3412                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3413                                                 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
3414                                         },
3415                                         RouteHop {
3416                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3417                                                 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
3418                                         },
3419                                         RouteHop {
3420                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3421                                                 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
3422                                         },
3423                                         RouteHop {
3424                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3425                                                 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
3426                                         },
3427                         ),
3428                 };
3429
3430                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3431
3432                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3433                 assert_eq!(onion_keys.len(), route.hops.len());
3434                 onion_keys
3435         }
3436
3437         #[test]
3438         fn onion_vectors() {
3439                 // Packet creation test vectors from BOLT 4
3440                 let onion_keys = build_test_onion_keys();
3441
3442                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3443                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3444                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3445                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3446                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3447
3448                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3449                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3450                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3451                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3452                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3453
3454                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3455                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3456                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3457                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3458                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3459
3460                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3461                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3462                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3463                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3464                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3465
3466                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3467                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3468                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3469                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3470                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3471
3472                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3473                 let payloads = vec!(
3474                         msgs::OnionHopData {
3475                                 realm: 0,
3476                                 data: msgs::OnionRealm0HopData {
3477                                         short_channel_id: 0,
3478                                         amt_to_forward: 0,
3479                                         outgoing_cltv_value: 0,
3480                                 },
3481                                 hmac: [0; 32],
3482                         },
3483                         msgs::OnionHopData {
3484                                 realm: 0,
3485                                 data: msgs::OnionRealm0HopData {
3486                                         short_channel_id: 0x0101010101010101,
3487                                         amt_to_forward: 0x0100000001,
3488                                         outgoing_cltv_value: 0,
3489                                 },
3490                                 hmac: [0; 32],
3491                         },
3492                         msgs::OnionHopData {
3493                                 realm: 0,
3494                                 data: msgs::OnionRealm0HopData {
3495                                         short_channel_id: 0x0202020202020202,
3496                                         amt_to_forward: 0x0200000002,
3497                                         outgoing_cltv_value: 0,
3498                                 },
3499                                 hmac: [0; 32],
3500                         },
3501                         msgs::OnionHopData {
3502                                 realm: 0,
3503                                 data: msgs::OnionRealm0HopData {
3504                                         short_channel_id: 0x0303030303030303,
3505                                         amt_to_forward: 0x0300000003,
3506                                         outgoing_cltv_value: 0,
3507                                 },
3508                                 hmac: [0; 32],
3509                         },
3510                         msgs::OnionHopData {
3511                                 realm: 0,
3512                                 data: msgs::OnionRealm0HopData {
3513                                         short_channel_id: 0x0404040404040404,
3514                                         amt_to_forward: 0x0400000004,
3515                                         outgoing_cltv_value: 0,
3516                                 },
3517                                 hmac: [0; 32],
3518                         },
3519                 );
3520
3521                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3522                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3523                 // anyway...
3524                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3525         }
3526
3527         #[test]
3528         fn test_failure_packet_onion() {
3529                 // Returning Errors test vectors from BOLT 4
3530
3531                 let onion_keys = build_test_onion_keys();
3532                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3533                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3534
3535                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3536                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3537
3538                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3539                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3540
3541                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3542                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3543
3544                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3545                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3546
3547                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3548                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3549         }
3550
3551         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3552                 assert!(chain.does_match_tx(tx));
3553                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3554                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3555                 for i in 2..100 {
3556                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3557                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3558                 }
3559         }
3560
3561         struct Node {
3562                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3563                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3564                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3565                 node: Arc<ChannelManager>,
3566                 router: Router,
3567                 node_seed: [u8; 32],
3568                 network_payment_count: Rc<RefCell<u8>>,
3569                 network_chan_count: Rc<RefCell<u32>>,
3570         }
3571         impl Drop for Node {
3572                 fn drop(&mut self) {
3573                         if !::std::thread::panicking() {
3574                                 // Check that we processed all pending events
3575                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3576                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3577                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3578                         }
3579                 }
3580         }
3581
3582         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3583                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3584         }
3585
3586         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) {
3587                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3588                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3589                 (announcement, as_update, bs_update, channel_id, tx)
3590         }
3591
3592         macro_rules! get_revoke_commit_msgs {
3593                 ($node: expr, $node_id: expr) => {
3594                         {
3595                                 let events = $node.node.get_and_clear_pending_msg_events();
3596                                 assert_eq!(events.len(), 2);
3597                                 (match events[0] {
3598                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3599                                                 assert_eq!(*node_id, $node_id);
3600                                                 (*msg).clone()
3601                                         },
3602                                         _ => panic!("Unexpected event"),
3603                                 }, match events[1] {
3604                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3605                                                 assert_eq!(*node_id, $node_id);
3606                                                 assert!(updates.update_add_htlcs.is_empty());
3607                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3608                                                 assert!(updates.update_fail_htlcs.is_empty());
3609                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3610                                                 assert!(updates.update_fee.is_none());
3611                                                 updates.commitment_signed.clone()
3612                                         },
3613                                         _ => panic!("Unexpected event"),
3614                                 })
3615                         }
3616                 }
3617         }
3618
3619         macro_rules! get_event_msg {
3620                 ($node: expr, $event_type: path, $node_id: expr) => {
3621                         {
3622                                 let events = $node.node.get_and_clear_pending_msg_events();
3623                                 assert_eq!(events.len(), 1);
3624                                 match events[0] {
3625                                         $event_type { ref node_id, ref msg } => {
3626                                                 assert_eq!(*node_id, $node_id);
3627                                                 (*msg).clone()
3628                                         },
3629                                         _ => panic!("Unexpected event"),
3630                                 }
3631                         }
3632                 }
3633         }
3634
3635         macro_rules! get_htlc_update_msgs {
3636                 ($node: expr, $node_id: expr) => {
3637                         {
3638                                 let events = $node.node.get_and_clear_pending_msg_events();
3639                                 assert_eq!(events.len(), 1);
3640                                 match events[0] {
3641                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3642                                                 assert_eq!(*node_id, $node_id);
3643                                                 (*updates).clone()
3644                                         },
3645                                         _ => panic!("Unexpected event"),
3646                                 }
3647                         }
3648                 }
3649         }
3650
3651         macro_rules! get_feerate {
3652                 ($node: expr, $channel_id: expr) => {
3653                         {
3654                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3655                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3656                                 chan.get_feerate()
3657                         }
3658                 }
3659         }
3660
3661
3662         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3663                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3664                 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();
3665                 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();
3666
3667                 let chan_id = *node_a.network_chan_count.borrow();
3668                 let tx;
3669                 let funding_output;
3670
3671                 let events_2 = node_a.node.get_and_clear_pending_events();
3672                 assert_eq!(events_2.len(), 1);
3673                 match events_2[0] {
3674                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3675                                 assert_eq!(*channel_value_satoshis, channel_value);
3676                                 assert_eq!(user_channel_id, 42);
3677
3678                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3679                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3680                                 }]};
3681                                 funding_output = OutPoint::new(tx.txid(), 0);
3682
3683                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3684                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3685                                 assert_eq!(added_monitors.len(), 1);
3686                                 assert_eq!(added_monitors[0].0, funding_output);
3687                                 added_monitors.clear();
3688                         },
3689                         _ => panic!("Unexpected event"),
3690                 }
3691
3692                 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();
3693                 {
3694                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3695                         assert_eq!(added_monitors.len(), 1);
3696                         assert_eq!(added_monitors[0].0, funding_output);
3697                         added_monitors.clear();
3698                 }
3699
3700                 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();
3701                 {
3702                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3703                         assert_eq!(added_monitors.len(), 1);
3704                         assert_eq!(added_monitors[0].0, funding_output);
3705                         added_monitors.clear();
3706                 }
3707
3708                 let events_4 = node_a.node.get_and_clear_pending_events();
3709                 assert_eq!(events_4.len(), 1);
3710                 match events_4[0] {
3711                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3712                                 assert_eq!(user_channel_id, 42);
3713                                 assert_eq!(*funding_txo, funding_output);
3714                         },
3715                         _ => panic!("Unexpected event"),
3716                 };
3717
3718                 tx
3719         }
3720
3721         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3722                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3723                 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();
3724
3725                 let channel_id;
3726
3727                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3728                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3729                 assert_eq!(events_6.len(), 2);
3730                 ((match events_6[0] {
3731                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3732                                 channel_id = msg.channel_id.clone();
3733                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3734                                 msg.clone()
3735                         },
3736                         _ => panic!("Unexpected event"),
3737                 }, match events_6[1] {
3738                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3739                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3740                                 msg.clone()
3741                         },
3742                         _ => panic!("Unexpected event"),
3743                 }), channel_id)
3744         }
3745
3746         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) {
3747                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3748                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3749                 (msgs, chan_id, tx)
3750         }
3751
3752         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) {
3753                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3754                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3755                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3756
3757                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3758                 assert_eq!(events_7.len(), 1);
3759                 let (announcement, bs_update) = match events_7[0] {
3760                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3761                                 (msg, update_msg)
3762                         },
3763                         _ => panic!("Unexpected event"),
3764                 };
3765
3766                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3767                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3768                 assert_eq!(events_8.len(), 1);
3769                 let as_update = match events_8[0] {
3770                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3771                                 assert!(*announcement == *msg);
3772                                 update_msg
3773                         },
3774                         _ => panic!("Unexpected event"),
3775                 };
3776
3777                 *node_a.network_chan_count.borrow_mut() += 1;
3778
3779                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3780         }
3781
3782         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3783                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3784         }
3785
3786         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) {
3787                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3788                 for node in nodes {
3789                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3790                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3791                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3792                 }
3793                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3794         }
3795
3796         macro_rules! check_spends {
3797                 ($tx: expr, $spends_tx: expr) => {
3798                         {
3799                                 let mut funding_tx_map = HashMap::new();
3800                                 let spends_tx = $spends_tx;
3801                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3802                                 $tx.verify(&funding_tx_map).unwrap();
3803                         }
3804                 }
3805         }
3806
3807         macro_rules! get_closing_signed_broadcast {
3808                 ($node: expr, $dest_pubkey: expr) => {
3809                         {
3810                                 let events = $node.get_and_clear_pending_msg_events();
3811                                 assert!(events.len() == 1 || events.len() == 2);
3812                                 (match events[events.len() - 1] {
3813                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3814                                                 assert_eq!(msg.contents.flags & 2, 2);
3815                                                 msg.clone()
3816                                         },
3817                                         _ => panic!("Unexpected event"),
3818                                 }, if events.len() == 2 {
3819                                         match events[0] {
3820                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3821                                                         assert_eq!(*node_id, $dest_pubkey);
3822                                                         Some(msg.clone())
3823                                                 },
3824                                                 _ => panic!("Unexpected event"),
3825                                         }
3826                                 } else { None })
3827                         }
3828                 }
3829         }
3830
3831         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) {
3832                 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) };
3833                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3834                 let (tx_a, tx_b);
3835
3836                 node_a.close_channel(channel_id).unwrap();
3837                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3838
3839                 let events_1 = node_b.get_and_clear_pending_msg_events();
3840                 assert!(events_1.len() >= 1);
3841                 let shutdown_b = match events_1[0] {
3842                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3843                                 assert_eq!(node_id, &node_a.get_our_node_id());
3844                                 msg.clone()
3845                         },
3846                         _ => panic!("Unexpected event"),
3847                 };
3848
3849                 let closing_signed_b = if !close_inbound_first {
3850                         assert_eq!(events_1.len(), 1);
3851                         None
3852                 } else {
3853                         Some(match events_1[1] {
3854                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3855                                         assert_eq!(node_id, &node_a.get_our_node_id());
3856                                         msg.clone()
3857                                 },
3858                                 _ => panic!("Unexpected event"),
3859                         })
3860                 };
3861
3862                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3863                 let (as_update, bs_update) = if close_inbound_first {
3864                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3865                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3866                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3867                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3868                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3869
3870                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3871                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3872                         assert!(none_b.is_none());
3873                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3874                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3875                         (as_update, bs_update)
3876                 } else {
3877                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3878
3879                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3880                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3881                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3882                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3883
3884                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3885                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3886                         assert!(none_a.is_none());
3887                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3888                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3889                         (as_update, bs_update)
3890                 };
3891                 assert_eq!(tx_a, tx_b);
3892                 check_spends!(tx_a, funding_tx);
3893
3894                 (as_update, bs_update, tx_a)
3895         }
3896
3897         struct SendEvent {
3898                 node_id: PublicKey,
3899                 msgs: Vec<msgs::UpdateAddHTLC>,
3900                 commitment_msg: msgs::CommitmentSigned,
3901         }
3902         impl SendEvent {
3903                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3904                         assert!(updates.update_fulfill_htlcs.is_empty());
3905                         assert!(updates.update_fail_htlcs.is_empty());
3906                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3907                         assert!(updates.update_fee.is_none());
3908                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3909                 }
3910
3911                 fn from_event(event: MessageSendEvent) -> SendEvent {
3912                         match event {
3913                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3914                                 _ => panic!("Unexpected event type!"),
3915                         }
3916                 }
3917
3918                 fn from_node(node: &Node) -> SendEvent {
3919                         let mut events = node.node.get_and_clear_pending_msg_events();
3920                         assert_eq!(events.len(), 1);
3921                         SendEvent::from_event(events.pop().unwrap())
3922                 }
3923         }
3924
3925         macro_rules! check_added_monitors {
3926                 ($node: expr, $count: expr) => {
3927                         {
3928                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3929                                 assert_eq!(added_monitors.len(), $count);
3930                                 added_monitors.clear();
3931                         }
3932                 }
3933         }
3934
3935         macro_rules! commitment_signed_dance {
3936                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3937                         {
3938                                 check_added_monitors!($node_a, 0);
3939                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3940                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3941                                 check_added_monitors!($node_a, 1);
3942                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3943                         }
3944                 };
3945                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3946                         {
3947                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3948                                 check_added_monitors!($node_b, 0);
3949                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3950                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3951                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3952                                 check_added_monitors!($node_b, 1);
3953                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3954                                 let (bs_revoke_and_ack, extra_msg_option) = {
3955                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3956                                         assert!(events.len() <= 2);
3957                                         (match events[0] {
3958                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3959                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3960                                                         (*msg).clone()
3961                                                 },
3962                                                 _ => panic!("Unexpected event"),
3963                                         }, events.get(1).map(|e| e.clone()))
3964                                 };
3965                                 check_added_monitors!($node_b, 1);
3966                                 if $fail_backwards {
3967                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3968                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3969                                 }
3970                                 (extra_msg_option, bs_revoke_and_ack)
3971                         }
3972                 };
3973                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3974                         {
3975                                 check_added_monitors!($node_a, 0);
3976                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3977                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3978                                 check_added_monitors!($node_a, 1);
3979                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3980                                 assert!(extra_msg_option.is_none());
3981                                 bs_revoke_and_ack
3982                         }
3983                 };
3984                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
3985                         {
3986                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
3987                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3988                                 {
3989                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
3990                                         if $fail_backwards {
3991                                                 assert_eq!(added_monitors.len(), 2);
3992                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
3993                                         } else {
3994                                                 assert_eq!(added_monitors.len(), 1);
3995                                         }
3996                                         added_monitors.clear();
3997                                 }
3998                                 extra_msg_option
3999                         }
4000                 };
4001                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4002                         {
4003                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4004                         }
4005                 };
4006                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4007                         {
4008                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4009                                 if $fail_backwards {
4010                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4011                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4012                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4013                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4014                                         } else { panic!("Unexpected event"); }
4015                                 } else {
4016                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4017                                 }
4018                         }
4019                 }
4020         }
4021
4022         macro_rules! get_payment_preimage_hash {
4023                 ($node: expr) => {
4024                         {
4025                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4026                                 *$node.network_payment_count.borrow_mut() += 1;
4027                                 let mut payment_hash = PaymentHash([0; 32]);
4028                                 let mut sha = Sha256::new();
4029                                 sha.input(&payment_preimage.0[..]);
4030                                 sha.result(&mut payment_hash.0[..]);
4031                                 (payment_preimage, payment_hash)
4032                         }
4033                 }
4034         }
4035
4036         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4037                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4038
4039                 let mut payment_event = {
4040                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4041                         check_added_monitors!(origin_node, 1);
4042
4043                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4044                         assert_eq!(events.len(), 1);
4045                         SendEvent::from_event(events.remove(0))
4046                 };
4047                 let mut prev_node = origin_node;
4048
4049                 for (idx, &node) in expected_route.iter().enumerate() {
4050                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4051
4052                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4053                         check_added_monitors!(node, 0);
4054                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4055
4056                         let events_1 = node.node.get_and_clear_pending_events();
4057                         assert_eq!(events_1.len(), 1);
4058                         match events_1[0] {
4059                                 Event::PendingHTLCsForwardable { .. } => { },
4060                                 _ => panic!("Unexpected event"),
4061                         };
4062
4063                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4064                         node.node.process_pending_htlc_forwards();
4065
4066                         if idx == expected_route.len() - 1 {
4067                                 let events_2 = node.node.get_and_clear_pending_events();
4068                                 assert_eq!(events_2.len(), 1);
4069                                 match events_2[0] {
4070                                         Event::PaymentReceived { ref payment_hash, amt } => {
4071                                                 assert_eq!(our_payment_hash, *payment_hash);
4072                                                 assert_eq!(amt, recv_value);
4073                                         },
4074                                         _ => panic!("Unexpected event"),
4075                                 }
4076                         } else {
4077                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4078                                 assert_eq!(events_2.len(), 1);
4079                                 check_added_monitors!(node, 1);
4080                                 payment_event = SendEvent::from_event(events_2.remove(0));
4081                                 assert_eq!(payment_event.msgs.len(), 1);
4082                         }
4083
4084                         prev_node = node;
4085                 }
4086
4087                 (our_payment_preimage, our_payment_hash)
4088         }
4089
4090         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4091                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4092                 check_added_monitors!(expected_route.last().unwrap(), 1);
4093
4094                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4095                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4096                 macro_rules! get_next_msgs {
4097                         ($node: expr) => {
4098                                 {
4099                                         let events = $node.node.get_and_clear_pending_msg_events();
4100                                         assert_eq!(events.len(), 1);
4101                                         match events[0] {
4102                                                 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 } } => {
4103                                                         assert!(update_add_htlcs.is_empty());
4104                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4105                                                         assert!(update_fail_htlcs.is_empty());
4106                                                         assert!(update_fail_malformed_htlcs.is_empty());
4107                                                         assert!(update_fee.is_none());
4108                                                         expected_next_node = node_id.clone();
4109                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4110                                                 },
4111                                                 _ => panic!("Unexpected event"),
4112                                         }
4113                                 }
4114                         }
4115                 }
4116
4117                 macro_rules! last_update_fulfill_dance {
4118                         ($node: expr, $prev_node: expr) => {
4119                                 {
4120                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4121                                         check_added_monitors!($node, 0);
4122                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4123                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4124                                 }
4125                         }
4126                 }
4127                 macro_rules! mid_update_fulfill_dance {
4128                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4129                                 {
4130                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4131                                         check_added_monitors!($node, 1);
4132                                         let new_next_msgs = if $new_msgs {
4133                                                 get_next_msgs!($node)
4134                                         } else {
4135                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4136                                                 None
4137                                         };
4138                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4139                                         next_msgs = new_next_msgs;
4140                                 }
4141                         }
4142                 }
4143
4144                 let mut prev_node = expected_route.last().unwrap();
4145                 for (idx, node) in expected_route.iter().rev().enumerate() {
4146                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4147                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4148                         if next_msgs.is_some() {
4149                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4150                         } else if update_next_msgs {
4151                                 next_msgs = get_next_msgs!(node);
4152                         } else {
4153                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4154                         }
4155                         if !skip_last && idx == expected_route.len() - 1 {
4156                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4157                         }
4158
4159                         prev_node = node;
4160                 }
4161
4162                 if !skip_last {
4163                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4164                         let events = origin_node.node.get_and_clear_pending_events();
4165                         assert_eq!(events.len(), 1);
4166                         match events[0] {
4167                                 Event::PaymentSent { payment_preimage } => {
4168                                         assert_eq!(payment_preimage, our_payment_preimage);
4169                                 },
4170                                 _ => panic!("Unexpected event"),
4171                         }
4172                 }
4173         }
4174
4175         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4176                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4177         }
4178
4179         const TEST_FINAL_CLTV: u32 = 32;
4180
4181         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4182                 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();
4183                 assert_eq!(route.hops.len(), expected_route.len());
4184                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4185                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4186                 }
4187
4188                 send_along_route(origin_node, route, expected_route, recv_value)
4189         }
4190
4191         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4192                 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();
4193                 assert_eq!(route.hops.len(), expected_route.len());
4194                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4195                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4196                 }
4197
4198                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4199
4200                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4201                 match err {
4202                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4203                         _ => panic!("Unknown error variants"),
4204                 };
4205         }
4206
4207         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4208                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4209                 claim_payment(&origin, expected_route, our_payment_preimage);
4210         }
4211
4212         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4213                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4214                 check_added_monitors!(expected_route.last().unwrap(), 1);
4215
4216                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4217                 macro_rules! update_fail_dance {
4218                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4219                                 {
4220                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4221                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4222                                 }
4223                         }
4224                 }
4225
4226                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4227                 let mut prev_node = expected_route.last().unwrap();
4228                 for (idx, node) in expected_route.iter().rev().enumerate() {
4229                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4230                         if next_msgs.is_some() {
4231                                 // We may be the "last node" for the purpose of the commitment dance if we're
4232                                 // skipping the last node (implying it is disconnected) and we're the
4233                                 // second-to-last node!
4234                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4235                         }
4236
4237                         let events = node.node.get_and_clear_pending_msg_events();
4238                         if !skip_last || idx != expected_route.len() - 1 {
4239                                 assert_eq!(events.len(), 1);
4240                                 match events[0] {
4241                                         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 } } => {
4242                                                 assert!(update_add_htlcs.is_empty());
4243                                                 assert!(update_fulfill_htlcs.is_empty());
4244                                                 assert_eq!(update_fail_htlcs.len(), 1);
4245                                                 assert!(update_fail_malformed_htlcs.is_empty());
4246                                                 assert!(update_fee.is_none());
4247                                                 expected_next_node = node_id.clone();
4248                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4249                                         },
4250                                         _ => panic!("Unexpected event"),
4251                                 }
4252                         } else {
4253                                 assert!(events.is_empty());
4254                         }
4255                         if !skip_last && idx == expected_route.len() - 1 {
4256                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4257                         }
4258
4259                         prev_node = node;
4260                 }
4261
4262                 if !skip_last {
4263                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4264
4265                         let events = origin_node.node.get_and_clear_pending_events();
4266                         assert_eq!(events.len(), 1);
4267                         match events[0] {
4268                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4269                                         assert_eq!(payment_hash, our_payment_hash);
4270                                         assert!(rejected_by_dest);
4271                                 },
4272                                 _ => panic!("Unexpected event"),
4273                         }
4274                 }
4275         }
4276
4277         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4278                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4279         }
4280
4281         fn create_network(node_count: usize) -> Vec<Node> {
4282                 let mut nodes = Vec::new();
4283                 let mut rng = thread_rng();
4284                 let secp_ctx = Secp256k1::new();
4285
4286                 let chan_count = Rc::new(RefCell::new(0));
4287                 let payment_count = Rc::new(RefCell::new(0));
4288
4289                 for i in 0..node_count {
4290                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4291                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4292                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4293                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4294                         let mut seed = [0; 32];
4295                         rng.fill_bytes(&mut seed);
4296                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4297                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4298                         let mut config = UserConfig::new();
4299                         config.channel_options.announced_channel = true;
4300                         config.channel_limits.force_announced_channel_preference = false;
4301                         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();
4302                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4303                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4304                                 network_payment_count: payment_count.clone(),
4305                                 network_chan_count: chan_count.clone(),
4306                         });
4307                 }
4308
4309                 nodes
4310         }
4311
4312         #[test]
4313         fn test_async_inbound_update_fee() {
4314                 let mut nodes = create_network(2);
4315                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4316                 let channel_id = chan.2;
4317
4318                 // balancing
4319                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4320
4321                 // A                                        B
4322                 // update_fee                            ->
4323                 // send (1) commitment_signed            -.
4324                 //                                       <- update_add_htlc/commitment_signed
4325                 // send (2) RAA (awaiting remote revoke) -.
4326                 // (1) commitment_signed is delivered    ->
4327                 //                                       .- send (3) RAA (awaiting remote revoke)
4328                 // (2) RAA is delivered                  ->
4329                 //                                       .- send (4) commitment_signed
4330                 //                                       <- (3) RAA is delivered
4331                 // send (5) commitment_signed            -.
4332                 //                                       <- (4) commitment_signed is delivered
4333                 // send (6) RAA                          -.
4334                 // (5) commitment_signed is delivered    ->
4335                 //                                       <- RAA
4336                 // (6) RAA is delivered                  ->
4337
4338                 // First nodes[0] generates an update_fee
4339                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4340                 check_added_monitors!(nodes[0], 1);
4341
4342                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4343                 assert_eq!(events_0.len(), 1);
4344                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4345                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4346                                 (update_fee.as_ref(), commitment_signed)
4347                         },
4348                         _ => panic!("Unexpected event"),
4349                 };
4350
4351                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4352
4353                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4354                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4355                 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();
4356                 check_added_monitors!(nodes[1], 1);
4357
4358                 let payment_event = {
4359                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4360                         assert_eq!(events_1.len(), 1);
4361                         SendEvent::from_event(events_1.remove(0))
4362                 };
4363                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4364                 assert_eq!(payment_event.msgs.len(), 1);
4365
4366                 // ...now when the messages get delivered everyone should be happy
4367                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4368                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4369                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4370                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4371                 check_added_monitors!(nodes[0], 1);
4372
4373                 // deliver(1), generate (3):
4374                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4375                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4376                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4377                 check_added_monitors!(nodes[1], 1);
4378
4379                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4380                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4381                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4382                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4383                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4384                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4385                 assert!(bs_update.update_fee.is_none()); // (4)
4386                 check_added_monitors!(nodes[1], 1);
4387
4388                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4389                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4390                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4391                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4392                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4393                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4394                 assert!(as_update.update_fee.is_none()); // (5)
4395                 check_added_monitors!(nodes[0], 1);
4396
4397                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4398                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4399                 // only (6) so get_event_msg's assert(len == 1) passes
4400                 check_added_monitors!(nodes[0], 1);
4401
4402                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4403                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4404                 check_added_monitors!(nodes[1], 1);
4405
4406                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4407                 check_added_monitors!(nodes[0], 1);
4408
4409                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4410                 assert_eq!(events_2.len(), 1);
4411                 match events_2[0] {
4412                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4413                         _ => panic!("Unexpected event"),
4414                 }
4415
4416                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4417                 check_added_monitors!(nodes[1], 1);
4418         }
4419
4420         #[test]
4421         fn test_update_fee_unordered_raa() {
4422                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4423                 // crash in an earlier version of the update_fee patch)
4424                 let mut nodes = create_network(2);
4425                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4426                 let channel_id = chan.2;
4427
4428                 // balancing
4429                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4430
4431                 // First nodes[0] generates an update_fee
4432                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4433                 check_added_monitors!(nodes[0], 1);
4434
4435                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4436                 assert_eq!(events_0.len(), 1);
4437                 let update_msg = match events_0[0] { // (1)
4438                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4439                                 update_fee.as_ref()
4440                         },
4441                         _ => panic!("Unexpected event"),
4442                 };
4443
4444                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4445
4446                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4447                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4448                 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();
4449                 check_added_monitors!(nodes[1], 1);
4450
4451                 let payment_event = {
4452                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4453                         assert_eq!(events_1.len(), 1);
4454                         SendEvent::from_event(events_1.remove(0))
4455                 };
4456                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4457                 assert_eq!(payment_event.msgs.len(), 1);
4458
4459                 // ...now when the messages get delivered everyone should be happy
4460                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4461                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4462                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4463                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4464                 check_added_monitors!(nodes[0], 1);
4465
4466                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4467                 check_added_monitors!(nodes[1], 1);
4468
4469                 // We can't continue, sadly, because our (1) now has a bogus signature
4470         }
4471
4472         #[test]
4473         fn test_multi_flight_update_fee() {
4474                 let nodes = create_network(2);
4475                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4476                 let channel_id = chan.2;
4477
4478                 // A                                        B
4479                 // update_fee/commitment_signed          ->
4480                 //                                       .- send (1) RAA and (2) commitment_signed
4481                 // update_fee (never committed)          ->
4482                 // (3) update_fee                        ->
4483                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4484                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4485                 // AwaitingRAA mode and will not generate the update_fee yet.
4486                 //                                       <- (1) RAA delivered
4487                 // (3) is generated and send (4) CS      -.
4488                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4489                 // know the per_commitment_point to use for it.
4490                 //                                       <- (2) commitment_signed delivered
4491                 // revoke_and_ack                        ->
4492                 //                                          B should send no response here
4493                 // (4) commitment_signed delivered       ->
4494                 //                                       <- RAA/commitment_signed delivered
4495                 // revoke_and_ack                        ->
4496
4497                 // First nodes[0] generates an update_fee
4498                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4499                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4500                 check_added_monitors!(nodes[0], 1);
4501
4502                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4503                 assert_eq!(events_0.len(), 1);
4504                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4505                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4506                                 (update_fee.as_ref().unwrap(), commitment_signed)
4507                         },
4508                         _ => panic!("Unexpected event"),
4509                 };
4510
4511                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4512                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4513                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4514                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4515                 check_added_monitors!(nodes[1], 1);
4516
4517                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4518                 // transaction:
4519                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4520                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4521                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4522
4523                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4524                 let mut update_msg_2 = msgs::UpdateFee {
4525                         channel_id: update_msg_1.channel_id.clone(),
4526                         feerate_per_kw: (initial_feerate + 30) as u32,
4527                 };
4528
4529                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4530
4531                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4532                 // Deliver (3)
4533                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4534
4535                 // Deliver (1), generating (3) and (4)
4536                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4537                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4538                 check_added_monitors!(nodes[0], 1);
4539                 assert!(as_second_update.update_add_htlcs.is_empty());
4540                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4541                 assert!(as_second_update.update_fail_htlcs.is_empty());
4542                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4543                 // Check that the update_fee newly generated matches what we delivered:
4544                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4545                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4546
4547                 // Deliver (2) commitment_signed
4548                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4549                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4550                 check_added_monitors!(nodes[0], 1);
4551                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4552
4553                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4554                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4555                 check_added_monitors!(nodes[1], 1);
4556
4557                 // Delever (4)
4558                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4559                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4560                 check_added_monitors!(nodes[1], 1);
4561
4562                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4563                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4564                 check_added_monitors!(nodes[0], 1);
4565
4566                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4567                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4568                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4569                 check_added_monitors!(nodes[0], 1);
4570
4571                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4572                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4573                 check_added_monitors!(nodes[1], 1);
4574         }
4575
4576         #[test]
4577         fn test_update_fee_vanilla() {
4578                 let nodes = create_network(2);
4579                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4580                 let channel_id = chan.2;
4581
4582                 let feerate = get_feerate!(nodes[0], channel_id);
4583                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4584                 check_added_monitors!(nodes[0], 1);
4585
4586                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4587                 assert_eq!(events_0.len(), 1);
4588                 let (update_msg, commitment_signed) = match events_0[0] {
4589                                 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 } } => {
4590                                 (update_fee.as_ref(), commitment_signed)
4591                         },
4592                         _ => panic!("Unexpected event"),
4593                 };
4594                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4595
4596                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4597                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4598                 check_added_monitors!(nodes[1], 1);
4599
4600                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4601                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4602                 check_added_monitors!(nodes[0], 1);
4603
4604                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4605                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4606                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4607                 check_added_monitors!(nodes[0], 1);
4608
4609                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4610                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4611                 check_added_monitors!(nodes[1], 1);
4612         }
4613
4614         #[test]
4615         fn test_update_fee_that_funder_cannot_afford() {
4616                 let nodes = create_network(2);
4617                 let channel_value = 1888;
4618                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4619                 let channel_id = chan.2;
4620
4621                 let feerate = 260;
4622                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4623                 check_added_monitors!(nodes[0], 1);
4624                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4625
4626                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4627
4628                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4629
4630                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4631                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4632                 {
4633                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4634                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4635
4636                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4637                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4638                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4639                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4640                         actual_fee = channel_value - actual_fee;
4641                         assert_eq!(total_fee, actual_fee);
4642                 } //drop the mutex
4643
4644                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4645                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4646                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4647                 check_added_monitors!(nodes[0], 1);
4648
4649                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4650
4651                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4652
4653                 //While producing the commitment_signed response after handling a received update_fee request the
4654                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4655                 //Should produce and error.
4656                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4657
4658                 assert!(match err.err {
4659                         "Funding remote cannot afford proposed new fee" => true,
4660                         _ => false,
4661                 });
4662
4663                 //clear the message we could not handle
4664                 nodes[1].node.get_and_clear_pending_msg_events();
4665         }
4666
4667         #[test]
4668         fn test_update_fee_with_fundee_update_add_htlc() {
4669                 let mut nodes = create_network(2);
4670                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4671                 let channel_id = chan.2;
4672
4673                 // balancing
4674                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4675
4676                 let feerate = get_feerate!(nodes[0], channel_id);
4677                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4678                 check_added_monitors!(nodes[0], 1);
4679
4680                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4681                 assert_eq!(events_0.len(), 1);
4682                 let (update_msg, commitment_signed) = match events_0[0] {
4683                                 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 } } => {
4684                                 (update_fee.as_ref(), commitment_signed)
4685                         },
4686                         _ => panic!("Unexpected event"),
4687                 };
4688                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4689                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4690                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4691                 check_added_monitors!(nodes[1], 1);
4692
4693                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4694
4695                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4696
4697                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4698                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4699                 {
4700                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4701                         assert_eq!(added_monitors.len(), 0);
4702                         added_monitors.clear();
4703                 }
4704                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4705                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4706                 // node[1] has nothing to do
4707
4708                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4709                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4710                 check_added_monitors!(nodes[0], 1);
4711
4712                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4713                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4714                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4715                 check_added_monitors!(nodes[0], 1);
4716                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4717                 check_added_monitors!(nodes[1], 1);
4718                 // AwaitingRemoteRevoke ends here
4719
4720                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4721                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4722                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4723                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4724                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4725                 assert_eq!(commitment_update.update_fee.is_none(), true);
4726
4727                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4728                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4729                 check_added_monitors!(nodes[0], 1);
4730                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4731
4732                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4733                 check_added_monitors!(nodes[1], 1);
4734                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4735
4736                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4737                 check_added_monitors!(nodes[1], 1);
4738                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4739                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4740
4741                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4742                 check_added_monitors!(nodes[0], 1);
4743                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4744
4745                 let events = nodes[0].node.get_and_clear_pending_events();
4746                 assert_eq!(events.len(), 1);
4747                 match events[0] {
4748                         Event::PendingHTLCsForwardable { .. } => { },
4749                         _ => panic!("Unexpected event"),
4750                 };
4751                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4752                 nodes[0].node.process_pending_htlc_forwards();
4753
4754                 let events = nodes[0].node.get_and_clear_pending_events();
4755                 assert_eq!(events.len(), 1);
4756                 match events[0] {
4757                         Event::PaymentReceived { .. } => { },
4758                         _ => panic!("Unexpected event"),
4759                 };
4760
4761                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4762
4763                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4764                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4765                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4766         }
4767
4768         #[test]
4769         fn test_update_fee() {
4770                 let nodes = create_network(2);
4771                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4772                 let channel_id = chan.2;
4773
4774                 // A                                        B
4775                 // (1) update_fee/commitment_signed      ->
4776                 //                                       <- (2) revoke_and_ack
4777                 //                                       .- send (3) commitment_signed
4778                 // (4) update_fee/commitment_signed      ->
4779                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4780                 //                                       <- (3) commitment_signed delivered
4781                 // send (6) revoke_and_ack               -.
4782                 //                                       <- (5) deliver revoke_and_ack
4783                 // (6) deliver revoke_and_ack            ->
4784                 //                                       .- send (7) commitment_signed in response to (4)
4785                 //                                       <- (7) deliver commitment_signed
4786                 // revoke_and_ack                        ->
4787
4788                 // Create and deliver (1)...
4789                 let feerate = get_feerate!(nodes[0], channel_id);
4790                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4791                 check_added_monitors!(nodes[0], 1);
4792
4793                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4794                 assert_eq!(events_0.len(), 1);
4795                 let (update_msg, commitment_signed) = match events_0[0] {
4796                                 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 } } => {
4797                                 (update_fee.as_ref(), commitment_signed)
4798                         },
4799                         _ => panic!("Unexpected event"),
4800                 };
4801                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4802
4803                 // Generate (2) and (3):
4804                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4805                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4806                 check_added_monitors!(nodes[1], 1);
4807
4808                 // Deliver (2):
4809                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4810                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4811                 check_added_monitors!(nodes[0], 1);
4812
4813                 // Create and deliver (4)...
4814                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4815                 check_added_monitors!(nodes[0], 1);
4816                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4817                 assert_eq!(events_0.len(), 1);
4818                 let (update_msg, commitment_signed) = match events_0[0] {
4819                                 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 } } => {
4820                                 (update_fee.as_ref(), commitment_signed)
4821                         },
4822                         _ => panic!("Unexpected event"),
4823                 };
4824
4825                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4826                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4827                 check_added_monitors!(nodes[1], 1);
4828                 // ... creating (5)
4829                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4830                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4831
4832                 // Handle (3), creating (6):
4833                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4834                 check_added_monitors!(nodes[0], 1);
4835                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4836                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4837
4838                 // Deliver (5):
4839                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4840                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4841                 check_added_monitors!(nodes[0], 1);
4842
4843                 // Deliver (6), creating (7):
4844                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4845                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4846                 assert!(commitment_update.update_add_htlcs.is_empty());
4847                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4848                 assert!(commitment_update.update_fail_htlcs.is_empty());
4849                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4850                 assert!(commitment_update.update_fee.is_none());
4851                 check_added_monitors!(nodes[1], 1);
4852
4853                 // Deliver (7)
4854                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4855                 check_added_monitors!(nodes[0], 1);
4856                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4857                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4858
4859                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4860                 check_added_monitors!(nodes[1], 1);
4861                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4862
4863                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4864                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4865                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4866         }
4867
4868         #[test]
4869         fn pre_funding_lock_shutdown_test() {
4870                 // Test sending a shutdown prior to funding_locked after funding generation
4871                 let nodes = create_network(2);
4872                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4873                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4874                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4875                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4876
4877                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4878                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4879                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4880                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4881                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4882
4883                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4884                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4885                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4886                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4887                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4888                 assert!(node_0_none.is_none());
4889
4890                 assert!(nodes[0].node.list_channels().is_empty());
4891                 assert!(nodes[1].node.list_channels().is_empty());
4892         }
4893
4894         #[test]
4895         fn updates_shutdown_wait() {
4896                 // Test sending a shutdown with outstanding updates pending
4897                 let mut nodes = create_network(3);
4898                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4899                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4900                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4901                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4902
4903                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4904
4905                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4906                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4907                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4908                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4909                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4910
4911                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4912                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4913
4914                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4915                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4916                 else { panic!("New sends should fail!") };
4917                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4918                 else { panic!("New sends should fail!") };
4919
4920                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4921                 check_added_monitors!(nodes[2], 1);
4922                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4923                 assert!(updates.update_add_htlcs.is_empty());
4924                 assert!(updates.update_fail_htlcs.is_empty());
4925                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4926                 assert!(updates.update_fee.is_none());
4927                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4928                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4929                 check_added_monitors!(nodes[1], 1);
4930                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4931                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4932
4933                 assert!(updates_2.update_add_htlcs.is_empty());
4934                 assert!(updates_2.update_fail_htlcs.is_empty());
4935                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4936                 assert!(updates_2.update_fee.is_none());
4937                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4938                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4939                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4940
4941                 let events = nodes[0].node.get_and_clear_pending_events();
4942                 assert_eq!(events.len(), 1);
4943                 match events[0] {
4944                         Event::PaymentSent { ref payment_preimage } => {
4945                                 assert_eq!(our_payment_preimage, *payment_preimage);
4946                         },
4947                         _ => panic!("Unexpected event"),
4948                 }
4949
4950                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4951                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4952                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4953                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4954                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4955                 assert!(node_0_none.is_none());
4956
4957                 assert!(nodes[0].node.list_channels().is_empty());
4958
4959                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4960                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4961                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4962                 assert!(nodes[1].node.list_channels().is_empty());
4963                 assert!(nodes[2].node.list_channels().is_empty());
4964         }
4965
4966         #[test]
4967         fn htlc_fail_async_shutdown() {
4968                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4969                 let mut nodes = create_network(3);
4970                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4971                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4972
4973                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4974                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4975                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4976                 check_added_monitors!(nodes[0], 1);
4977                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4978                 assert_eq!(updates.update_add_htlcs.len(), 1);
4979                 assert!(updates.update_fulfill_htlcs.is_empty());
4980                 assert!(updates.update_fail_htlcs.is_empty());
4981                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4982                 assert!(updates.update_fee.is_none());
4983
4984                 nodes[1].node.close_channel(&chan_1.2).unwrap();
4985                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4986                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4987                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4988
4989                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
4990                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
4991                 check_added_monitors!(nodes[1], 1);
4992                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4993                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
4994
4995                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4996                 assert!(updates_2.update_add_htlcs.is_empty());
4997                 assert!(updates_2.update_fulfill_htlcs.is_empty());
4998                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
4999                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5000                 assert!(updates_2.update_fee.is_none());
5001
5002                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5003                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5004
5005                 let events = nodes[0].node.get_and_clear_pending_events();
5006                 assert_eq!(events.len(), 1);
5007                 match events[0] {
5008                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
5009                                 assert_eq!(our_payment_hash, *payment_hash);
5010                                 assert!(!rejected_by_dest);
5011                         },
5012                         _ => panic!("Unexpected event"),
5013                 }
5014
5015                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5016                 assert_eq!(msg_events.len(), 2);
5017                 let node_0_closing_signed = match msg_events[0] {
5018                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
5019                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5020                                 (*msg).clone()
5021                         },
5022                         _ => panic!("Unexpected event"),
5023                 };
5024                 match msg_events[1] {
5025                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
5026                         },
5027                         _ => panic!("Unexpected event"),
5028                 }
5029
5030                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5031                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5032                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5033                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5034                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5035                 assert!(node_0_none.is_none());
5036
5037                 assert!(nodes[0].node.list_channels().is_empty());
5038
5039                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5040                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5041                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5042                 assert!(nodes[1].node.list_channels().is_empty());
5043                 assert!(nodes[2].node.list_channels().is_empty());
5044         }
5045
5046         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5047                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5048                 // messages delivered prior to disconnect
5049                 let nodes = create_network(3);
5050                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5051                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5052
5053                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5054
5055                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5056                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5057                 if recv_count > 0 {
5058                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5059                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5060                         if recv_count > 1 {
5061                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5062                         }
5063                 }
5064
5065                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5066                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5067
5068                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5069                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5070                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5071                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5072
5073                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5074                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5075                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5076
5077                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5078                 let node_0_2nd_shutdown = if recv_count > 0 {
5079                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5080                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5081                         node_0_2nd_shutdown
5082                 } else {
5083                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5084                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5085                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5086                 };
5087                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5088
5089                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5090                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5091
5092                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5093                 check_added_monitors!(nodes[2], 1);
5094                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5095                 assert!(updates.update_add_htlcs.is_empty());
5096                 assert!(updates.update_fail_htlcs.is_empty());
5097                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5098                 assert!(updates.update_fee.is_none());
5099                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5100                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5101                 check_added_monitors!(nodes[1], 1);
5102                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5103                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5104
5105                 assert!(updates_2.update_add_htlcs.is_empty());
5106                 assert!(updates_2.update_fail_htlcs.is_empty());
5107                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5108                 assert!(updates_2.update_fee.is_none());
5109                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5110                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5111                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5112
5113                 let events = nodes[0].node.get_and_clear_pending_events();
5114                 assert_eq!(events.len(), 1);
5115                 match events[0] {
5116                         Event::PaymentSent { ref payment_preimage } => {
5117                                 assert_eq!(our_payment_preimage, *payment_preimage);
5118                         },
5119                         _ => panic!("Unexpected event"),
5120                 }
5121
5122                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5123                 if recv_count > 0 {
5124                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5125                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5126                         assert!(node_1_closing_signed.is_some());
5127                 }
5128
5129                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5130                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5131
5132                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5133                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5134                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5135                 if recv_count == 0 {
5136                         // If all closing_signeds weren't delivered we can just resume where we left off...
5137                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5138
5139                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5140                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5141                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5142
5143                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5144                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5145                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5146
5147                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5148                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5149
5150                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5151                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5152                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5153
5154                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5155                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5156                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5157                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5158                         assert!(node_0_none.is_none());
5159                 } else {
5160                         // If one node, however, received + responded with an identical closing_signed we end
5161                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5162                         // There isn't really anything better we can do simply, but in the future we might
5163                         // explore storing a set of recently-closed channels that got disconnected during
5164                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5165                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5166                         // transaction.
5167                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5168
5169                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5170                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5171                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5172                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5173                                 assert_eq!(*channel_id, chan_1.2);
5174                         } else { panic!("Needed SendErrorMessage close"); }
5175
5176                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5177                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5178                         // closing_signed so we do it ourselves
5179                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5180                         assert_eq!(events.len(), 1);
5181                         match events[0] {
5182                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5183                                         assert_eq!(msg.contents.flags & 2, 2);
5184                                 },
5185                                 _ => panic!("Unexpected event"),
5186                         }
5187                 }
5188
5189                 assert!(nodes[0].node.list_channels().is_empty());
5190
5191                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5192                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5193                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5194                 assert!(nodes[1].node.list_channels().is_empty());
5195                 assert!(nodes[2].node.list_channels().is_empty());
5196         }
5197
5198         #[test]
5199         fn test_shutdown_rebroadcast() {
5200                 do_test_shutdown_rebroadcast(0);
5201                 do_test_shutdown_rebroadcast(1);
5202                 do_test_shutdown_rebroadcast(2);
5203         }
5204
5205         #[test]
5206         fn fake_network_test() {
5207                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5208                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5209                 let nodes = create_network(4);
5210
5211                 // Create some initial channels
5212                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5213                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5214                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5215
5216                 // Rebalance the network a bit by relaying one payment through all the channels...
5217                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5218                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5219                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5220                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5221
5222                 // Send some more payments
5223                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5224                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5225                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5226
5227                 // Test failure packets
5228                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5229                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5230
5231                 // Add a new channel that skips 3
5232                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5233
5234                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5235                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5236                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5237                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5238                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5239                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5240                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5241
5242                 // Do some rebalance loop payments, simultaneously
5243                 let mut hops = Vec::with_capacity(3);
5244                 hops.push(RouteHop {
5245                         pubkey: nodes[2].node.get_our_node_id(),
5246                         short_channel_id: chan_2.0.contents.short_channel_id,
5247                         fee_msat: 0,
5248                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5249                 });
5250                 hops.push(RouteHop {
5251                         pubkey: nodes[3].node.get_our_node_id(),
5252                         short_channel_id: chan_3.0.contents.short_channel_id,
5253                         fee_msat: 0,
5254                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5255                 });
5256                 hops.push(RouteHop {
5257                         pubkey: nodes[1].node.get_our_node_id(),
5258                         short_channel_id: chan_4.0.contents.short_channel_id,
5259                         fee_msat: 1000000,
5260                         cltv_expiry_delta: TEST_FINAL_CLTV,
5261                 });
5262                 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;
5263                 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;
5264                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5265
5266                 let mut hops = Vec::with_capacity(3);
5267                 hops.push(RouteHop {
5268                         pubkey: nodes[3].node.get_our_node_id(),
5269                         short_channel_id: chan_4.0.contents.short_channel_id,
5270                         fee_msat: 0,
5271                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5272                 });
5273                 hops.push(RouteHop {
5274                         pubkey: nodes[2].node.get_our_node_id(),
5275                         short_channel_id: chan_3.0.contents.short_channel_id,
5276                         fee_msat: 0,
5277                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5278                 });
5279                 hops.push(RouteHop {
5280                         pubkey: nodes[1].node.get_our_node_id(),
5281                         short_channel_id: chan_2.0.contents.short_channel_id,
5282                         fee_msat: 1000000,
5283                         cltv_expiry_delta: TEST_FINAL_CLTV,
5284                 });
5285                 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;
5286                 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;
5287                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5288
5289                 // Claim the rebalances...
5290                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5291                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5292
5293                 // Add a duplicate new channel from 2 to 4
5294                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5295
5296                 // Send some payments across both channels
5297                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5298                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5299                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5300
5301                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5302
5303                 //TODO: Test that routes work again here as we've been notified that the channel is full
5304
5305                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5306                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5307                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5308
5309                 // Close down the channels...
5310                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5311                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5312                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5313                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5314                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5315         }
5316
5317         #[test]
5318         fn duplicate_htlc_test() {
5319                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5320                 // claiming/failing them are all separate and don't effect each other
5321                 let mut nodes = create_network(6);
5322
5323                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5324                 create_announced_chan_between_nodes(&nodes, 0, 3);
5325                 create_announced_chan_between_nodes(&nodes, 1, 3);
5326                 create_announced_chan_between_nodes(&nodes, 2, 3);
5327                 create_announced_chan_between_nodes(&nodes, 3, 4);
5328                 create_announced_chan_between_nodes(&nodes, 3, 5);
5329
5330                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5331
5332                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5333                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5334
5335                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5336                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5337
5338                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5339                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5340                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5341         }
5342
5343         #[derive(PartialEq)]
5344         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5345         /// Tests that the given node has broadcast transactions for the given Channel
5346         ///
5347         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5348         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5349         /// broadcast and the revoked outputs were claimed.
5350         ///
5351         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5352         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5353         ///
5354         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5355         /// also fail.
5356         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5357                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5358                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5359
5360                 let mut res = Vec::with_capacity(2);
5361                 node_txn.retain(|tx| {
5362                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5363                                 check_spends!(tx, chan.3.clone());
5364                                 if commitment_tx.is_none() {
5365                                         res.push(tx.clone());
5366                                 }
5367                                 false
5368                         } else { true }
5369                 });
5370                 if let Some(explicit_tx) = commitment_tx {
5371                         res.push(explicit_tx.clone());
5372                 }
5373
5374                 assert_eq!(res.len(), 1);
5375
5376                 if has_htlc_tx != HTLCType::NONE {
5377                         node_txn.retain(|tx| {
5378                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5379                                         check_spends!(tx, res[0].clone());
5380                                         if has_htlc_tx == HTLCType::TIMEOUT {
5381                                                 assert!(tx.lock_time != 0);
5382                                         } else {
5383                                                 assert!(tx.lock_time == 0);
5384                                         }
5385                                         res.push(tx.clone());
5386                                         false
5387                                 } else { true }
5388                         });
5389                         assert!(res.len() == 2 || res.len() == 3);
5390                         if res.len() == 3 {
5391                                 assert_eq!(res[1], res[2]);
5392                         }
5393                 }
5394
5395                 assert!(node_txn.is_empty());
5396                 res
5397         }
5398
5399         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5400         /// HTLC transaction.
5401         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5402                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5403                 assert_eq!(node_txn.len(), 1);
5404                 node_txn.retain(|tx| {
5405                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5406                                 check_spends!(tx, revoked_tx.clone());
5407                                 false
5408                         } else { true }
5409                 });
5410                 assert!(node_txn.is_empty());
5411         }
5412
5413         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5414                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5415
5416                 assert!(node_txn.len() >= 1);
5417                 assert_eq!(node_txn[0].input.len(), 1);
5418                 let mut found_prev = false;
5419
5420                 for tx in prev_txn {
5421                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5422                                 check_spends!(node_txn[0], tx.clone());
5423                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5424                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5425
5426                                 found_prev = true;
5427                                 break;
5428                         }
5429                 }
5430                 assert!(found_prev);
5431
5432                 let mut res = Vec::new();
5433                 mem::swap(&mut *node_txn, &mut res);
5434                 res
5435         }
5436
5437         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5438                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5439                 assert_eq!(events_1.len(), 1);
5440                 let as_update = match events_1[0] {
5441                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5442                                 msg.clone()
5443                         },
5444                         _ => panic!("Unexpected event"),
5445                 };
5446
5447                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5448                 assert_eq!(events_2.len(), 1);
5449                 let bs_update = match events_2[0] {
5450                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5451                                 msg.clone()
5452                         },
5453                         _ => panic!("Unexpected event"),
5454                 };
5455
5456                 for node in nodes {
5457                         node.router.handle_channel_update(&as_update).unwrap();
5458                         node.router.handle_channel_update(&bs_update).unwrap();
5459                 }
5460         }
5461
5462         macro_rules! expect_pending_htlcs_forwardable {
5463                 ($node: expr) => {{
5464                         let events = $node.node.get_and_clear_pending_events();
5465                         assert_eq!(events.len(), 1);
5466                         match events[0] {
5467                                 Event::PendingHTLCsForwardable { .. } => { },
5468                                 _ => panic!("Unexpected event"),
5469                         };
5470                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5471                         $node.node.process_pending_htlc_forwards();
5472                 }}
5473         }
5474
5475         fn do_channel_reserve_test(test_recv: bool) {
5476                 use util::rng;
5477                 use std::sync::atomic::Ordering;
5478                 use ln::msgs::HandleError;
5479
5480                 macro_rules! get_channel_value_stat {
5481                         ($node: expr, $channel_id: expr) => {{
5482                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5483                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5484                                 chan.get_value_stat()
5485                         }}
5486                 }
5487
5488                 let mut nodes = create_network(3);
5489                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5490                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5491
5492                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5493                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5494
5495                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5496                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5497
5498                 macro_rules! get_route_and_payment_hash {
5499                         ($recv_value: expr) => {{
5500                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5501                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5502                                 (route, payment_hash, payment_preimage)
5503                         }}
5504                 };
5505
5506                 macro_rules! expect_forward {
5507                         ($node: expr) => {{
5508                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5509                                 assert_eq!(events.len(), 1);
5510                                 check_added_monitors!($node, 1);
5511                                 let payment_event = SendEvent::from_event(events.remove(0));
5512                                 payment_event
5513                         }}
5514                 }
5515
5516                 macro_rules! expect_payment_received {
5517                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5518                                 let events = $node.node.get_and_clear_pending_events();
5519                                 assert_eq!(events.len(), 1);
5520                                 match events[0] {
5521                                         Event::PaymentReceived { ref payment_hash, amt } => {
5522                                                 assert_eq!($expected_payment_hash, *payment_hash);
5523                                                 assert_eq!($expected_recv_value, amt);
5524                                         },
5525                                         _ => panic!("Unexpected event"),
5526                                 }
5527                         }
5528                 };
5529
5530                 let feemsat = 239; // somehow we know?
5531                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5532
5533                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5534
5535                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5536                 {
5537                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5538                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5539                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5540                         match err {
5541                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5542                                 _ => panic!("Unknown error variants"),
5543                         }
5544                 }
5545
5546                 let mut htlc_id = 0;
5547                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5548                 // nodes[0]'s wealth
5549                 loop {
5550                         let amt_msat = recv_value_0 + total_fee_msat;
5551                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5552                                 break;
5553                         }
5554                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5555                         htlc_id += 1;
5556
5557                         let (stat01_, stat11_, stat12_, stat22_) = (
5558                                 get_channel_value_stat!(nodes[0], chan_1.2),
5559                                 get_channel_value_stat!(nodes[1], chan_1.2),
5560                                 get_channel_value_stat!(nodes[1], chan_2.2),
5561                                 get_channel_value_stat!(nodes[2], chan_2.2),
5562                         );
5563
5564                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5565                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5566                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5567                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5568                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5569                 }
5570
5571                 {
5572                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5573                         // attempt to get channel_reserve violation
5574                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5575                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5576                         match err {
5577                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5578                                 _ => panic!("Unknown error variants"),
5579                         }
5580                 }
5581
5582                 // adding pending output
5583                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5584                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5585
5586                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5587                 let payment_event_1 = {
5588                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5589                         check_added_monitors!(nodes[0], 1);
5590
5591                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5592                         assert_eq!(events.len(), 1);
5593                         SendEvent::from_event(events.remove(0))
5594                 };
5595                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5596
5597                 // channel reserve test with htlc pending output > 0
5598                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5599                 {
5600                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5601                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5602                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5603                                 _ => panic!("Unknown error variants"),
5604                         }
5605                 }
5606
5607                 {
5608                         // test channel_reserve test on nodes[1] side
5609                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5610
5611                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5612                         let secp_ctx = Secp256k1::new();
5613                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5614                                 let mut session_key = [0; 32];
5615                                 rng::fill_bytes(&mut session_key);
5616                                 session_key
5617                         }).expect("RNG is bad!");
5618
5619                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5620                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5621                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5622                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5623                         let msg = msgs::UpdateAddHTLC {
5624                                 channel_id: chan_1.2,
5625                                 htlc_id,
5626                                 amount_msat: htlc_msat,
5627                                 payment_hash: our_payment_hash,
5628                                 cltv_expiry: htlc_cltv,
5629                                 onion_routing_packet: onion_packet,
5630                         };
5631
5632                         if test_recv {
5633                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5634                                 match err {
5635                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5636                                 }
5637                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5638                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5639                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5640                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5641                                 assert_eq!(channel_close_broadcast.len(), 1);
5642                                 match channel_close_broadcast[0] {
5643                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5644                                                 assert_eq!(msg.contents.flags & 2, 2);
5645                                         },
5646                                         _ => panic!("Unexpected event"),
5647                                 }
5648                                 return;
5649                         }
5650                 }
5651
5652                 // split the rest to test holding cell
5653                 let recv_value_21 = recv_value_2/2;
5654                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5655                 {
5656                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5657                         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);
5658                 }
5659
5660                 // now see if they go through on both sides
5661                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5662                 // but this will stuck in the holding cell
5663                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5664                 check_added_monitors!(nodes[0], 0);
5665                 let events = nodes[0].node.get_and_clear_pending_events();
5666                 assert_eq!(events.len(), 0);
5667
5668                 // test with outbound holding cell amount > 0
5669                 {
5670                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5671                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5672                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5673                                 _ => panic!("Unknown error variants"),
5674                         }
5675                 }
5676
5677                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5678                 // this will also stuck in the holding cell
5679                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5680                 check_added_monitors!(nodes[0], 0);
5681                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5682                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5683
5684                 // flush the pending htlc
5685                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5686                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5687                 check_added_monitors!(nodes[1], 1);
5688
5689                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5690                 check_added_monitors!(nodes[0], 1);
5691                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5692
5693                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5694                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5695                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5696                 check_added_monitors!(nodes[0], 1);
5697
5698                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5699                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5700                 check_added_monitors!(nodes[1], 1);
5701
5702                 expect_pending_htlcs_forwardable!(nodes[1]);
5703
5704                 let ref payment_event_11 = expect_forward!(nodes[1]);
5705                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5706                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5707
5708                 expect_pending_htlcs_forwardable!(nodes[2]);
5709                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5710
5711                 // flush the htlcs in the holding cell
5712                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5713                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5714                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5715                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5716                 expect_pending_htlcs_forwardable!(nodes[1]);
5717
5718                 let ref payment_event_3 = expect_forward!(nodes[1]);
5719                 assert_eq!(payment_event_3.msgs.len(), 2);
5720                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5721                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5722
5723                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5724                 expect_pending_htlcs_forwardable!(nodes[2]);
5725
5726                 let events = nodes[2].node.get_and_clear_pending_events();
5727                 assert_eq!(events.len(), 2);
5728                 match events[0] {
5729                         Event::PaymentReceived { ref payment_hash, amt } => {
5730                                 assert_eq!(our_payment_hash_21, *payment_hash);
5731                                 assert_eq!(recv_value_21, amt);
5732                         },
5733                         _ => panic!("Unexpected event"),
5734                 }
5735                 match events[1] {
5736                         Event::PaymentReceived { ref payment_hash, amt } => {
5737                                 assert_eq!(our_payment_hash_22, *payment_hash);
5738                                 assert_eq!(recv_value_22, amt);
5739                         },
5740                         _ => panic!("Unexpected event"),
5741                 }
5742
5743                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5744                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5745                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5746
5747                 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);
5748                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5749                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5750                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5751
5752                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5753                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5754         }
5755
5756         #[test]
5757         fn channel_reserve_test() {
5758                 do_channel_reserve_test(false);
5759                 do_channel_reserve_test(true);
5760         }
5761
5762         #[test]
5763         fn channel_monitor_network_test() {
5764                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5765                 // tests that ChannelMonitor is able to recover from various states.
5766                 let nodes = create_network(5);
5767
5768                 // Create some initial channels
5769                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5770                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5771                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5772                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5773
5774                 // Rebalance the network a bit by relaying one payment through all the channels...
5775                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5776                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5777                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5778                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5779
5780                 // Simple case with no pending HTLCs:
5781                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5782                 {
5783                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5784                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5785                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5786                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5787                 }
5788                 get_announce_close_broadcast_events(&nodes, 0, 1);
5789                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5790                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5791
5792                 // One pending HTLC is discarded by the force-close:
5793                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5794
5795                 // Simple case of one pending HTLC to HTLC-Timeout
5796                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5797                 {
5798                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5799                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5800                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5801                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5802                 }
5803                 get_announce_close_broadcast_events(&nodes, 1, 2);
5804                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5805                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5806
5807                 macro_rules! claim_funds {
5808                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5809                                 {
5810                                         assert!($node.node.claim_funds($preimage));
5811                                         check_added_monitors!($node, 1);
5812
5813                                         let events = $node.node.get_and_clear_pending_msg_events();
5814                                         assert_eq!(events.len(), 1);
5815                                         match events[0] {
5816                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5817                                                         assert!(update_add_htlcs.is_empty());
5818                                                         assert!(update_fail_htlcs.is_empty());
5819                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5820                                                 },
5821                                                 _ => panic!("Unexpected event"),
5822                                         };
5823                                 }
5824                         }
5825                 }
5826
5827                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5828                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5829                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5830                 {
5831                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5832
5833                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5834                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5835
5836                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5837                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5838
5839                         check_preimage_claim(&nodes[3], &node_txn);
5840                 }
5841                 get_announce_close_broadcast_events(&nodes, 2, 3);
5842                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5843                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5844
5845                 { // Cheat and reset nodes[4]'s height to 1
5846                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5847                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5848                 }
5849
5850                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5851                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5852                 // One pending HTLC to time out:
5853                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5854                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5855                 // buffer space).
5856
5857                 {
5858                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5859                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5860                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5861                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5862                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5863                         }
5864
5865                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5866
5867                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5868                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5869
5870                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5871                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5872                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5873                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5874                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5875                         }
5876
5877                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5878
5879                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5880                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5881
5882                         check_preimage_claim(&nodes[4], &node_txn);
5883                 }
5884                 get_announce_close_broadcast_events(&nodes, 3, 4);
5885                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5886                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5887         }
5888
5889         #[test]
5890         fn test_justice_tx() {
5891                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5892
5893                 let nodes = create_network(2);
5894                 // Create some new channels:
5895                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5896
5897                 // A pending HTLC which will be revoked:
5898                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5899                 // Get the will-be-revoked local txn from nodes[0]
5900                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5901                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5902                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5903                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5904                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5905                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5906                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5907                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5908                 // Revoke the old state
5909                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5910
5911                 {
5912                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5913                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5914                         {
5915                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5916                                 assert_eq!(node_txn.len(), 3);
5917                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5918                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5919
5920                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5921                                 node_txn.swap_remove(0);
5922                         }
5923                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5924
5925                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5926                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5927                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5928                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5929                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5930                 }
5931                 get_announce_close_broadcast_events(&nodes, 0, 1);
5932
5933                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5934                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5935
5936                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5937                 // Create some new channels:
5938                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5939
5940                 // A pending HTLC which will be revoked:
5941                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5942                 // Get the will-be-revoked local txn from B
5943                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5944                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5945                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5946                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5947                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5948                 // Revoke the old state
5949                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5950                 {
5951                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5952                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5953                         {
5954                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5955                                 assert_eq!(node_txn.len(), 3);
5956                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5957                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5958
5959                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5960                                 node_txn.swap_remove(0);
5961                         }
5962                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5963
5964                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5965                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5966                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5967                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5968                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5969                 }
5970                 get_announce_close_broadcast_events(&nodes, 0, 1);
5971                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5972                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5973         }
5974
5975         #[test]
5976         fn revoked_output_claim() {
5977                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5978                 // transaction is broadcast by its counterparty
5979                 let nodes = create_network(2);
5980                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5981                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5982                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5983                 assert_eq!(revoked_local_txn.len(), 1);
5984                 // Only output is the full channel value back to nodes[0]:
5985                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5986                 // Send a payment through, updating everyone's latest commitment txn
5987                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5988
5989                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5990                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5991                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5992                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5993                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
5994
5995                 assert_eq!(node_txn[0], node_txn[2]);
5996
5997                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5998                 check_spends!(node_txn[1], chan_1.3.clone());
5999
6000                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6001                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6002                 get_announce_close_broadcast_events(&nodes, 0, 1);
6003         }
6004
6005         #[test]
6006         fn claim_htlc_outputs_shared_tx() {
6007                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6008                 let nodes = create_network(2);
6009
6010                 // Create some new channel:
6011                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6012
6013                 // Rebalance the network to generate htlc in the two directions
6014                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6015                 // 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
6016                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6017                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6018
6019                 // Get the will-be-revoked local txn from node[0]
6020                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6021                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6022                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6023                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6024                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6025                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6026                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6027                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6028
6029                 //Revoke the old state
6030                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6031
6032                 {
6033                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6034                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6035                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6036
6037                         let events = nodes[1].node.get_and_clear_pending_events();
6038                         assert_eq!(events.len(), 1);
6039                         match events[0] {
6040                                 Event::PaymentFailed { payment_hash, .. } => {
6041                                         assert_eq!(payment_hash, payment_hash_2);
6042                                 },
6043                                 _ => panic!("Unexpected event"),
6044                         }
6045
6046                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6047                         assert_eq!(node_txn.len(), 4);
6048
6049                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6050                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6051
6052                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6053
6054                         let mut witness_lens = BTreeSet::new();
6055                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6056                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6057                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6058                         assert_eq!(witness_lens.len(), 3);
6059                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6060                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6061                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6062
6063                         // Next nodes[1] broadcasts its current local tx state:
6064                         assert_eq!(node_txn[1].input.len(), 1);
6065                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6066
6067                         assert_eq!(node_txn[2].input.len(), 1);
6068                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6069                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6070                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6071                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6072                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6073                 }
6074                 get_announce_close_broadcast_events(&nodes, 0, 1);
6075                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6076                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6077         }
6078
6079         #[test]
6080         fn claim_htlc_outputs_single_tx() {
6081                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6082                 let nodes = create_network(2);
6083
6084                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6085
6086                 // Rebalance the network to generate htlc in the two directions
6087                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6088                 // 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
6089                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6090                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6091                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6092
6093                 // Get the will-be-revoked local txn from node[0]
6094                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6095
6096                 //Revoke the old state
6097                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6098
6099                 {
6100                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6101                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6102                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6103
6104                         let events = nodes[1].node.get_and_clear_pending_events();
6105                         assert_eq!(events.len(), 1);
6106                         match events[0] {
6107                                 Event::PaymentFailed { payment_hash, .. } => {
6108                                         assert_eq!(payment_hash, payment_hash_2);
6109                                 },
6110                                 _ => panic!("Unexpected event"),
6111                         }
6112
6113                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6114                         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)
6115
6116                         assert_eq!(node_txn[0], node_txn[7]);
6117                         assert_eq!(node_txn[1], node_txn[8]);
6118                         assert_eq!(node_txn[2], node_txn[9]);
6119                         assert_eq!(node_txn[3], node_txn[10]);
6120                         assert_eq!(node_txn[4], node_txn[11]);
6121                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6122                         assert_eq!(node_txn[4], node_txn[6]);
6123
6124                         assert_eq!(node_txn[0].input.len(), 1);
6125                         assert_eq!(node_txn[1].input.len(), 1);
6126                         assert_eq!(node_txn[2].input.len(), 1);
6127
6128                         let mut revoked_tx_map = HashMap::new();
6129                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6130                         node_txn[0].verify(&revoked_tx_map).unwrap();
6131                         node_txn[1].verify(&revoked_tx_map).unwrap();
6132                         node_txn[2].verify(&revoked_tx_map).unwrap();
6133
6134                         let mut witness_lens = BTreeSet::new();
6135                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6136                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6137                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6138                         assert_eq!(witness_lens.len(), 3);
6139                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6140                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6141                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6142
6143                         assert_eq!(node_txn[3].input.len(), 1);
6144                         check_spends!(node_txn[3], chan_1.3.clone());
6145
6146                         assert_eq!(node_txn[4].input.len(), 1);
6147                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6148                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6149                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6150                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6151                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6152                 }
6153                 get_announce_close_broadcast_events(&nodes, 0, 1);
6154                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6155                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6156         }
6157
6158         #[test]
6159         fn test_htlc_on_chain_success() {
6160                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6161                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6162                 // broadcasting the right event to other nodes in payment path.
6163                 // A --------------------> B ----------------------> C (preimage)
6164                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6165                 // commitment transaction was broadcast.
6166                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6167                 // towards B.
6168                 // B should be able to claim via preimage if A then broadcasts its local tx.
6169                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6170                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6171                 // PaymentSent event).
6172
6173                 let nodes = create_network(3);
6174
6175                 // Create some initial channels
6176                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6177                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6178
6179                 // Rebalance the network a bit by relaying one payment through all the channels...
6180                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6181                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6182
6183                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6184                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6185
6186                 // Broadcast legit commitment tx from C on B's chain
6187                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6188                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6189                 assert_eq!(commitment_tx.len(), 1);
6190                 check_spends!(commitment_tx[0], chan_2.3.clone());
6191                 nodes[2].node.claim_funds(our_payment_preimage);
6192                 check_added_monitors!(nodes[2], 1);
6193                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6194                 assert!(updates.update_add_htlcs.is_empty());
6195                 assert!(updates.update_fail_htlcs.is_empty());
6196                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6197                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6198
6199                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6200                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6201                 assert_eq!(events.len(), 1);
6202                 match events[0] {
6203                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6204                         _ => panic!("Unexpected event"),
6205                 }
6206                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6207                 assert_eq!(node_txn.len(), 3);
6208                 assert_eq!(node_txn[1], commitment_tx[0]);
6209                 assert_eq!(node_txn[0], node_txn[2]);
6210                 check_spends!(node_txn[0], commitment_tx[0].clone());
6211                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6212                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6213                 assert_eq!(node_txn[0].lock_time, 0);
6214
6215                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6216                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6217                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6218                 {
6219                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6220                         assert_eq!(added_monitors.len(), 1);
6221                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6222                         added_monitors.clear();
6223                 }
6224                 assert_eq!(events.len(), 2);
6225                 match events[0] {
6226                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6227                         _ => panic!("Unexpected event"),
6228                 }
6229                 match events[1] {
6230                         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, .. } } => {
6231                                 assert!(update_add_htlcs.is_empty());
6232                                 assert!(update_fail_htlcs.is_empty());
6233                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6234                                 assert!(update_fail_malformed_htlcs.is_empty());
6235                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6236                         },
6237                         _ => panic!("Unexpected event"),
6238                 };
6239                 {
6240                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6241                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6242                         // timeout-claim of the output that nodes[2] just claimed via success.
6243                         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)
6244                         assert_eq!(node_txn.len(), 4);
6245                         assert_eq!(node_txn[0], node_txn[3]);
6246                         check_spends!(node_txn[0], commitment_tx[0].clone());
6247                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6248                         assert_ne!(node_txn[0].lock_time, 0);
6249                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6250                         check_spends!(node_txn[1], chan_2.3.clone());
6251                         check_spends!(node_txn[2], node_txn[1].clone());
6252                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6253                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6254                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6255                         assert_ne!(node_txn[2].lock_time, 0);
6256                         node_txn.clear();
6257                 }
6258
6259                 // Broadcast legit commitment tx from A on B's chain
6260                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6261                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6262                 check_spends!(commitment_tx[0], chan_1.3.clone());
6263                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6264                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6265                 assert_eq!(events.len(), 1);
6266                 match events[0] {
6267                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6268                         _ => panic!("Unexpected event"),
6269                 }
6270                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6271                 assert_eq!(node_txn.len(), 3);
6272                 assert_eq!(node_txn[0], node_txn[2]);
6273                 check_spends!(node_txn[0], commitment_tx[0].clone());
6274                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6275                 assert_eq!(node_txn[0].lock_time, 0);
6276                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6277                 check_spends!(node_txn[1], chan_1.3.clone());
6278                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6279                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6280                 // we already checked the same situation with A.
6281
6282                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6283                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6284                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6285                 assert_eq!(events.len(), 1);
6286                 match events[0] {
6287                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6288                         _ => panic!("Unexpected event"),
6289                 }
6290                 let events = nodes[0].node.get_and_clear_pending_events();
6291                 assert_eq!(events.len(), 1);
6292                 match events[0] {
6293                         Event::PaymentSent { payment_preimage } => {
6294                                 assert_eq!(payment_preimage, our_payment_preimage);
6295                         },
6296                         _ => panic!("Unexpected event"),
6297                 }
6298                 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)
6299                 assert_eq!(node_txn.len(), 4);
6300                 assert_eq!(node_txn[0], node_txn[3]);
6301                 check_spends!(node_txn[0], commitment_tx[0].clone());
6302                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6303                 assert_ne!(node_txn[0].lock_time, 0);
6304                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6305                 check_spends!(node_txn[1], chan_1.3.clone());
6306                 check_spends!(node_txn[2], node_txn[1].clone());
6307                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6308                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6309                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6310                 assert_ne!(node_txn[2].lock_time, 0);
6311         }
6312
6313         #[test]
6314         fn test_htlc_on_chain_timeout() {
6315                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6316                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6317                 // broadcasting the right event to other nodes in payment path.
6318                 // A ------------------> B ----------------------> C (timeout)
6319                 //    B's commitment tx                 C's commitment tx
6320                 //            \                                  \
6321                 //         B's HTLC timeout tx               B's timeout tx
6322
6323                 let nodes = create_network(3);
6324
6325                 // Create some intial channels
6326                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6327                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6328
6329                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6330                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6331                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6332
6333                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6334                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6335
6336                 // Brodacast legit commitment tx from C on B's chain
6337                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6338                 check_spends!(commitment_tx[0], chan_2.3.clone());
6339                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6340                 {
6341                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6342                         assert_eq!(added_monitors.len(), 1);
6343                         added_monitors.clear();
6344                 }
6345                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6346                 assert_eq!(events.len(), 1);
6347                 match events[0] {
6348                         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, .. } } => {
6349                                 assert!(update_add_htlcs.is_empty());
6350                                 assert!(!update_fail_htlcs.is_empty());
6351                                 assert!(update_fulfill_htlcs.is_empty());
6352                                 assert!(update_fail_malformed_htlcs.is_empty());
6353                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6354                         },
6355                         _ => panic!("Unexpected event"),
6356                 };
6357                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6358                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6359                 assert_eq!(events.len(), 1);
6360                 match events[0] {
6361                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6362                         _ => panic!("Unexpected event"),
6363                 }
6364                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6365                 assert_eq!(node_txn.len(), 1);
6366                 check_spends!(node_txn[0], chan_2.3.clone());
6367                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6368
6369                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6370                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6371                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6372                 let timeout_tx;
6373                 {
6374                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6375                         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)
6376                         assert_eq!(node_txn[0], node_txn[5]);
6377                         assert_eq!(node_txn[1], node_txn[6]);
6378                         assert_eq!(node_txn[2], node_txn[7]);
6379                         check_spends!(node_txn[0], commitment_tx[0].clone());
6380                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6381                         check_spends!(node_txn[1], chan_2.3.clone());
6382                         check_spends!(node_txn[2], node_txn[1].clone());
6383                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6384                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6385                         check_spends!(node_txn[3], chan_2.3.clone());
6386                         check_spends!(node_txn[4], node_txn[3].clone());
6387                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6388                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6389                         timeout_tx = node_txn[0].clone();
6390                         node_txn.clear();
6391                 }
6392
6393                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6394                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6395                 check_added_monitors!(nodes[1], 1);
6396                 assert_eq!(events.len(), 2);
6397                 match events[0] {
6398                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6399                         _ => panic!("Unexpected event"),
6400                 }
6401                 match events[1] {
6402                         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, .. } } => {
6403                                 assert!(update_add_htlcs.is_empty());
6404                                 assert!(!update_fail_htlcs.is_empty());
6405                                 assert!(update_fulfill_htlcs.is_empty());
6406                                 assert!(update_fail_malformed_htlcs.is_empty());
6407                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6408                         },
6409                         _ => panic!("Unexpected event"),
6410                 };
6411                 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
6412                 assert_eq!(node_txn.len(), 0);
6413
6414                 // Broadcast legit commitment tx from B on A's chain
6415                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6416                 check_spends!(commitment_tx[0], chan_1.3.clone());
6417
6418                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6419                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6420                 assert_eq!(events.len(), 1);
6421                 match events[0] {
6422                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6423                         _ => panic!("Unexpected event"),
6424                 }
6425                 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
6426                 assert_eq!(node_txn.len(), 4);
6427                 assert_eq!(node_txn[0], node_txn[3]);
6428                 check_spends!(node_txn[0], commitment_tx[0].clone());
6429                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6430                 check_spends!(node_txn[1], chan_1.3.clone());
6431                 check_spends!(node_txn[2], node_txn[1].clone());
6432                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6433                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6434         }
6435
6436         #[test]
6437         fn test_simple_commitment_revoked_fail_backward() {
6438                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6439                 // and fail backward accordingly.
6440
6441                 let nodes = create_network(3);
6442
6443                 // Create some initial channels
6444                 create_announced_chan_between_nodes(&nodes, 0, 1);
6445                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6446
6447                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6448                 // Get the will-be-revoked local txn from nodes[2]
6449                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6450                 // Revoke the old state
6451                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6452
6453                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6454
6455                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6456                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6457                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6458                 check_added_monitors!(nodes[1], 1);
6459                 assert_eq!(events.len(), 2);
6460                 match events[0] {
6461                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6462                         _ => panic!("Unexpected event"),
6463                 }
6464                 match events[1] {
6465                         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, .. } } => {
6466                                 assert!(update_add_htlcs.is_empty());
6467                                 assert_eq!(update_fail_htlcs.len(), 1);
6468                                 assert!(update_fulfill_htlcs.is_empty());
6469                                 assert!(update_fail_malformed_htlcs.is_empty());
6470                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6471
6472                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6473                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6474
6475                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6476                                 assert_eq!(events.len(), 1);
6477                                 match events[0] {
6478                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6479                                         _ => panic!("Unexpected event"),
6480                                 }
6481                                 let events = nodes[0].node.get_and_clear_pending_events();
6482                                 assert_eq!(events.len(), 1);
6483                                 match events[0] {
6484                                         Event::PaymentFailed { .. } => {},
6485                                         _ => panic!("Unexpected event"),
6486                                 }
6487                         },
6488                         _ => panic!("Unexpected event"),
6489                 }
6490         }
6491
6492         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6493                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6494                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6495                 // commitment transaction anymore.
6496                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6497                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6498                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6499                 // technically disallowed and we should probably handle it reasonably.
6500                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6501                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6502                 // transactions:
6503                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6504                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6505                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6506                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6507                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6508                 let mut nodes = create_network(3);
6509
6510                 // Create some initial channels
6511                 create_announced_chan_between_nodes(&nodes, 0, 1);
6512                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6513
6514                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6515                 // Get the will-be-revoked local txn from nodes[2]
6516                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6517                 // Revoke the old state
6518                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6519
6520                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6521                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6522                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6523
6524                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6525                 check_added_monitors!(nodes[2], 1);
6526                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6527                 assert!(updates.update_add_htlcs.is_empty());
6528                 assert!(updates.update_fulfill_htlcs.is_empty());
6529                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6530                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6531                 assert!(updates.update_fee.is_none());
6532                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6533                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6534                 // Drop the last RAA from 3 -> 2
6535
6536                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6537                 check_added_monitors!(nodes[2], 1);
6538                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6539                 assert!(updates.update_add_htlcs.is_empty());
6540                 assert!(updates.update_fulfill_htlcs.is_empty());
6541                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6542                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6543                 assert!(updates.update_fee.is_none());
6544                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6545                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6546                 check_added_monitors!(nodes[1], 1);
6547                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6548                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6549                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6550                 check_added_monitors!(nodes[2], 1);
6551
6552                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6553                 check_added_monitors!(nodes[2], 1);
6554                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6555                 assert!(updates.update_add_htlcs.is_empty());
6556                 assert!(updates.update_fulfill_htlcs.is_empty());
6557                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6558                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6559                 assert!(updates.update_fee.is_none());
6560                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6561                 // At this point first_payment_hash has dropped out of the latest two commitment
6562                 // transactions that nodes[1] is tracking...
6563                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6564                 check_added_monitors!(nodes[1], 1);
6565                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6566                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6567                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6568                 check_added_monitors!(nodes[2], 1);
6569
6570                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6571                 // on nodes[2]'s RAA.
6572                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6573                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6574                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6575                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6576                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6577                 check_added_monitors!(nodes[1], 0);
6578
6579                 if deliver_bs_raa {
6580                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6581                         // One monitor for the new revocation preimage, one as we generate a commitment for
6582                         // nodes[0] to fail first_payment_hash backwards.
6583                         check_added_monitors!(nodes[1], 2);
6584                 }
6585
6586                 let mut failed_htlcs = HashSet::new();
6587                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6588
6589                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6590                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6591
6592                 let events = nodes[1].node.get_and_clear_pending_events();
6593                 assert_eq!(events.len(), 1);
6594                 match events[0] {
6595                         Event::PaymentFailed { ref payment_hash, .. } => {
6596                                 assert_eq!(*payment_hash, fourth_payment_hash);
6597                         },
6598                         _ => panic!("Unexpected event"),
6599                 }
6600
6601                 if !deliver_bs_raa {
6602                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6603                         check_added_monitors!(nodes[1], 1);
6604                 }
6605
6606                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6607                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6608                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6609                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6610                         _ => panic!("Unexpected event"),
6611                 }
6612                 if deliver_bs_raa {
6613                         match events[0] {
6614                                 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, .. } } => {
6615                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6616                                         assert_eq!(update_add_htlcs.len(), 1);
6617                                         assert!(update_fulfill_htlcs.is_empty());
6618                                         assert!(update_fail_htlcs.is_empty());
6619                                         assert!(update_fail_malformed_htlcs.is_empty());
6620                                 },
6621                                 _ => panic!("Unexpected event"),
6622                         }
6623                 }
6624                 // Due to the way backwards-failing occurs we do the updates in two steps.
6625                 let updates = match events[1] {
6626                         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, .. } } => {
6627                                 assert!(update_add_htlcs.is_empty());
6628                                 assert_eq!(update_fail_htlcs.len(), 1);
6629                                 assert!(update_fulfill_htlcs.is_empty());
6630                                 assert!(update_fail_malformed_htlcs.is_empty());
6631                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6632
6633                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6634                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6635                                 check_added_monitors!(nodes[0], 1);
6636                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6637                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6638                                 check_added_monitors!(nodes[1], 1);
6639                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6640                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6641                                 check_added_monitors!(nodes[1], 1);
6642                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6643                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6644                                 check_added_monitors!(nodes[0], 1);
6645
6646                                 if !deliver_bs_raa {
6647                                         // If we delievered B's RAA we got an unknown preimage error, not something
6648                                         // that we should update our routing table for.
6649                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6650                                         assert_eq!(events.len(), 1);
6651                                         match events[0] {
6652                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6653                                                 _ => panic!("Unexpected event"),
6654                                         }
6655                                 }
6656                                 let events = nodes[0].node.get_and_clear_pending_events();
6657                                 assert_eq!(events.len(), 1);
6658                                 match events[0] {
6659                                         Event::PaymentFailed { ref payment_hash, .. } => {
6660                                                 assert!(failed_htlcs.insert(payment_hash.0));
6661                                         },
6662                                         _ => panic!("Unexpected event"),
6663                                 }
6664
6665                                 bs_second_update
6666                         },
6667                         _ => panic!("Unexpected event"),
6668                 };
6669
6670                 assert!(updates.update_add_htlcs.is_empty());
6671                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6672                 assert!(updates.update_fulfill_htlcs.is_empty());
6673                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6674                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6675                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6676                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6677
6678                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6679                 assert_eq!(events.len(), 2);
6680                 for event in events {
6681                         match event {
6682                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6683                                 _ => panic!("Unexpected event"),
6684                         }
6685                 }
6686
6687                 let events = nodes[0].node.get_and_clear_pending_events();
6688                 assert_eq!(events.len(), 2);
6689                 match events[0] {
6690                         Event::PaymentFailed { ref payment_hash, .. } => {
6691                                 assert!(failed_htlcs.insert(payment_hash.0));
6692                         },
6693                         _ => panic!("Unexpected event"),
6694                 }
6695                 match events[1] {
6696                         Event::PaymentFailed { ref payment_hash, .. } => {
6697                                 assert!(failed_htlcs.insert(payment_hash.0));
6698                         },
6699                         _ => panic!("Unexpected event"),
6700                 }
6701
6702                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6703                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6704                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6705         }
6706
6707         #[test]
6708         fn test_commitment_revoked_fail_backward_exhaustive() {
6709                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6710                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6711         }
6712
6713         #[test]
6714         fn test_htlc_ignore_latest_remote_commitment() {
6715                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6716                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6717                 let nodes = create_network(2);
6718                 create_announced_chan_between_nodes(&nodes, 0, 1);
6719
6720                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6721                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6722                 {
6723                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6724                         assert_eq!(events.len(), 1);
6725                         match events[0] {
6726                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6727                                         assert_eq!(flags & 0b10, 0b10);
6728                                 },
6729                                 _ => panic!("Unexpected event"),
6730                         }
6731                 }
6732
6733                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6734                 assert_eq!(node_txn.len(), 2);
6735
6736                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6737                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6738
6739                 {
6740                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6741                         assert_eq!(events.len(), 1);
6742                         match events[0] {
6743                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6744                                         assert_eq!(flags & 0b10, 0b10);
6745                                 },
6746                                 _ => panic!("Unexpected event"),
6747                         }
6748                 }
6749
6750                 // Duplicate the block_connected call since this may happen due to other listeners
6751                 // registering new transactions
6752                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6753         }
6754
6755         #[test]
6756         fn test_force_close_fail_back() {
6757                 // Check which HTLCs are failed-backwards on channel force-closure
6758                 let mut nodes = create_network(3);
6759                 create_announced_chan_between_nodes(&nodes, 0, 1);
6760                 create_announced_chan_between_nodes(&nodes, 1, 2);
6761
6762                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6763
6764                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6765
6766                 let mut payment_event = {
6767                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6768                         check_added_monitors!(nodes[0], 1);
6769
6770                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6771                         assert_eq!(events.len(), 1);
6772                         SendEvent::from_event(events.remove(0))
6773                 };
6774
6775                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6776                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6777
6778                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6779                 assert_eq!(events_1.len(), 1);
6780                 match events_1[0] {
6781                         Event::PendingHTLCsForwardable { .. } => { },
6782                         _ => panic!("Unexpected event"),
6783                 };
6784
6785                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6786                 nodes[1].node.process_pending_htlc_forwards();
6787
6788                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6789                 assert_eq!(events_2.len(), 1);
6790                 payment_event = SendEvent::from_event(events_2.remove(0));
6791                 assert_eq!(payment_event.msgs.len(), 1);
6792
6793                 check_added_monitors!(nodes[1], 1);
6794                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6795                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6796                 check_added_monitors!(nodes[2], 1);
6797                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6798
6799                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6800                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6801                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6802
6803                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6804                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6805                 assert_eq!(events_3.len(), 1);
6806                 match events_3[0] {
6807                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6808                                 assert_eq!(flags & 0b10, 0b10);
6809                         },
6810                         _ => panic!("Unexpected event"),
6811                 }
6812
6813                 let tx = {
6814                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6815                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6816                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6817                         // back to nodes[1] upon timeout otherwise.
6818                         assert_eq!(node_txn.len(), 1);
6819                         node_txn.remove(0)
6820                 };
6821
6822                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6823                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6824
6825                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6826                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6827                 assert_eq!(events_4.len(), 1);
6828                 match events_4[0] {
6829                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6830                                 assert_eq!(flags & 0b10, 0b10);
6831                         },
6832                         _ => panic!("Unexpected event"),
6833                 }
6834
6835                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6836                 {
6837                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6838                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6839                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6840                 }
6841                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6842                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6843                 assert_eq!(node_txn.len(), 1);
6844                 assert_eq!(node_txn[0].input.len(), 1);
6845                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6846                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6847                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6848
6849                 check_spends!(node_txn[0], tx);
6850         }
6851
6852         #[test]
6853         fn test_unconf_chan() {
6854                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6855                 let nodes = create_network(2);
6856                 create_announced_chan_between_nodes(&nodes, 0, 1);
6857
6858                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6859                 assert_eq!(channel_state.by_id.len(), 1);
6860                 assert_eq!(channel_state.short_to_id.len(), 1);
6861                 mem::drop(channel_state);
6862
6863                 let mut headers = Vec::new();
6864                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6865                 headers.push(header.clone());
6866                 for _i in 2..100 {
6867                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6868                         headers.push(header.clone());
6869                 }
6870                 while !headers.is_empty() {
6871                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6872                 }
6873                 {
6874                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6875                         assert_eq!(events.len(), 1);
6876                         match events[0] {
6877                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6878                                         assert_eq!(flags & 0b10, 0b10);
6879                                 },
6880                                 _ => panic!("Unexpected event"),
6881                         }
6882                 }
6883                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6884                 assert_eq!(channel_state.by_id.len(), 0);
6885                 assert_eq!(channel_state.short_to_id.len(), 0);
6886         }
6887
6888         macro_rules! get_chan_reestablish_msgs {
6889                 ($src_node: expr, $dst_node: expr) => {
6890                         {
6891                                 let mut res = Vec::with_capacity(1);
6892                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6893                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6894                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6895                                                 res.push(msg.clone());
6896                                         } else {
6897                                                 panic!("Unexpected event")
6898                                         }
6899                                 }
6900                                 res
6901                         }
6902                 }
6903         }
6904
6905         macro_rules! handle_chan_reestablish_msgs {
6906                 ($src_node: expr, $dst_node: expr) => {
6907                         {
6908                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6909                                 let mut idx = 0;
6910                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6911                                         idx += 1;
6912                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6913                                         Some(msg.clone())
6914                                 } else {
6915                                         None
6916                                 };
6917
6918                                 let mut revoke_and_ack = None;
6919                                 let mut commitment_update = None;
6920                                 let order = if let Some(ev) = msg_events.get(idx) {
6921                                         idx += 1;
6922                                         match ev {
6923                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6924                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6925                                                         revoke_and_ack = Some(msg.clone());
6926                                                         RAACommitmentOrder::RevokeAndACKFirst
6927                                                 },
6928                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6929                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6930                                                         commitment_update = Some(updates.clone());
6931                                                         RAACommitmentOrder::CommitmentFirst
6932                                                 },
6933                                                 _ => panic!("Unexpected event"),
6934                                         }
6935                                 } else {
6936                                         RAACommitmentOrder::CommitmentFirst
6937                                 };
6938
6939                                 if let Some(ev) = msg_events.get(idx) {
6940                                         match ev {
6941                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6942                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6943                                                         assert!(revoke_and_ack.is_none());
6944                                                         revoke_and_ack = Some(msg.clone());
6945                                                 },
6946                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6947                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6948                                                         assert!(commitment_update.is_none());
6949                                                         commitment_update = Some(updates.clone());
6950                                                 },
6951                                                 _ => panic!("Unexpected event"),
6952                                         }
6953                                 }
6954
6955                                 (funding_locked, revoke_and_ack, commitment_update, order)
6956                         }
6957                 }
6958         }
6959
6960         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6961         /// for claims/fails they are separated out.
6962         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)) {
6963                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6964                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6965                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6966                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6967
6968                 if send_funding_locked.0 {
6969                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6970                         // from b
6971                         for reestablish in reestablish_1.iter() {
6972                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6973                         }
6974                 }
6975                 if send_funding_locked.1 {
6976                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6977                         // from a
6978                         for reestablish in reestablish_2.iter() {
6979                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6980                         }
6981                 }
6982                 if send_funding_locked.0 || send_funding_locked.1 {
6983                         // If we expect any funding_locked's, both sides better have set
6984                         // next_local_commitment_number to 1
6985                         for reestablish in reestablish_1.iter() {
6986                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6987                         }
6988                         for reestablish in reestablish_2.iter() {
6989                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6990                         }
6991                 }
6992
6993                 let mut resp_1 = Vec::new();
6994                 for msg in reestablish_1 {
6995                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
6996                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
6997                 }
6998                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
6999                         check_added_monitors!(node_b, 1);
7000                 } else {
7001                         check_added_monitors!(node_b, 0);
7002                 }
7003
7004                 let mut resp_2 = Vec::new();
7005                 for msg in reestablish_2 {
7006                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7007                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7008                 }
7009                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7010                         check_added_monitors!(node_a, 1);
7011                 } else {
7012                         check_added_monitors!(node_a, 0);
7013                 }
7014
7015                 // We dont yet support both needing updates, as that would require a different commitment dance:
7016                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7017                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7018
7019                 for chan_msgs in resp_1.drain(..) {
7020                         if send_funding_locked.0 {
7021                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7022                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7023                                 if !announcement_event.is_empty() {
7024                                         assert_eq!(announcement_event.len(), 1);
7025                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7026                                                 //TODO: Test announcement_sigs re-sending
7027                                         } else { panic!("Unexpected event!"); }
7028                                 }
7029                         } else {
7030                                 assert!(chan_msgs.0.is_none());
7031                         }
7032                         if pending_raa.0 {
7033                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7034                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7035                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7036                                 check_added_monitors!(node_a, 1);
7037                         } else {
7038                                 assert!(chan_msgs.1.is_none());
7039                         }
7040                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7041                                 let commitment_update = chan_msgs.2.unwrap();
7042                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7043                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7044                                 } else {
7045                                         assert!(commitment_update.update_add_htlcs.is_empty());
7046                                 }
7047                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7048                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7049                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7050                                 for update_add in commitment_update.update_add_htlcs {
7051                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7052                                 }
7053                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7054                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7055                                 }
7056                                 for update_fail in commitment_update.update_fail_htlcs {
7057                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7058                                 }
7059
7060                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7061                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7062                                 } else {
7063                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7064                                         check_added_monitors!(node_a, 1);
7065                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7066                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7067                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7068                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7069                                         check_added_monitors!(node_b, 1);
7070                                 }
7071                         } else {
7072                                 assert!(chan_msgs.2.is_none());
7073                         }
7074                 }
7075
7076                 for chan_msgs in resp_2.drain(..) {
7077                         if send_funding_locked.1 {
7078                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7079                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7080                                 if !announcement_event.is_empty() {
7081                                         assert_eq!(announcement_event.len(), 1);
7082                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7083                                                 //TODO: Test announcement_sigs re-sending
7084                                         } else { panic!("Unexpected event!"); }
7085                                 }
7086                         } else {
7087                                 assert!(chan_msgs.0.is_none());
7088                         }
7089                         if pending_raa.1 {
7090                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7091                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7092                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7093                                 check_added_monitors!(node_b, 1);
7094                         } else {
7095                                 assert!(chan_msgs.1.is_none());
7096                         }
7097                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7098                                 let commitment_update = chan_msgs.2.unwrap();
7099                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7100                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7101                                 }
7102                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7103                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7104                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7105                                 for update_add in commitment_update.update_add_htlcs {
7106                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7107                                 }
7108                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7109                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7110                                 }
7111                                 for update_fail in commitment_update.update_fail_htlcs {
7112                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7113                                 }
7114
7115                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7116                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7117                                 } else {
7118                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7119                                         check_added_monitors!(node_b, 1);
7120                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7121                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7122                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7123                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7124                                         check_added_monitors!(node_a, 1);
7125                                 }
7126                         } else {
7127                                 assert!(chan_msgs.2.is_none());
7128                         }
7129                 }
7130         }
7131
7132         #[test]
7133         fn test_simple_peer_disconnect() {
7134                 // Test that we can reconnect when there are no lost messages
7135                 let nodes = create_network(3);
7136                 create_announced_chan_between_nodes(&nodes, 0, 1);
7137                 create_announced_chan_between_nodes(&nodes, 1, 2);
7138
7139                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7140                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7141                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7142
7143                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7144                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7145                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7146                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7147
7148                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7149                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7150                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7151
7152                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7153                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7154                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7155                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7156
7157                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7158                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7159
7160                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7161                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7162
7163                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7164                 {
7165                         let events = nodes[0].node.get_and_clear_pending_events();
7166                         assert_eq!(events.len(), 2);
7167                         match events[0] {
7168                                 Event::PaymentSent { payment_preimage } => {
7169                                         assert_eq!(payment_preimage, payment_preimage_3);
7170                                 },
7171                                 _ => panic!("Unexpected event"),
7172                         }
7173                         match events[1] {
7174                                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
7175                                         assert_eq!(payment_hash, payment_hash_5);
7176                                         assert!(rejected_by_dest);
7177                                 },
7178                                 _ => panic!("Unexpected event"),
7179                         }
7180                 }
7181
7182                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7183                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7184         }
7185
7186         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7187                 // Test that we can reconnect when in-flight HTLC updates get dropped
7188                 let mut nodes = create_network(2);
7189                 if messages_delivered == 0 {
7190                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7191                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7192                 } else {
7193                         create_announced_chan_between_nodes(&nodes, 0, 1);
7194                 }
7195
7196                 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();
7197                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7198
7199                 let payment_event = {
7200                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7201                         check_added_monitors!(nodes[0], 1);
7202
7203                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7204                         assert_eq!(events.len(), 1);
7205                         SendEvent::from_event(events.remove(0))
7206                 };
7207                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7208
7209                 if messages_delivered < 2 {
7210                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7211                 } else {
7212                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7213                         if messages_delivered >= 3 {
7214                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7215                                 check_added_monitors!(nodes[1], 1);
7216                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7217
7218                                 if messages_delivered >= 4 {
7219                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7220                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7221                                         check_added_monitors!(nodes[0], 1);
7222
7223                                         if messages_delivered >= 5 {
7224                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7225                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7226                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7227                                                 check_added_monitors!(nodes[0], 1);
7228
7229                                                 if messages_delivered >= 6 {
7230                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7231                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7232                                                         check_added_monitors!(nodes[1], 1);
7233                                                 }
7234                                         }
7235                                 }
7236                         }
7237                 }
7238
7239                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7240                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7241                 if messages_delivered < 3 {
7242                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7243                         // received on either side, both sides will need to resend them.
7244                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7245                 } else if messages_delivered == 3 {
7246                         // nodes[0] still wants its RAA + commitment_signed
7247                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7248                 } else if messages_delivered == 4 {
7249                         // nodes[0] still wants its commitment_signed
7250                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7251                 } else if messages_delivered == 5 {
7252                         // nodes[1] still wants its final RAA
7253                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7254                 } else if messages_delivered == 6 {
7255                         // Everything was delivered...
7256                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7257                 }
7258
7259                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7260                 assert_eq!(events_1.len(), 1);
7261                 match events_1[0] {
7262                         Event::PendingHTLCsForwardable { .. } => { },
7263                         _ => panic!("Unexpected event"),
7264                 };
7265
7266                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7267                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7268                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7269
7270                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7271                 nodes[1].node.process_pending_htlc_forwards();
7272
7273                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7274                 assert_eq!(events_2.len(), 1);
7275                 match events_2[0] {
7276                         Event::PaymentReceived { ref payment_hash, amt } => {
7277                                 assert_eq!(payment_hash_1, *payment_hash);
7278                                 assert_eq!(amt, 1000000);
7279                         },
7280                         _ => panic!("Unexpected event"),
7281                 }
7282
7283                 nodes[1].node.claim_funds(payment_preimage_1);
7284                 check_added_monitors!(nodes[1], 1);
7285
7286                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7287                 assert_eq!(events_3.len(), 1);
7288                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7289                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7290                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7291                                 assert!(updates.update_add_htlcs.is_empty());
7292                                 assert!(updates.update_fail_htlcs.is_empty());
7293                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7294                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7295                                 assert!(updates.update_fee.is_none());
7296                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7297                         },
7298                         _ => panic!("Unexpected event"),
7299                 };
7300
7301                 if messages_delivered >= 1 {
7302                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7303
7304                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7305                         assert_eq!(events_4.len(), 1);
7306                         match events_4[0] {
7307                                 Event::PaymentSent { ref payment_preimage } => {
7308                                         assert_eq!(payment_preimage_1, *payment_preimage);
7309                                 },
7310                                 _ => panic!("Unexpected event"),
7311                         }
7312
7313                         if messages_delivered >= 2 {
7314                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7315                                 check_added_monitors!(nodes[0], 1);
7316                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7317
7318                                 if messages_delivered >= 3 {
7319                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7320                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7321                                         check_added_monitors!(nodes[1], 1);
7322
7323                                         if messages_delivered >= 4 {
7324                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7325                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7326                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7327                                                 check_added_monitors!(nodes[1], 1);
7328
7329                                                 if messages_delivered >= 5 {
7330                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7331                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7332                                                         check_added_monitors!(nodes[0], 1);
7333                                                 }
7334                                         }
7335                                 }
7336                         }
7337                 }
7338
7339                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7340                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7341                 if messages_delivered < 2 {
7342                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7343                         //TODO: Deduplicate PaymentSent events, then enable this if:
7344                         //if messages_delivered < 1 {
7345                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7346                                 assert_eq!(events_4.len(), 1);
7347                                 match events_4[0] {
7348                                         Event::PaymentSent { ref payment_preimage } => {
7349                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7350                                         },
7351                                         _ => panic!("Unexpected event"),
7352                                 }
7353                         //}
7354                 } else if messages_delivered == 2 {
7355                         // nodes[0] still wants its RAA + commitment_signed
7356                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7357                 } else if messages_delivered == 3 {
7358                         // nodes[0] still wants its commitment_signed
7359                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7360                 } else if messages_delivered == 4 {
7361                         // nodes[1] still wants its final RAA
7362                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7363                 } else if messages_delivered == 5 {
7364                         // Everything was delivered...
7365                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7366                 }
7367
7368                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7369                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7370                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7371
7372                 // Channel should still work fine...
7373                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7374                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7375         }
7376
7377         #[test]
7378         fn test_drop_messages_peer_disconnect_a() {
7379                 do_test_drop_messages_peer_disconnect(0);
7380                 do_test_drop_messages_peer_disconnect(1);
7381                 do_test_drop_messages_peer_disconnect(2);
7382                 do_test_drop_messages_peer_disconnect(3);
7383         }
7384
7385         #[test]
7386         fn test_drop_messages_peer_disconnect_b() {
7387                 do_test_drop_messages_peer_disconnect(4);
7388                 do_test_drop_messages_peer_disconnect(5);
7389                 do_test_drop_messages_peer_disconnect(6);
7390         }
7391
7392         #[test]
7393         fn test_funding_peer_disconnect() {
7394                 // Test that we can lock in our funding tx while disconnected
7395                 let nodes = create_network(2);
7396                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7397
7398                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7399                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7400
7401                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7402                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7403                 assert_eq!(events_1.len(), 1);
7404                 match events_1[0] {
7405                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7406                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7407                         },
7408                         _ => panic!("Unexpected event"),
7409                 }
7410
7411                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7412
7413                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7414                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7415
7416                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7417                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7418                 assert_eq!(events_2.len(), 2);
7419                 match events_2[0] {
7420                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7421                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7422                         },
7423                         _ => panic!("Unexpected event"),
7424                 }
7425                 match events_2[1] {
7426                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7427                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7428                         },
7429                         _ => panic!("Unexpected event"),
7430                 }
7431
7432                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7433
7434                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7435                 // rebroadcasting announcement_signatures upon reconnect.
7436
7437                 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();
7438                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7439                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7440         }
7441
7442         #[test]
7443         fn test_drop_messages_peer_disconnect_dual_htlc() {
7444                 // Test that we can handle reconnecting when both sides of a channel have pending
7445                 // commitment_updates when we disconnect.
7446                 let mut nodes = create_network(2);
7447                 create_announced_chan_between_nodes(&nodes, 0, 1);
7448
7449                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7450
7451                 // Now try to send a second payment which will fail to send
7452                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7453                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7454
7455                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7456                 check_added_monitors!(nodes[0], 1);
7457
7458                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7459                 assert_eq!(events_1.len(), 1);
7460                 match events_1[0] {
7461                         MessageSendEvent::UpdateHTLCs { .. } => {},
7462                         _ => panic!("Unexpected event"),
7463                 }
7464
7465                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7466                 check_added_monitors!(nodes[1], 1);
7467
7468                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7469                 assert_eq!(events_2.len(), 1);
7470                 match events_2[0] {
7471                         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 } } => {
7472                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7473                                 assert!(update_add_htlcs.is_empty());
7474                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7475                                 assert!(update_fail_htlcs.is_empty());
7476                                 assert!(update_fail_malformed_htlcs.is_empty());
7477                                 assert!(update_fee.is_none());
7478
7479                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7480                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7481                                 assert_eq!(events_3.len(), 1);
7482                                 match events_3[0] {
7483                                         Event::PaymentSent { ref payment_preimage } => {
7484                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7485                                         },
7486                                         _ => panic!("Unexpected event"),
7487                                 }
7488
7489                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7490                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7491                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7492                                 check_added_monitors!(nodes[0], 1);
7493                         },
7494                         _ => panic!("Unexpected event"),
7495                 }
7496
7497                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7498                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7499
7500                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7501                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7502                 assert_eq!(reestablish_1.len(), 1);
7503                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7504                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7505                 assert_eq!(reestablish_2.len(), 1);
7506
7507                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7508                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7509                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7510                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7511
7512                 assert!(as_resp.0.is_none());
7513                 assert!(bs_resp.0.is_none());
7514
7515                 assert!(bs_resp.1.is_none());
7516                 assert!(bs_resp.2.is_none());
7517
7518                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7519
7520                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7521                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7522                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7523                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7524                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7525                 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();
7526                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7527                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7528                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7529                 check_added_monitors!(nodes[1], 1);
7530
7531                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7532                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7533                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7534                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7535                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7536                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7537                 assert!(bs_second_commitment_signed.update_fee.is_none());
7538                 check_added_monitors!(nodes[1], 1);
7539
7540                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7541                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7542                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7543                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7544                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7545                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7546                 assert!(as_commitment_signed.update_fee.is_none());
7547                 check_added_monitors!(nodes[0], 1);
7548
7549                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7550                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7551                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7552                 check_added_monitors!(nodes[0], 1);
7553
7554                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7555                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7556                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7557                 check_added_monitors!(nodes[1], 1);
7558
7559                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7560                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7561                 check_added_monitors!(nodes[1], 1);
7562
7563                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7564                 assert_eq!(events_4.len(), 1);
7565                 match events_4[0] {
7566                         Event::PendingHTLCsForwardable { .. } => { },
7567                         _ => panic!("Unexpected event"),
7568                 };
7569
7570                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7571                 nodes[1].node.process_pending_htlc_forwards();
7572
7573                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7574                 assert_eq!(events_5.len(), 1);
7575                 match events_5[0] {
7576                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7577                                 assert_eq!(payment_hash_2, *payment_hash);
7578                         },
7579                         _ => panic!("Unexpected event"),
7580                 }
7581
7582                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7583                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7584                 check_added_monitors!(nodes[0], 1);
7585
7586                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7587         }
7588
7589         #[test]
7590         fn test_simple_monitor_permanent_update_fail() {
7591                 // Test that we handle a simple permanent monitor update failure
7592                 let mut nodes = create_network(2);
7593                 create_announced_chan_between_nodes(&nodes, 0, 1);
7594
7595                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7596                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7597
7598                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7599                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7600                 check_added_monitors!(nodes[0], 1);
7601
7602                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7603                 assert_eq!(events_1.len(), 2);
7604                 match events_1[0] {
7605                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7606                         _ => panic!("Unexpected event"),
7607                 };
7608                 match events_1[1] {
7609                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7610                         _ => panic!("Unexpected event"),
7611                 };
7612
7613                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7614                 // PaymentFailed event
7615
7616                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7617         }
7618
7619         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7620                 // Test that we can recover from a simple temporary monitor update failure optionally with
7621                 // a disconnect in between
7622                 let mut nodes = create_network(2);
7623                 create_announced_chan_between_nodes(&nodes, 0, 1);
7624
7625                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7626                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7627
7628                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7629                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7630                 check_added_monitors!(nodes[0], 1);
7631
7632                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7633                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7634                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7635
7636                 if disconnect {
7637                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7638                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7639                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7640                 }
7641
7642                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7643                 nodes[0].node.test_restore_channel_monitor();
7644                 check_added_monitors!(nodes[0], 1);
7645
7646                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7647                 assert_eq!(events_2.len(), 1);
7648                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7649                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7650                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7651                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7652
7653                 expect_pending_htlcs_forwardable!(nodes[1]);
7654
7655                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7656                 assert_eq!(events_3.len(), 1);
7657                 match events_3[0] {
7658                         Event::PaymentReceived { ref payment_hash, amt } => {
7659                                 assert_eq!(payment_hash_1, *payment_hash);
7660                                 assert_eq!(amt, 1000000);
7661                         },
7662                         _ => panic!("Unexpected event"),
7663                 }
7664
7665                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7666
7667                 // Now set it to failed again...
7668                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7669                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7670                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7671                 check_added_monitors!(nodes[0], 1);
7672
7673                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7674                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7675                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7676
7677                 if disconnect {
7678                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7679                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7680                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7681                 }
7682
7683                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7684                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7685                 nodes[0].node.test_restore_channel_monitor();
7686                 check_added_monitors!(nodes[0], 1);
7687
7688                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7689                 assert_eq!(events_5.len(), 1);
7690                 match events_5[0] {
7691                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7692                         _ => panic!("Unexpected event"),
7693                 }
7694
7695                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7696                 // PaymentFailed event
7697
7698                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7699         }
7700
7701         #[test]
7702         fn test_simple_monitor_temporary_update_fail() {
7703                 do_test_simple_monitor_temporary_update_fail(false);
7704                 do_test_simple_monitor_temporary_update_fail(true);
7705         }
7706
7707         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7708                 let disconnect_flags = 8 | 16;
7709
7710                 // Test that we can recover from a temporary monitor update failure with some in-flight
7711                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7712                 // * First we route a payment, then get a temporary monitor update failure when trying to
7713                 //   route a second payment. We then claim the first payment.
7714                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7715                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7716                 //   the ChannelMonitor on a watchtower).
7717                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7718                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7719                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7720                 //   disconnect_count & !disconnect_flags is 0).
7721                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7722                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7723                 //   disconnect_count, to get the update_fulfill_htlc through.
7724                 // * We then walk through more message exchanges to get the original update_add_htlc
7725                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7726                 //   disconnect/reconnecting based on disconnect_count.
7727                 let mut nodes = create_network(2);
7728                 create_announced_chan_between_nodes(&nodes, 0, 1);
7729
7730                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7731
7732                 // Now try to send a second payment which will fail to send
7733                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7734                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7735
7736                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7737                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7738                 check_added_monitors!(nodes[0], 1);
7739
7740                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7741                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7742                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7743
7744                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7745                 // but nodes[0] won't respond since it is frozen.
7746                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7747                 check_added_monitors!(nodes[1], 1);
7748                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7749                 assert_eq!(events_2.len(), 1);
7750                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7751                         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 } } => {
7752                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7753                                 assert!(update_add_htlcs.is_empty());
7754                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7755                                 assert!(update_fail_htlcs.is_empty());
7756                                 assert!(update_fail_malformed_htlcs.is_empty());
7757                                 assert!(update_fee.is_none());
7758
7759                                 if (disconnect_count & 16) == 0 {
7760                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7761                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7762                                         assert_eq!(events_3.len(), 1);
7763                                         match events_3[0] {
7764                                                 Event::PaymentSent { ref payment_preimage } => {
7765                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7766                                                 },
7767                                                 _ => panic!("Unexpected event"),
7768                                         }
7769
7770                                         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) {
7771                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7772                                         } else { panic!(); }
7773                                 }
7774
7775                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7776                         },
7777                         _ => panic!("Unexpected event"),
7778                 };
7779
7780                 if disconnect_count & !disconnect_flags > 0 {
7781                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7782                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7783                 }
7784
7785                 // Now fix monitor updating...
7786                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7787                 nodes[0].node.test_restore_channel_monitor();
7788                 check_added_monitors!(nodes[0], 1);
7789
7790                 macro_rules! disconnect_reconnect_peers { () => { {
7791                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7792                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7793
7794                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7795                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7796                         assert_eq!(reestablish_1.len(), 1);
7797                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7798                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7799                         assert_eq!(reestablish_2.len(), 1);
7800
7801                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7802                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7803                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7804                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7805
7806                         assert!(as_resp.0.is_none());
7807                         assert!(bs_resp.0.is_none());
7808
7809                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7810                 } } }
7811
7812                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7813                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7814                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7815
7816                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7817                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7818                         assert_eq!(reestablish_1.len(), 1);
7819                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7820                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7821                         assert_eq!(reestablish_2.len(), 1);
7822
7823                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7824                         check_added_monitors!(nodes[0], 0);
7825                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7826                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7827                         check_added_monitors!(nodes[1], 0);
7828                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7829
7830                         assert!(as_resp.0.is_none());
7831                         assert!(bs_resp.0.is_none());
7832
7833                         assert!(bs_resp.1.is_none());
7834                         if (disconnect_count & 16) == 0 {
7835                                 assert!(bs_resp.2.is_none());
7836
7837                                 assert!(as_resp.1.is_some());
7838                                 assert!(as_resp.2.is_some());
7839                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7840                         } else {
7841                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7842                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7843                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7844                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7845                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7846                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7847
7848                                 assert!(as_resp.1.is_none());
7849
7850                                 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();
7851                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7852                                 assert_eq!(events_3.len(), 1);
7853                                 match events_3[0] {
7854                                         Event::PaymentSent { ref payment_preimage } => {
7855                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7856                                         },
7857                                         _ => panic!("Unexpected event"),
7858                                 }
7859
7860                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7861                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7862                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7863                                 check_added_monitors!(nodes[0], 1);
7864
7865                                 as_resp.1 = Some(as_resp_raa);
7866                                 bs_resp.2 = None;
7867                         }
7868
7869                         if disconnect_count & !disconnect_flags > 1 {
7870                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7871
7872                                 if (disconnect_count & 16) == 0 {
7873                                         assert!(reestablish_1 == second_reestablish_1);
7874                                         assert!(reestablish_2 == second_reestablish_2);
7875                                 }
7876                                 assert!(as_resp == second_as_resp);
7877                                 assert!(bs_resp == second_bs_resp);
7878                         }
7879
7880                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7881                 } else {
7882                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7883                         assert_eq!(events_4.len(), 2);
7884                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7885                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7886                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7887                                         msg.clone()
7888                                 },
7889                                 _ => panic!("Unexpected event"),
7890                         })
7891                 };
7892
7893                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7894
7895                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7896                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7897                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7898                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7899                 check_added_monitors!(nodes[1], 1);
7900
7901                 if disconnect_count & !disconnect_flags > 2 {
7902                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7903
7904                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7905                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7906
7907                         assert!(as_resp.2.is_none());
7908                         assert!(bs_resp.2.is_none());
7909                 }
7910
7911                 let as_commitment_update;
7912                 let bs_second_commitment_update;
7913
7914                 macro_rules! handle_bs_raa { () => {
7915                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7916                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7917                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7918                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7919                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7920                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7921                         assert!(as_commitment_update.update_fee.is_none());
7922                         check_added_monitors!(nodes[0], 1);
7923                 } }
7924
7925                 macro_rules! handle_initial_raa { () => {
7926                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7927                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7928                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7929                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7930                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7931                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7932                         assert!(bs_second_commitment_update.update_fee.is_none());
7933                         check_added_monitors!(nodes[1], 1);
7934                 } }
7935
7936                 if (disconnect_count & 8) == 0 {
7937                         handle_bs_raa!();
7938
7939                         if disconnect_count & !disconnect_flags > 3 {
7940                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7941
7942                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7943                                 assert!(bs_resp.1.is_none());
7944
7945                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7946                                 assert!(bs_resp.2.is_none());
7947
7948                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7949                         }
7950
7951                         handle_initial_raa!();
7952
7953                         if disconnect_count & !disconnect_flags > 4 {
7954                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7955
7956                                 assert!(as_resp.1.is_none());
7957                                 assert!(bs_resp.1.is_none());
7958
7959                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7960                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7961                         }
7962                 } else {
7963                         handle_initial_raa!();
7964
7965                         if disconnect_count & !disconnect_flags > 3 {
7966                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7967
7968                                 assert!(as_resp.1.is_none());
7969                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7970
7971                                 assert!(as_resp.2.is_none());
7972                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7973
7974                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7975                         }
7976
7977                         handle_bs_raa!();
7978
7979                         if disconnect_count & !disconnect_flags > 4 {
7980                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7981
7982                                 assert!(as_resp.1.is_none());
7983                                 assert!(bs_resp.1.is_none());
7984
7985                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7986                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7987                         }
7988                 }
7989
7990                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7991                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7992                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7993                 check_added_monitors!(nodes[0], 1);
7994
7995                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
7996                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7997                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7998                 check_added_monitors!(nodes[1], 1);
7999
8000                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8001                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8002                 check_added_monitors!(nodes[1], 1);
8003
8004                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8005                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8006                 check_added_monitors!(nodes[0], 1);
8007
8008                 expect_pending_htlcs_forwardable!(nodes[1]);
8009
8010                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8011                 assert_eq!(events_5.len(), 1);
8012                 match events_5[0] {
8013                         Event::PaymentReceived { ref payment_hash, amt } => {
8014                                 assert_eq!(payment_hash_2, *payment_hash);
8015                                 assert_eq!(amt, 1000000);
8016                         },
8017                         _ => panic!("Unexpected event"),
8018                 }
8019
8020                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8021         }
8022
8023         #[test]
8024         fn test_monitor_temporary_update_fail_a() {
8025                 do_test_monitor_temporary_update_fail(0);
8026                 do_test_monitor_temporary_update_fail(1);
8027                 do_test_monitor_temporary_update_fail(2);
8028                 do_test_monitor_temporary_update_fail(3);
8029                 do_test_monitor_temporary_update_fail(4);
8030                 do_test_monitor_temporary_update_fail(5);
8031         }
8032
8033         #[test]
8034         fn test_monitor_temporary_update_fail_b() {
8035                 do_test_monitor_temporary_update_fail(2 | 8);
8036                 do_test_monitor_temporary_update_fail(3 | 8);
8037                 do_test_monitor_temporary_update_fail(4 | 8);
8038                 do_test_monitor_temporary_update_fail(5 | 8);
8039         }
8040
8041         #[test]
8042         fn test_monitor_temporary_update_fail_c() {
8043                 do_test_monitor_temporary_update_fail(1 | 16);
8044                 do_test_monitor_temporary_update_fail(2 | 16);
8045                 do_test_monitor_temporary_update_fail(3 | 16);
8046                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8047                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8048         }
8049
8050         #[test]
8051         fn test_monitor_update_fail_cs() {
8052                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8053                 let mut nodes = create_network(2);
8054                 create_announced_chan_between_nodes(&nodes, 0, 1);
8055
8056                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8057                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8058                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8059                 check_added_monitors!(nodes[0], 1);
8060
8061                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8062                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8063
8064                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8065                 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() {
8066                         assert_eq!(err, "Failed to update ChannelMonitor");
8067                 } else { panic!(); }
8068                 check_added_monitors!(nodes[1], 1);
8069                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8070
8071                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8072                 nodes[1].node.test_restore_channel_monitor();
8073                 check_added_monitors!(nodes[1], 1);
8074                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8075                 assert_eq!(responses.len(), 2);
8076
8077                 match responses[0] {
8078                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8079                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8080                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8081                                 check_added_monitors!(nodes[0], 1);
8082                         },
8083                         _ => panic!("Unexpected event"),
8084                 }
8085                 match responses[1] {
8086                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8087                                 assert!(updates.update_add_htlcs.is_empty());
8088                                 assert!(updates.update_fulfill_htlcs.is_empty());
8089                                 assert!(updates.update_fail_htlcs.is_empty());
8090                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8091                                 assert!(updates.update_fee.is_none());
8092                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8093
8094                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8095                                 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() {
8096                                         assert_eq!(err, "Failed to update ChannelMonitor");
8097                                 } else { panic!(); }
8098                                 check_added_monitors!(nodes[0], 1);
8099                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8100                         },
8101                         _ => panic!("Unexpected event"),
8102                 }
8103
8104                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8105                 nodes[0].node.test_restore_channel_monitor();
8106                 check_added_monitors!(nodes[0], 1);
8107
8108                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8109                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8110                 check_added_monitors!(nodes[1], 1);
8111
8112                 let mut events = nodes[1].node.get_and_clear_pending_events();
8113                 assert_eq!(events.len(), 1);
8114                 match events[0] {
8115                         Event::PendingHTLCsForwardable { .. } => { },
8116                         _ => panic!("Unexpected event"),
8117                 };
8118                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8119                 nodes[1].node.process_pending_htlc_forwards();
8120
8121                 events = nodes[1].node.get_and_clear_pending_events();
8122                 assert_eq!(events.len(), 1);
8123                 match events[0] {
8124                         Event::PaymentReceived { payment_hash, amt } => {
8125                                 assert_eq!(payment_hash, our_payment_hash);
8126                                 assert_eq!(amt, 1000000);
8127                         },
8128                         _ => panic!("Unexpected event"),
8129                 };
8130
8131                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8132         }
8133
8134         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8135                 // Tests handling of a monitor update failure when processing an incoming RAA
8136                 let mut nodes = create_network(3);
8137                 create_announced_chan_between_nodes(&nodes, 0, 1);
8138                 create_announced_chan_between_nodes(&nodes, 1, 2);
8139
8140                 // Rebalance a bit so that we can send backwards from 2 to 1.
8141                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8142
8143                 // Route a first payment that we'll fail backwards
8144                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8145
8146                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8147                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8148                 check_added_monitors!(nodes[2], 1);
8149
8150                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8151                 assert!(updates.update_add_htlcs.is_empty());
8152                 assert!(updates.update_fulfill_htlcs.is_empty());
8153                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8154                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8155                 assert!(updates.update_fee.is_none());
8156                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8157
8158                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8159                 check_added_monitors!(nodes[0], 0);
8160
8161                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8162                 // holding cell.
8163                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8164                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8165                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8166                 check_added_monitors!(nodes[0], 1);
8167
8168                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8169                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8170                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8171
8172                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8173                 assert_eq!(events_1.len(), 1);
8174                 match events_1[0] {
8175                         Event::PendingHTLCsForwardable { .. } => { },
8176                         _ => panic!("Unexpected event"),
8177                 };
8178
8179                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8180                 nodes[1].node.process_pending_htlc_forwards();
8181                 check_added_monitors!(nodes[1], 0);
8182                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8183
8184                 // Now fail monitor updating.
8185                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8186                 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() {
8187                         assert_eq!(err, "Failed to update ChannelMonitor");
8188                 } else { panic!(); }
8189                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8190                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8191                 check_added_monitors!(nodes[1], 1);
8192
8193                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8194                 // for forwarding.
8195
8196                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8197                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8198                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8199                 check_added_monitors!(nodes[0], 1);
8200
8201                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8202                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8203                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8204                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8205                 check_added_monitors!(nodes[1], 0);
8206
8207                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8208                 assert_eq!(events_2.len(), 1);
8209                 match events_2.remove(0) {
8210                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8211                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8212                                 assert!(updates.update_fulfill_htlcs.is_empty());
8213                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8214                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8215                                 assert!(updates.update_add_htlcs.is_empty());
8216                                 assert!(updates.update_fee.is_none());
8217
8218                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8219                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
8220
8221                                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
8222                                 assert_eq!(msg_events.len(), 1);
8223                                 match msg_events[0] {
8224                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
8225                                         },
8226                                         _ => panic!("Unexpected event"),
8227                                 }
8228
8229                                 let events = nodes[0].node.get_and_clear_pending_events();
8230                                 assert_eq!(events.len(), 1);
8231                                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
8232                                         assert_eq!(payment_hash, payment_hash_3);
8233                                         assert!(!rejected_by_dest);
8234                                 } else { panic!("Unexpected event!"); }
8235                         },
8236                         _ => panic!("Unexpected event type!"),
8237                 };
8238
8239                 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
8240                         // Try to route another payment backwards from 2 to make sure 1 holds off on responding
8241                         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
8242                         let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8243                         nodes[2].node.send_payment(route, payment_hash_4).unwrap();
8244                         check_added_monitors!(nodes[2], 1);
8245
8246                         send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
8247                         nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8248                         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) {
8249                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
8250                         } else { panic!(); }
8251                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8252                         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8253                         (Some(payment_preimage_4), Some(payment_hash_4))
8254                 } else { (None, None) };
8255
8256                 // Restore monitor updating, ensuring we immediately get a fail-back update and a
8257                 // update_add update.
8258                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8259                 nodes[1].node.test_restore_channel_monitor();
8260                 check_added_monitors!(nodes[1], 2);
8261
8262                 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
8263                 if test_ignore_second_cs {
8264                         assert_eq!(events_3.len(), 3);
8265                 } else {
8266                         assert_eq!(events_3.len(), 2);
8267                 }
8268
8269                 // Note that the ordering of the events for different nodes is non-prescriptive, though the
8270                 // ordering of the two events that both go to nodes[2] have to stay in the same order.
8271                 let messages_a = match events_3.pop().unwrap() {
8272                         MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
8273                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8274                                 assert!(updates.update_fulfill_htlcs.is_empty());
8275                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8276                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8277                                 assert!(updates.update_add_htlcs.is_empty());
8278                                 assert!(updates.update_fee.is_none());
8279                                 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
8280                         },
8281                         _ => panic!("Unexpected event type!"),
8282                 };
8283                 let raa = if test_ignore_second_cs {
8284                         match events_3.remove(1) {
8285                                 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
8286                                         assert_eq!(node_id, nodes[2].node.get_our_node_id());
8287                                         Some(msg.clone())
8288                                 },
8289                                 _ => panic!("Unexpected event"),
8290                         }
8291                 } else { None };
8292                 let send_event_b = SendEvent::from_event(events_3.remove(0));
8293                 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
8294
8295                 // Now deliver the new messages...
8296
8297                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
8298                 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
8299                 let events_4 = nodes[0].node.get_and_clear_pending_events();
8300                 assert_eq!(events_4.len(), 1);
8301                 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
8302                         assert_eq!(payment_hash, payment_hash_1);
8303                         assert!(rejected_by_dest);
8304                 } else { panic!("Unexpected event!"); }
8305
8306                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
8307                 if test_ignore_second_cs {
8308                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
8309                         check_added_monitors!(nodes[2], 1);
8310                         let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8311                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
8312                         check_added_monitors!(nodes[2], 1);
8313                         let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8314                         assert!(bs_cs.update_add_htlcs.is_empty());
8315                         assert!(bs_cs.update_fail_htlcs.is_empty());
8316                         assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
8317                         assert!(bs_cs.update_fulfill_htlcs.is_empty());
8318                         assert!(bs_cs.update_fee.is_none());
8319
8320                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
8321                         check_added_monitors!(nodes[1], 1);
8322                         let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
8323                         assert!(as_cs.update_add_htlcs.is_empty());
8324                         assert!(as_cs.update_fail_htlcs.is_empty());
8325                         assert!(as_cs.update_fail_malformed_htlcs.is_empty());
8326                         assert!(as_cs.update_fulfill_htlcs.is_empty());
8327                         assert!(as_cs.update_fee.is_none());
8328
8329                         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
8330                         check_added_monitors!(nodes[1], 1);
8331                         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
8332
8333                         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
8334                         check_added_monitors!(nodes[2], 1);
8335                         let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8336
8337                         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
8338                         check_added_monitors!(nodes[2], 1);
8339                         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
8340
8341                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
8342                         check_added_monitors!(nodes[1], 1);
8343                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8344                 } else {
8345                         commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
8346                 }
8347
8348                 let events_5 = nodes[2].node.get_and_clear_pending_events();
8349                 assert_eq!(events_5.len(), 1);
8350                 match events_5[0] {
8351                         Event::PendingHTLCsForwardable { .. } => { },
8352                         _ => panic!("Unexpected event"),
8353                 };
8354
8355                 nodes[2].node.channel_state.lock().unwrap().next_forward = Instant::now();
8356                 nodes[2].node.process_pending_htlc_forwards();
8357
8358                 let events_6 = nodes[2].node.get_and_clear_pending_events();
8359                 assert_eq!(events_6.len(), 1);
8360                 match events_6[0] {
8361                         Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
8362                         _ => panic!("Unexpected event"),
8363                 };
8364
8365                 if test_ignore_second_cs {
8366                         let events_7 = nodes[1].node.get_and_clear_pending_events();
8367                         assert_eq!(events_7.len(), 1);
8368                         match events_7[0] {
8369                                 Event::PendingHTLCsForwardable { .. } => { },
8370                                 _ => panic!("Unexpected event"),
8371                         };
8372
8373                         nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8374                         nodes[1].node.process_pending_htlc_forwards();
8375                         check_added_monitors!(nodes[1], 1);
8376
8377                         send_event = SendEvent::from_node(&nodes[1]);
8378                         assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
8379                         assert_eq!(send_event.msgs.len(), 1);
8380                         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8381                         commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
8382
8383                         let events_8 = nodes[0].node.get_and_clear_pending_events();
8384                         assert_eq!(events_8.len(), 1);
8385                         match events_8[0] {
8386                                 Event::PendingHTLCsForwardable { .. } => { },
8387                                 _ => panic!("Unexpected event"),
8388                         };
8389
8390                         nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
8391                         nodes[0].node.process_pending_htlc_forwards();
8392
8393                         let events_9 = nodes[0].node.get_and_clear_pending_events();
8394                         assert_eq!(events_9.len(), 1);
8395                         match events_9[0] {
8396                                 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
8397                                 _ => panic!("Unexpected event"),
8398                         };
8399                         claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
8400                 }
8401
8402                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
8403         }
8404
8405         #[test]
8406         fn test_monitor_update_fail_raa() {
8407                 do_test_monitor_update_fail_raa(false);
8408                 do_test_monitor_update_fail_raa(true);
8409         }
8410
8411         #[test]
8412         fn test_monitor_update_fail_reestablish() {
8413                 // Simple test for message retransmission after monitor update failure on
8414                 // channel_reestablish generating a monitor update (which comes from freeing holding cell
8415                 // HTLCs).
8416                 let mut nodes = create_network(3);
8417                 create_announced_chan_between_nodes(&nodes, 0, 1);
8418                 create_announced_chan_between_nodes(&nodes, 1, 2);
8419
8420                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8421
8422                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8423                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8424
8425                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
8426                 check_added_monitors!(nodes[2], 1);
8427                 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8428                 assert!(updates.update_add_htlcs.is_empty());
8429                 assert!(updates.update_fail_htlcs.is_empty());
8430                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8431                 assert!(updates.update_fee.is_none());
8432                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8433                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8434                 check_added_monitors!(nodes[1], 1);
8435                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8436                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
8437
8438                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8439                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8440                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8441
8442                 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
8443                 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8444
8445                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8446
8447                 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() {
8448                         assert_eq!(err, "Failed to update ChannelMonitor");
8449                 } else { panic!(); }
8450                 check_added_monitors!(nodes[1], 1);
8451
8452                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8453                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8454
8455                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8456                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8457
8458                 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
8459                 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
8460
8461                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
8462
8463                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
8464                 check_added_monitors!(nodes[1], 0);
8465                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8466
8467                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8468                 nodes[1].node.test_restore_channel_monitor();
8469                 check_added_monitors!(nodes[1], 1);
8470
8471                 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8472                 assert!(updates.update_add_htlcs.is_empty());
8473                 assert!(updates.update_fail_htlcs.is_empty());
8474                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8475                 assert!(updates.update_fee.is_none());
8476                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8477                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
8478                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
8479
8480                 let events = nodes[0].node.get_and_clear_pending_events();
8481                 assert_eq!(events.len(), 1);
8482                 match events[0] {
8483                         Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
8484                         _ => panic!("Unexpected event"),
8485                 }
8486         }
8487
8488         #[test]
8489         fn test_invalid_channel_announcement() {
8490                 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
8491                 let secp_ctx = Secp256k1::new();
8492                 let nodes = create_network(2);
8493
8494                 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
8495
8496                 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8497                 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
8498                 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8499                 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
8500
8501                 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 } );
8502
8503                 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
8504                 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
8505
8506                 let as_network_key = nodes[0].node.get_our_node_id();
8507                 let bs_network_key = nodes[1].node.get_our_node_id();
8508
8509                 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
8510
8511                 let mut chan_announcement;
8512
8513                 macro_rules! dummy_unsigned_msg {
8514                         () => {
8515                                 msgs::UnsignedChannelAnnouncement {
8516                                         features: msgs::GlobalFeatures::new(),
8517                                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
8518                                         short_channel_id: as_chan.get_short_channel_id().unwrap(),
8519                                         node_id_1: if were_node_one { as_network_key } else { bs_network_key },
8520                                         node_id_2: if were_node_one { bs_network_key } else { as_network_key },
8521                                         bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
8522                                         bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
8523                                         excess_data: Vec::new(),
8524                                 };
8525                         }
8526                 }
8527
8528                 macro_rules! sign_msg {
8529                         ($unsigned_msg: expr) => {
8530                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
8531                                 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
8532                                 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
8533                                 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
8534                                 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
8535                                 chan_announcement = msgs::ChannelAnnouncement {
8536                                         node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
8537                                         node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
8538                                         bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
8539                                         bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
8540                                         contents: $unsigned_msg
8541                                 }
8542                         }
8543                 }
8544
8545                 let unsigned_msg = dummy_unsigned_msg!();
8546                 sign_msg!(unsigned_msg);
8547                 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
8548                 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 } );
8549
8550                 // Configured with Network::Testnet
8551                 let mut unsigned_msg = dummy_unsigned_msg!();
8552                 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
8553                 sign_msg!(unsigned_msg);
8554                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8555
8556                 let mut unsigned_msg = dummy_unsigned_msg!();
8557                 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
8558                 sign_msg!(unsigned_msg);
8559                 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
8560         }
8561
8562         struct VecWriter(Vec<u8>);
8563         impl Writer for VecWriter {
8564                 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
8565                         self.0.extend_from_slice(buf);
8566                         Ok(())
8567                 }
8568                 fn size_hint(&mut self, size: usize) {
8569                         self.0.reserve_exact(size);
8570                 }
8571         }
8572
8573         #[test]
8574         fn test_no_txn_manager_serialize_deserialize() {
8575                 let mut nodes = create_network(2);
8576
8577                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
8578
8579                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8580
8581                 let nodes_0_serialized = nodes[0].node.encode();
8582                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8583                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8584
8585                 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())));
8586                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8587                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8588                 assert!(chan_0_monitor_read.is_empty());
8589
8590                 let mut nodes_0_read = &nodes_0_serialized[..];
8591                 let config = UserConfig::new();
8592                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8593                 let (_, nodes_0_deserialized) = {
8594                         let mut channel_monitors = HashMap::new();
8595                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8596                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8597                                 default_config: config,
8598                                 keys_manager,
8599                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8600                                 monitor: nodes[0].chan_monitor.clone(),
8601                                 chain_monitor: nodes[0].chain_monitor.clone(),
8602                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8603                                 logger: Arc::new(test_utils::TestLogger::new()),
8604                                 channel_monitors: &channel_monitors,
8605                         }).unwrap()
8606                 };
8607                 assert!(nodes_0_read.is_empty());
8608
8609                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8610                 nodes[0].node = Arc::new(nodes_0_deserialized);
8611                 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
8612                 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
8613                 assert_eq!(nodes[0].node.list_channels().len(), 1);
8614                 check_added_monitors!(nodes[0], 1);
8615
8616                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
8617                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
8618                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
8619                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
8620
8621                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
8622                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8623                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
8624                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8625
8626                 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8627                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8628                 for node in nodes.iter() {
8629                         assert!(node.router.handle_channel_announcement(&announcement).unwrap());
8630                         node.router.handle_channel_update(&as_update).unwrap();
8631                         node.router.handle_channel_update(&bs_update).unwrap();
8632                 }
8633
8634                 send_payment(&nodes[0], &[&nodes[1]], 1000000);
8635         }
8636
8637         #[test]
8638         fn test_simple_manager_serialize_deserialize() {
8639                 let mut nodes = create_network(2);
8640                 create_announced_chan_between_nodes(&nodes, 0, 1);
8641
8642                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8643                 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
8644
8645                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8646
8647                 let nodes_0_serialized = nodes[0].node.encode();
8648                 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
8649                 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
8650
8651                 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())));
8652                 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
8653                 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
8654                 assert!(chan_0_monitor_read.is_empty());
8655
8656                 let mut nodes_0_read = &nodes_0_serialized[..];
8657                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8658                 let (_, nodes_0_deserialized) = {
8659                         let mut channel_monitors = HashMap::new();
8660                         channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
8661                         <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8662                                 default_config: UserConfig::new(),
8663                                 keys_manager,
8664                                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8665                                 monitor: nodes[0].chan_monitor.clone(),
8666                                 chain_monitor: nodes[0].chain_monitor.clone(),
8667                                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8668                                 logger: Arc::new(test_utils::TestLogger::new()),
8669                                 channel_monitors: &channel_monitors,
8670                         }).unwrap()
8671                 };
8672                 assert!(nodes_0_read.is_empty());
8673
8674                 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
8675                 nodes[0].node = Arc::new(nodes_0_deserialized);
8676                 check_added_monitors!(nodes[0], 1);
8677
8678                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8679
8680                 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
8681                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
8682         }
8683
8684         #[test]
8685         fn test_manager_serialize_deserialize_inconsistent_monitor() {
8686                 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
8687                 let mut nodes = create_network(4);
8688                 create_announced_chan_between_nodes(&nodes, 0, 1);
8689                 create_announced_chan_between_nodes(&nodes, 2, 0);
8690                 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
8691
8692                 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
8693
8694                 // Serialize the ChannelManager here, but the monitor we keep up-to-date
8695                 let nodes_0_serialized = nodes[0].node.encode();
8696
8697                 route_payment(&nodes[0], &[&nodes[3]], 1000000);
8698                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8699                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8700                 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
8701
8702                 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
8703                 // nodes[3])
8704                 let mut node_0_monitors_serialized = Vec::new();
8705                 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
8706                         let mut writer = VecWriter(Vec::new());
8707                         monitor.1.write_for_disk(&mut writer).unwrap();
8708                         node_0_monitors_serialized.push(writer.0);
8709                 }
8710
8711                 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())));
8712                 let mut node_0_monitors = Vec::new();
8713                 for serialized in node_0_monitors_serialized.iter() {
8714                         let mut read = &serialized[..];
8715                         let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
8716                         assert!(read.is_empty());
8717                         node_0_monitors.push(monitor);
8718                 }
8719
8720                 let mut nodes_0_read = &nodes_0_serialized[..];
8721                 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
8722                 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
8723                         default_config: UserConfig::new(),
8724                         keys_manager,
8725                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
8726                         monitor: nodes[0].chan_monitor.clone(),
8727                         chain_monitor: nodes[0].chain_monitor.clone(),
8728                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
8729                         logger: Arc::new(test_utils::TestLogger::new()),
8730                         channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
8731                 }).unwrap();
8732                 assert!(nodes_0_read.is_empty());
8733
8734                 { // Channel close should result in a commitment tx and an HTLC tx
8735                         let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8736                         assert_eq!(txn.len(), 2);
8737                         assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
8738                         assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
8739                 }
8740
8741                 for monitor in node_0_monitors.drain(..) {
8742                         assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
8743                         check_added_monitors!(nodes[0], 1);
8744                 }
8745                 nodes[0].node = Arc::new(nodes_0_deserialized);
8746
8747                 // nodes[1] and nodes[2] have no lost state with nodes[0]...
8748                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8749                 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
8750                 //... and we can even still claim the payment!
8751                 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
8752
8753                 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
8754                 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
8755                 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
8756                 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) {
8757                         assert_eq!(msg.channel_id, channel_id);
8758                 } else { panic!("Unexpected result"); }
8759         }
8760
8761         macro_rules! check_spendable_outputs {
8762                 ($node: expr, $der_idx: expr) => {
8763                         {
8764                                 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
8765                                 let mut txn = Vec::new();
8766                                 for event in events {
8767                                         match event {
8768                                                 Event::SpendableOutputs { ref outputs } => {
8769                                                         for outp in outputs {
8770                                                                 match *outp {
8771                                                                         SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
8772                                                                                 let input = TxIn {
8773                                                                                         previous_output: outpoint.clone(),
8774                                                                                         script_sig: Script::new(),
8775                                                                                         sequence: 0,
8776                                                                                         witness: Vec::new(),
8777                                                                                 };
8778                                                                                 let outp = TxOut {
8779                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8780                                                                                         value: output.value,
8781                                                                                 };
8782                                                                                 let mut spend_tx = Transaction {
8783                                                                                         version: 2,
8784                                                                                         lock_time: 0,
8785                                                                                         input: vec![input],
8786                                                                                         output: vec![outp],
8787                                                                                 };
8788                                                                                 let secp_ctx = Secp256k1::new();
8789                                                                                 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
8790                                                                                 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
8791                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8792                                                                                 let remotesig = secp_ctx.sign(&sighash, key);
8793                                                                                 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
8794                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8795                                                                                 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
8796                                                                                 txn.push(spend_tx);
8797                                                                         },
8798                                                                         SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
8799                                                                                 let input = TxIn {
8800                                                                                         previous_output: outpoint.clone(),
8801                                                                                         script_sig: Script::new(),
8802                                                                                         sequence: *to_self_delay as u32,
8803                                                                                         witness: Vec::new(),
8804                                                                                 };
8805                                                                                 let outp = TxOut {
8806                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8807                                                                                         value: output.value,
8808                                                                                 };
8809                                                                                 let mut spend_tx = Transaction {
8810                                                                                         version: 2,
8811                                                                                         lock_time: 0,
8812                                                                                         input: vec![input],
8813                                                                                         output: vec![outp],
8814                                                                                 };
8815                                                                                 let secp_ctx = Secp256k1::new();
8816                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
8817                                                                                 let local_delaysig = secp_ctx.sign(&sighash, key);
8818                                                                                 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
8819                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8820                                                                                 spend_tx.input[0].witness.push(vec!(0));
8821                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
8822                                                                                 txn.push(spend_tx);
8823                                                                         },
8824                                                                         SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
8825                                                                                 let secp_ctx = Secp256k1::new();
8826                                                                                 let input = TxIn {
8827                                                                                         previous_output: outpoint.clone(),
8828                                                                                         script_sig: Script::new(),
8829                                                                                         sequence: 0,
8830                                                                                         witness: Vec::new(),
8831                                                                                 };
8832                                                                                 let outp = TxOut {
8833                                                                                         script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
8834                                                                                         value: output.value,
8835                                                                                 };
8836                                                                                 let mut spend_tx = Transaction {
8837                                                                                         version: 2,
8838                                                                                         lock_time: 0,
8839                                                                                         input: vec![input],
8840                                                                                         output: vec![outp.clone()],
8841                                                                                 };
8842                                                                                 let secret = {
8843                                                                                         match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
8844                                                                                                 Ok(master_key) => {
8845                                                                                                         match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
8846                                                                                                                 Ok(key) => key,
8847                                                                                                                 Err(_) => panic!("Your RNG is busted"),
8848                                                                                                         }
8849                                                                                                 }
8850                                                                                                 Err(_) => panic!("Your rng is busted"),
8851                                                                                         }
8852                                                                                 };
8853                                                                                 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
8854                                                                                 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
8855                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
8856                                                                                 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
8857                                                                                 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
8858                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
8859                                                                                 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
8860                                                                                 txn.push(spend_tx);
8861                                                                         },
8862                                                                 }
8863                                                         }
8864                                                 },
8865                                                 _ => panic!("Unexpected event"),
8866                                         };
8867                                 }
8868                                 txn
8869                         }
8870                 }
8871         }
8872
8873         #[test]
8874         fn test_claim_sizeable_push_msat() {
8875                 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
8876                 let nodes = create_network(2);
8877
8878                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8879                 nodes[1].node.force_close_channel(&chan.2);
8880                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8881                 match events[0] {
8882                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8883                         _ => panic!("Unexpected event"),
8884                 }
8885                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8886                 assert_eq!(node_txn.len(), 1);
8887                 check_spends!(node_txn[0], chan.3.clone());
8888                 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
8889
8890                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8891                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8892                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8893                 assert_eq!(spend_txn.len(), 1);
8894                 check_spends!(spend_txn[0], node_txn[0].clone());
8895         }
8896
8897         #[test]
8898         fn test_claim_on_remote_sizeable_push_msat() {
8899                 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8900                 // to_remote output is encumbered by a P2WPKH
8901
8902                 let nodes = create_network(2);
8903
8904                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
8905                 nodes[0].node.force_close_channel(&chan.2);
8906                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8907                 match events[0] {
8908                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8909                         _ => panic!("Unexpected event"),
8910                 }
8911                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8912                 assert_eq!(node_txn.len(), 1);
8913                 check_spends!(node_txn[0], chan.3.clone());
8914                 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
8915
8916                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8917                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
8918                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8919                 match events[0] {
8920                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8921                         _ => panic!("Unexpected event"),
8922                 }
8923                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8924                 assert_eq!(spend_txn.len(), 2);
8925                 assert_eq!(spend_txn[0], spend_txn[1]);
8926                 check_spends!(spend_txn[0], node_txn[0].clone());
8927         }
8928
8929         #[test]
8930         fn test_claim_on_remote_revoked_sizeable_push_msat() {
8931                 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
8932                 // to_remote output is encumbered by a P2WPKH
8933
8934                 let nodes = create_network(2);
8935
8936                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
8937                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8938                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
8939                 assert_eq!(revoked_local_txn[0].input.len(), 1);
8940                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8941
8942                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8943                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8944                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
8945                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8946                 match events[0] {
8947                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8948                         _ => panic!("Unexpected event"),
8949                 }
8950                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8951                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
8952                 assert_eq!(spend_txn.len(), 4);
8953                 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
8954                 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
8955                 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
8956                 check_spends!(spend_txn[1], node_txn[0].clone());
8957         }
8958
8959         #[test]
8960         fn test_static_spendable_outputs_preimage_tx() {
8961                 let nodes = create_network(2);
8962
8963                 // Create some initial channels
8964                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8965
8966                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8967
8968                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
8969                 assert_eq!(commitment_tx[0].input.len(), 1);
8970                 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
8971
8972                 // Settle A's commitment tx on B's chain
8973                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8974                 assert!(nodes[1].node.claim_funds(payment_preimage));
8975                 check_added_monitors!(nodes[1], 1);
8976                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
8977                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8978                 match events[0] {
8979                         MessageSendEvent::UpdateHTLCs { .. } => {},
8980                         _ => panic!("Unexpected event"),
8981                 }
8982                 match events[1] {
8983                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
8984                         _ => panic!("Unexepected event"),
8985                 }
8986
8987                 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
8988                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
8989                 check_spends!(node_txn[0], commitment_tx[0].clone());
8990                 assert_eq!(node_txn[0], node_txn[2]);
8991                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8992                 check_spends!(node_txn[1], chan_1.3.clone());
8993
8994                 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
8995                 assert_eq!(spend_txn.len(), 2);
8996                 assert_eq!(spend_txn[0], spend_txn[1]);
8997                 check_spends!(spend_txn[0], node_txn[0].clone());
8998         }
8999
9000         #[test]
9001         fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
9002                 let nodes = create_network(2);
9003
9004                 // Create some initial channels
9005                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9006
9007                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9008                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
9009                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9010                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9011
9012                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9013
9014                 let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9015                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9016                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9017                 match events[0] {
9018                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9019                         _ => panic!("Unexpected event"),
9020                 }
9021                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9022                 assert_eq!(node_txn.len(), 3);
9023                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
9024                 assert_eq!(node_txn[0].input.len(), 2);
9025                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
9026
9027                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9028                 assert_eq!(spend_txn.len(), 2);
9029                 assert_eq!(spend_txn[0], spend_txn[1]);
9030                 check_spends!(spend_txn[0], node_txn[0].clone());
9031         }
9032
9033         #[test]
9034         fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
9035                 let nodes = create_network(2);
9036
9037                 // Create some initial channels
9038                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9039
9040                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9041                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9042                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9043                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9044
9045                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9046
9047                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9048                 // A will generate HTLC-Timeout from revoked commitment tx
9049                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9050                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9051                 match events[0] {
9052                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9053                         _ => panic!("Unexpected event"),
9054                 }
9055                 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9056                 assert_eq!(revoked_htlc_txn.len(), 3);
9057                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9058                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9059                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9060                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9061                 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
9062
9063                 // B will generate justice tx from A's revoked commitment/HTLC tx
9064                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9065                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9066                 match events[0] {
9067                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9068                         _ => panic!("Unexpected event"),
9069                 }
9070
9071                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9072                 assert_eq!(node_txn.len(), 4);
9073                 assert_eq!(node_txn[3].input.len(), 1);
9074                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9075
9076                 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
9077                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9078                 assert_eq!(spend_txn.len(), 3);
9079                 assert_eq!(spend_txn[0], spend_txn[1]);
9080                 check_spends!(spend_txn[0], node_txn[0].clone());
9081                 check_spends!(spend_txn[2], node_txn[3].clone());
9082         }
9083
9084         #[test]
9085         fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
9086                 let nodes = create_network(2);
9087
9088                 // Create some initial channels
9089                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9090
9091                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
9092                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9093                 assert_eq!(revoked_local_txn[0].input.len(), 1);
9094                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
9095
9096                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9097
9098                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9099                 // B will generate HTLC-Success from revoked commitment tx
9100                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
9101                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9102                 match events[0] {
9103                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9104                         _ => panic!("Unexpected event"),
9105                 }
9106                 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9107
9108                 assert_eq!(revoked_htlc_txn.len(), 3);
9109                 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
9110                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
9111                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9112                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
9113
9114                 // A will generate justice tx from B's revoked commitment/HTLC tx
9115                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
9116                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9117                 match events[0] {
9118                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9119                         _ => panic!("Unexpected event"),
9120                 }
9121
9122                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9123                 assert_eq!(node_txn.len(), 4);
9124                 assert_eq!(node_txn[3].input.len(), 1);
9125                 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
9126
9127                 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
9128                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9129                 assert_eq!(spend_txn.len(), 5);
9130                 assert_eq!(spend_txn[0], spend_txn[2]);
9131                 assert_eq!(spend_txn[1], spend_txn[3]);
9132                 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
9133                 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
9134                 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
9135         }
9136
9137         #[test]
9138         fn test_onchain_to_onchain_claim() {
9139                 // Test that in case of channel closure, we detect the state of output thanks to
9140                 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
9141                 // First, have C claim an HTLC against its own latest commitment transaction.
9142                 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
9143                 // channel.
9144                 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
9145                 // gets broadcast.
9146
9147                 let nodes = create_network(3);
9148
9149                 // Create some initial channels
9150                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9151                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9152
9153                 // Rebalance the network a bit by relaying one payment through all the channels ...
9154                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9155                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
9156
9157                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
9158                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9159                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9160                 check_spends!(commitment_tx[0], chan_2.3.clone());
9161                 nodes[2].node.claim_funds(payment_preimage);
9162                 check_added_monitors!(nodes[2], 1);
9163                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9164                 assert!(updates.update_add_htlcs.is_empty());
9165                 assert!(updates.update_fail_htlcs.is_empty());
9166                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9167                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9168
9169                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9170                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9171                 assert_eq!(events.len(), 1);
9172                 match events[0] {
9173                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9174                         _ => panic!("Unexpected event"),
9175                 }
9176
9177                 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
9178                 assert_eq!(c_txn.len(), 3);
9179                 assert_eq!(c_txn[0], c_txn[2]);
9180                 assert_eq!(commitment_tx[0], c_txn[1]);
9181                 check_spends!(c_txn[1], chan_2.3.clone());
9182                 check_spends!(c_txn[2], c_txn[1].clone());
9183                 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
9184                 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9185                 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9186                 assert_eq!(c_txn[0].lock_time, 0); // Success tx
9187
9188                 // 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
9189                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
9190                 {
9191                         let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9192                         assert_eq!(b_txn.len(), 4);
9193                         assert_eq!(b_txn[0], b_txn[3]);
9194                         check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
9195                         check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
9196                         assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9197                         assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
9198                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9199                         check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
9200                         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9201                         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9202                         assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
9203                         b_txn.clear();
9204                 }
9205                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9206                 check_added_monitors!(nodes[1], 1);
9207                 match msg_events[0] {
9208                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9209                         _ => panic!("Unexpected event"),
9210                 }
9211                 match msg_events[1] {
9212                         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, .. } } => {
9213                                 assert!(update_add_htlcs.is_empty());
9214                                 assert!(update_fail_htlcs.is_empty());
9215                                 assert_eq!(update_fulfill_htlcs.len(), 1);
9216                                 assert!(update_fail_malformed_htlcs.is_empty());
9217                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
9218                         },
9219                         _ => panic!("Unexpected event"),
9220                 };
9221                 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
9222                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9223                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
9224                 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9225                 assert_eq!(b_txn.len(), 3);
9226                 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
9227                 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
9228                 check_spends!(b_txn[0], commitment_tx[0].clone());
9229                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9230                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
9231                 assert_eq!(b_txn[2].lock_time, 0); // Success tx
9232                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
9233                 match msg_events[0] {
9234                         MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
9235                         _ => panic!("Unexpected event"),
9236                 }
9237         }
9238
9239         #[test]
9240         fn test_duplicate_payment_hash_one_failure_one_success() {
9241                 // Topology : A --> B --> C
9242                 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
9243                 let mut nodes = create_network(3);
9244
9245                 create_announced_chan_between_nodes(&nodes, 0, 1);
9246                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
9247
9248                 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
9249                 *nodes[0].network_payment_count.borrow_mut() -= 1;
9250                 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
9251
9252                 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
9253                 assert_eq!(commitment_txn[0].input.len(), 1);
9254                 check_spends!(commitment_txn[0], chan_2.3.clone());
9255
9256                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9257                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9258                 let htlc_timeout_tx;
9259                 { // Extract one of the two HTLC-Timeout transaction
9260                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9261                         assert_eq!(node_txn.len(), 7);
9262                         assert_eq!(node_txn[0], node_txn[5]);
9263                         assert_eq!(node_txn[1], node_txn[6]);
9264                         check_spends!(node_txn[0], commitment_txn[0].clone());
9265                         assert_eq!(node_txn[0].input.len(), 1);
9266                         check_spends!(node_txn[1], commitment_txn[0].clone());
9267                         assert_eq!(node_txn[1].input.len(), 1);
9268                         assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
9269                         check_spends!(node_txn[2], chan_2.3.clone());
9270                         check_spends!(node_txn[3], node_txn[2].clone());
9271                         check_spends!(node_txn[4], node_txn[2].clone());
9272                         htlc_timeout_tx = node_txn[1].clone();
9273                 }
9274
9275                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9276                 match events[0] {
9277                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9278                         _ => panic!("Unexepected event"),
9279                 }
9280
9281                 nodes[2].node.claim_funds(our_payment_preimage);
9282                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
9283                 check_added_monitors!(nodes[2], 2);
9284                 let events = nodes[2].node.get_and_clear_pending_msg_events();
9285                 match events[0] {
9286                         MessageSendEvent::UpdateHTLCs { .. } => {},
9287                         _ => panic!("Unexpected event"),
9288                 }
9289                 match events[1] {
9290                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9291                         _ => panic!("Unexepected event"),
9292                 }
9293                 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9294                 assert_eq!(htlc_success_txn.len(), 5);
9295                 check_spends!(htlc_success_txn[2], chan_2.3.clone());
9296                 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
9297                 assert_eq!(htlc_success_txn[0].input.len(), 1);
9298                 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9299                 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
9300                 assert_eq!(htlc_success_txn[1].input.len(), 1);
9301                 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9302                 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
9303                 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
9304                 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
9305
9306                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
9307                 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9308                 assert!(htlc_updates.update_add_htlcs.is_empty());
9309                 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
9310                 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
9311                 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
9312                 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
9313                 check_added_monitors!(nodes[1], 1);
9314
9315                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
9316                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9317                 {
9318                         commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
9319                         let events = nodes[0].node.get_and_clear_pending_msg_events();
9320                         assert_eq!(events.len(), 1);
9321                         match events[0] {
9322                                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
9323                                 },
9324                                 _ => { panic!("Unexpected event"); }
9325                         }
9326                 }
9327                 let events = nodes[0].node.get_and_clear_pending_events();
9328                 match events[0] {
9329                         Event::PaymentFailed { ref payment_hash, .. } => {
9330                                 assert_eq!(*payment_hash, duplicate_payment_hash);
9331                         }
9332                         _ => panic!("Unexpected event"),
9333                 }
9334
9335                 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
9336                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
9337                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9338                 assert!(updates.update_add_htlcs.is_empty());
9339                 assert!(updates.update_fail_htlcs.is_empty());
9340                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
9341                 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
9342                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9343                 check_added_monitors!(nodes[1], 1);
9344
9345                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
9346                 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
9347
9348                 let events = nodes[0].node.get_and_clear_pending_events();
9349                 match events[0] {
9350                         Event::PaymentSent { ref payment_preimage } => {
9351                                 assert_eq!(*payment_preimage, our_payment_preimage);
9352                         }
9353                         _ => panic!("Unexpected event"),
9354                 }
9355         }
9356
9357         #[test]
9358         fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
9359                 let nodes = create_network(2);
9360
9361                 // Create some initial channels
9362                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9363
9364                 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9365                 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9366                 assert_eq!(local_txn[0].input.len(), 1);
9367                 check_spends!(local_txn[0], chan_1.3.clone());
9368
9369                 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
9370                 nodes[1].node.claim_funds(payment_preimage);
9371                 check_added_monitors!(nodes[1], 1);
9372                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9373                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
9374                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9375                 match events[0] {
9376                         MessageSendEvent::UpdateHTLCs { .. } => {},
9377                         _ => panic!("Unexpected event"),
9378                 }
9379                 match events[1] {
9380                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9381                         _ => panic!("Unexepected event"),
9382                 }
9383                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9384                 assert_eq!(node_txn[0].input.len(), 1);
9385                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
9386                 check_spends!(node_txn[0], local_txn[0].clone());
9387
9388                 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
9389                 let spend_txn = check_spendable_outputs!(nodes[1], 1);
9390                 assert_eq!(spend_txn.len(), 2);
9391                 check_spends!(spend_txn[0], node_txn[0].clone());
9392                 check_spends!(spend_txn[1], node_txn[2].clone());
9393         }
9394
9395         #[test]
9396         fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
9397                 let nodes = create_network(2);
9398
9399                 // Create some initial channels
9400                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
9401
9402                 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
9403                 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
9404                 assert_eq!(local_txn[0].input.len(), 1);
9405                 check_spends!(local_txn[0], chan_1.3.clone());
9406
9407                 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9408                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9409                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
9410                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9411                 match events[0] {
9412                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
9413                         _ => panic!("Unexepected event"),
9414                 }
9415                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9416                 assert_eq!(node_txn[0].input.len(), 1);
9417                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9418                 check_spends!(node_txn[0], local_txn[0].clone());
9419
9420                 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
9421                 let spend_txn = check_spendable_outputs!(nodes[0], 1);
9422                 assert_eq!(spend_txn.len(), 8);
9423                 assert_eq!(spend_txn[0], spend_txn[2]);
9424                 assert_eq!(spend_txn[0], spend_txn[4]);
9425                 assert_eq!(spend_txn[0], spend_txn[6]);
9426                 assert_eq!(spend_txn[1], spend_txn[3]);
9427                 assert_eq!(spend_txn[1], spend_txn[5]);
9428                 assert_eq!(spend_txn[1], spend_txn[7]);
9429                 check_spends!(spend_txn[0], local_txn[0].clone());
9430                 check_spends!(spend_txn[1], node_txn[0].clone());
9431         }
9432
9433         #[test]
9434         fn test_static_output_closing_tx() {
9435                 let nodes = create_network(2);
9436
9437                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
9438
9439                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
9440                 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
9441
9442                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9443                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9444                 let spend_txn = check_spendable_outputs!(nodes[0], 2);
9445                 assert_eq!(spend_txn.len(), 1);
9446                 check_spends!(spend_txn[0], closing_tx.clone());
9447
9448                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
9449                 let spend_txn = check_spendable_outputs!(nodes[1], 2);
9450                 assert_eq!(spend_txn.len(), 1);
9451                 check_spends!(spend_txn[0], closing_tx);
9452         }
9453 }