Add constant for HTLC failure anti-reorg delay
[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
38 use crypto;
39 use crypto::mac::{Mac,MacResult};
40 use crypto::hmac::Hmac;
41 use crypto::digest::Digest;
42 use crypto::symmetriccipher::SynchronousStreamCipher;
43
44 use std::{cmp, ptr, mem};
45 use std::collections::{HashMap, hash_map, HashSet};
46 use std::io::Cursor;
47 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
48 use std::sync::atomic::{AtomicUsize, Ordering};
49 use std::time::{Instant,Duration};
50
51 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 ///
53 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
54 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
55 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 ///
57 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
58 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
59 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
60 /// the HTLC backwards along the relevant path).
61 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
62 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
63 mod channel_held_info {
64         use ln::msgs;
65         use ln::router::Route;
66         use ln::channelmanager::PaymentHash;
67         use secp256k1::key::SecretKey;
68
69         /// Stores the info we will need to send when we want to forward an HTLC onwards
70         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
71         pub struct PendingForwardHTLCInfo {
72                 pub(super) onion_packet: Option<msgs::OnionPacket>,
73                 pub(super) incoming_shared_secret: [u8; 32],
74                 pub(super) payment_hash: PaymentHash,
75                 pub(super) short_channel_id: u64,
76                 pub(super) amt_to_forward: u64,
77                 pub(super) outgoing_cltv_value: u32,
78         }
79
80         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81         pub enum HTLCFailureMsg {
82                 Relay(msgs::UpdateFailHTLC),
83                 Malformed(msgs::UpdateFailMalformedHTLC),
84         }
85
86         /// Stores whether we can't forward an HTLC or relevant forwarding info
87         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
88         pub enum PendingHTLCStatus {
89                 Forward(PendingForwardHTLCInfo),
90                 Fail(HTLCFailureMsg),
91         }
92
93         /// Tracks the inbound corresponding to an outbound HTLC
94         #[derive(Clone, PartialEq)]
95         pub struct HTLCPreviousHopData {
96                 pub(super) short_channel_id: u64,
97                 pub(super) htlc_id: u64,
98                 pub(super) incoming_packet_shared_secret: [u8; 32],
99         }
100
101         /// Tracks the inbound corresponding to an outbound HTLC
102         #[derive(Clone, PartialEq)]
103         pub enum HTLCSource {
104                 PreviousHopData(HTLCPreviousHopData),
105                 OutboundRoute {
106                         route: Route,
107                         session_priv: SecretKey,
108                         /// Technically we can recalculate this from the route, but we cache it here to avoid
109                         /// doing a double-pass on route when we get a failure back
110                         first_hop_htlc_msat: u64,
111                 },
112         }
113         #[cfg(test)]
114         impl HTLCSource {
115                 pub fn dummy() -> Self {
116                         HTLCSource::OutboundRoute {
117                                 route: Route { hops: Vec::new() },
118                                 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
119                                 first_hop_htlc_msat: 0,
120                         }
121                 }
122         }
123
124         #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
125         pub(crate) enum HTLCFailReason {
126                 ErrorPacket {
127                         err: msgs::OnionErrorPacket,
128                 },
129                 Reason {
130                         failure_code: u16,
131                         data: Vec<u8>,
132                 }
133         }
134 }
135 pub(super) use self::channel_held_info::*;
136
137 /// payment_hash type, use to cross-lock hop
138 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139 pub struct PaymentHash(pub [u8;32]);
140 /// payment_preimage type, use to route payment between hop
141 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142 pub struct PaymentPreimage(pub [u8;32]);
143
144 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
145
146 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
147 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
148 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
149 /// channel_state lock. We then return the set of things that need to be done outside the lock in
150 /// this struct and call handle_error!() on it.
151
152 struct MsgHandleErrInternal {
153         err: msgs::HandleError,
154         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
155 }
156 impl MsgHandleErrInternal {
157         #[inline]
158         fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
159                 Self {
160                         err: HandleError {
161                                 err,
162                                 action: Some(msgs::ErrorAction::SendErrorMessage {
163                                         msg: msgs::ErrorMessage {
164                                                 channel_id,
165                                                 data: err.to_string()
166                                         },
167                                 }),
168                         },
169                         shutdown_finish: None,
170                 }
171         }
172         #[inline]
173         fn from_no_close(err: msgs::HandleError) -> Self {
174                 Self { err, shutdown_finish: None }
175         }
176         #[inline]
177         fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
178                 Self {
179                         err: HandleError {
180                                 err,
181                                 action: Some(msgs::ErrorAction::SendErrorMessage {
182                                         msg: msgs::ErrorMessage {
183                                                 channel_id,
184                                                 data: err.to_string()
185                                         },
186                                 }),
187                         },
188                         shutdown_finish: Some((shutdown_res, channel_update)),
189                 }
190         }
191         #[inline]
192         fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
193                 Self {
194                         err: match err {
195                                 ChannelError::Ignore(msg) => HandleError {
196                                         err: msg,
197                                         action: Some(msgs::ErrorAction::IgnoreError),
198                                 },
199                                 ChannelError::Close(msg) => HandleError {
200                                         err: msg,
201                                         action: Some(msgs::ErrorAction::SendErrorMessage {
202                                                 msg: msgs::ErrorMessage {
203                                                         channel_id,
204                                                         data: msg.to_string()
205                                                 },
206                                         }),
207                                 },
208                         },
209                         shutdown_finish: None,
210                 }
211         }
212 }
213
214 /// Pass to fail_htlc_backwwards to indicate the reason to fail the payment
215 /// after a PaymentReceived event.
216 #[derive(PartialEq)]
217 pub enum PaymentFailReason {
218         /// Indicate the preimage for payment_hash is not known after a PaymentReceived event
219         PreimageUnknown,
220         /// Indicate the payment amount is incorrect ( received is < expected or > 2*expected ) after a PaymentReceived event
221         AmountMismatch,
222 }
223
224 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
225 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
226 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
227 /// probably increase this significantly.
228 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
229
230 struct HTLCForwardInfo {
231         prev_short_channel_id: u64,
232         prev_htlc_id: u64,
233         forward_info: PendingForwardHTLCInfo,
234 }
235
236 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
237 /// be sent in the order they appear in the return value, however sometimes the order needs to be
238 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
239 /// they were originally sent). In those cases, this enum is also returned.
240 #[derive(Clone, PartialEq)]
241 pub(super) enum RAACommitmentOrder {
242         /// Send the CommitmentUpdate messages first
243         CommitmentFirst,
244         /// Send the RevokeAndACK message first
245         RevokeAndACKFirst,
246 }
247
248 struct ChannelHolder {
249         by_id: HashMap<[u8; 32], Channel>,
250         short_to_id: HashMap<u64, [u8; 32]>,
251         next_forward: Instant,
252         /// short channel id -> forward infos. Key of 0 means payments received
253         /// Note that while this is held in the same mutex as the channels themselves, no consistency
254         /// guarantees are made about there existing a channel with the short id here, nor the short
255         /// ids in the PendingForwardHTLCInfo!
256         forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
257         /// Note that while this is held in the same mutex as the channels themselves, no consistency
258         /// guarantees are made about the channels given here actually existing anymore by the time you
259         /// go to read them!
260         claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
261         /// Messages to send to peers - pushed to in the same lock that they are generated in (except
262         /// for broadcast messages, where ordering isn't as strict).
263         pending_msg_events: Vec<events::MessageSendEvent>,
264 }
265 struct MutChannelHolder<'a> {
266         by_id: &'a mut HashMap<[u8; 32], Channel>,
267         short_to_id: &'a mut HashMap<u64, [u8; 32]>,
268         next_forward: &'a mut Instant,
269         forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
270         claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
271         pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
272 }
273 impl ChannelHolder {
274         fn borrow_parts(&mut self) -> MutChannelHolder {
275                 MutChannelHolder {
276                         by_id: &mut self.by_id,
277                         short_to_id: &mut self.short_to_id,
278                         next_forward: &mut self.next_forward,
279                         forward_htlcs: &mut self.forward_htlcs,
280                         claimable_htlcs: &mut self.claimable_htlcs,
281                         pending_msg_events: &mut self.pending_msg_events,
282                 }
283         }
284 }
285
286 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
287 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
288
289 /// Manager which keeps track of a number of channels and sends messages to the appropriate
290 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
291 ///
292 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
293 /// to individual Channels.
294 ///
295 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
296 /// all peers during write/read (though does not modify this instance, only the instance being
297 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
298 /// called funding_transaction_generated for outbound channels).
299 ///
300 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
301 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
302 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
303 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
304 /// the serialization process). If the deserialized version is out-of-date compared to the
305 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
306 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
307 ///
308 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
309 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
310 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
311 /// block_connected() to step towards your best block) upon deserialization before using the
312 /// object!
313 pub struct ChannelManager {
314         default_configuration: UserConfig,
315         genesis_hash: Sha256dHash,
316         fee_estimator: Arc<FeeEstimator>,
317         monitor: Arc<ManyChannelMonitor>,
318         chain_monitor: Arc<ChainWatchInterface>,
319         tx_broadcaster: Arc<BroadcasterInterface>,
320
321         latest_block_height: AtomicUsize,
322         last_block_hash: Mutex<Sha256dHash>,
323         secp_ctx: Secp256k1<secp256k1::All>,
324
325         channel_state: Mutex<ChannelHolder>,
326         our_network_key: SecretKey,
327
328         pending_events: Mutex<Vec<events::Event>>,
329         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
330         /// Essentially just when we're serializing ourselves out.
331         /// Taken first everywhere where we are making changes before any other locks.
332         total_consistency_lock: RwLock<()>,
333
334         keys_manager: Arc<KeysInterface>,
335
336         logger: Arc<Logger>,
337 }
338
339 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
340 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
341 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
342 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
343 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
344 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
345 const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
346
347 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
348 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
349 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
350 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
351 // on-chain to time out the HTLC.
352 #[deny(const_err)]
353 #[allow(dead_code)]
354 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
355
356 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
357 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
358 #[deny(const_err)]
359 #[allow(dead_code)]
360 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
361
362 macro_rules! secp_call {
363         ( $res: expr, $err: expr ) => {
364                 match $res {
365                         Ok(key) => key,
366                         Err(_) => return Err($err),
367                 }
368         };
369 }
370
371 struct OnionKeys {
372         #[cfg(test)]
373         shared_secret: SharedSecret,
374         #[cfg(test)]
375         blinding_factor: [u8; 32],
376         ephemeral_pubkey: PublicKey,
377         rho: [u8; 32],
378         mu: [u8; 32],
379 }
380
381 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
382 pub struct ChannelDetails {
383         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
384         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
385         /// Note that this means this value is *not* persistent - it can change once during the
386         /// lifetime of the channel.
387         pub channel_id: [u8; 32],
388         /// The position of the funding transaction in the chain. None if the funding transaction has
389         /// not yet been confirmed and the channel fully opened.
390         pub short_channel_id: Option<u64>,
391         /// The node_id of our counterparty
392         pub remote_network_id: PublicKey,
393         /// The value, in satoshis, of this channel as appears in the funding output
394         pub channel_value_satoshis: u64,
395         /// The user_id passed in to create_channel, or 0 if the channel was inbound.
396         pub user_id: u64,
397 }
398
399 macro_rules! handle_error {
400         ($self: ident, $internal: expr, $their_node_id: expr) => {
401                 match $internal {
402                         Ok(msg) => Ok(msg),
403                         Err(MsgHandleErrInternal { err, shutdown_finish }) => {
404                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
405                                         $self.finish_force_close_channel(shutdown_res);
406                                         if let Some(update) = update_option {
407                                                 let mut channel_state = $self.channel_state.lock().unwrap();
408                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
409                                                         msg: update
410                                                 });
411                                         }
412                                 }
413                                 Err(err)
414                         },
415                 }
416         }
417 }
418
419 macro_rules! break_chan_entry {
420         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
421                 match $res {
422                         Ok(res) => res,
423                         Err(ChannelError::Ignore(msg)) => {
424                                 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
425                         },
426                         Err(ChannelError::Close(msg)) => {
427                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
428                                 let (channel_id, mut chan) = $entry.remove_entry();
429                                 if let Some(short_id) = chan.get_short_channel_id() {
430                                         $channel_state.short_to_id.remove(&short_id);
431                                 }
432                                 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
433                         },
434                 }
435         }
436 }
437
438 macro_rules! try_chan_entry {
439         ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
440                 match $res {
441                         Ok(res) => res,
442                         Err(ChannelError::Ignore(msg)) => {
443                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
444                         },
445                         Err(ChannelError::Close(msg)) => {
446                                 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
447                                 let (channel_id, mut chan) = $entry.remove_entry();
448                                 if let Some(short_id) = chan.get_short_channel_id() {
449                                         $channel_state.short_to_id.remove(&short_id);
450                                 }
451                                 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
452                         },
453                 }
454         }
455 }
456
457 macro_rules! return_monitor_err {
458         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
459                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new())
460         };
461         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $raa_first_dropped_cs: expr) => {
462                 if $action_type != RAACommitmentOrder::RevokeAndACKFirst { panic!("Bad return_monitor_err call!"); }
463                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, Vec::new(), Vec::new(), $raa_first_dropped_cs)
464         };
465         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr) => {
466                 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $failed_forwards, $failed_fails, false)
467         };
468         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $failed_forwards: expr, $failed_fails: expr, $raa_first_dropped_cs: expr) => {
469                 match $err {
470                         ChannelMonitorUpdateErr::PermanentFailure => {
471                                 let (channel_id, mut chan) = $entry.remove_entry();
472                                 if let Some(short_id) = chan.get_short_channel_id() {
473                                         $channel_state.short_to_id.remove(&short_id);
474                                 }
475                                 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
476                                 // chain in a confused state! We need to move them into the ChannelMonitor which
477                                 // will be responsible for failing backwards once things confirm on-chain.
478                                 // It's ok that we drop $failed_forwards here - at this point we'd rather they
479                                 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
480                                 // us bother trying to claim it just to forward on to another peer. If we're
481                                 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
482                                 // given up the preimage yet, so might as well just wait until the payment is
483                                 // retried, avoiding the on-chain fees.
484                                 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
485                         },
486                         ChannelMonitorUpdateErr::TemporaryFailure => {
487                                 $entry.get_mut().monitor_update_failed($action_type, $failed_forwards, $failed_fails, $raa_first_dropped_cs);
488                                 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
489                         },
490                 }
491         }
492 }
493
494 // Does not break in case of TemporaryFailure!
495 macro_rules! maybe_break_monitor_err {
496         ($self: expr, $err: expr, $channel_state: expr, $entry: expr, $action_type: path) => {
497                 match $err {
498                         ChannelMonitorUpdateErr::PermanentFailure => {
499                                 let (channel_id, mut chan) = $entry.remove_entry();
500                                 if let Some(short_id) = chan.get_short_channel_id() {
501                                         $channel_state.short_to_id.remove(&short_id);
502                                 }
503                                 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
504                         },
505                         ChannelMonitorUpdateErr::TemporaryFailure => {
506                                 $entry.get_mut().monitor_update_failed($action_type, Vec::new(), Vec::new(), false);
507                         },
508                 }
509         }
510 }
511
512 impl ChannelManager {
513         /// Constructs a new ChannelManager to hold several channels and route between them.
514         ///
515         /// This is the main "logic hub" for all channel-related actions, and implements
516         /// ChannelMessageHandler.
517         ///
518         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
519         ///
520         /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
521         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> {
522                 let secp_ctx = Secp256k1::new();
523
524                 let res = Arc::new(ChannelManager {
525                         default_configuration: config.clone(),
526                         genesis_hash: genesis_block(network).header.bitcoin_hash(),
527                         fee_estimator: feeest.clone(),
528                         monitor: monitor.clone(),
529                         chain_monitor,
530                         tx_broadcaster,
531
532                         latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
533                         last_block_hash: Mutex::new(Default::default()),
534                         secp_ctx,
535
536                         channel_state: Mutex::new(ChannelHolder{
537                                 by_id: HashMap::new(),
538                                 short_to_id: HashMap::new(),
539                                 next_forward: Instant::now(),
540                                 forward_htlcs: HashMap::new(),
541                                 claimable_htlcs: HashMap::new(),
542                                 pending_msg_events: Vec::new(),
543                         }),
544                         our_network_key: keys_manager.get_node_secret(),
545
546                         pending_events: Mutex::new(Vec::new()),
547                         total_consistency_lock: RwLock::new(()),
548
549                         keys_manager,
550
551                         logger,
552                 });
553                 let weak_res = Arc::downgrade(&res);
554                 res.chain_monitor.register_listener(weak_res);
555                 Ok(res)
556         }
557
558         /// Creates a new outbound channel to the given remote node and with the given value.
559         ///
560         /// user_id will be provided back as user_channel_id in FundingGenerationReady and
561         /// FundingBroadcastSafe events to allow tracking of which events correspond with which
562         /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
563         /// may wish to avoid using 0 for user_id here.
564         ///
565         /// If successful, will generate a SendOpenChannel message event, so you should probably poll
566         /// PeerManager::process_events afterwards.
567         ///
568         /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
569         /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
570         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
571                 if channel_value_satoshis < 1000 {
572                         return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
573                 }
574
575                 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)?;
576                 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
577
578                 let _ = self.total_consistency_lock.read().unwrap();
579                 let mut channel_state = self.channel_state.lock().unwrap();
580                 match channel_state.by_id.entry(channel.channel_id()) {
581                         hash_map::Entry::Occupied(_) => {
582                                 if cfg!(feature = "fuzztarget") {
583                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
584                                 } else {
585                                         panic!("RNG is bad???");
586                                 }
587                         },
588                         hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
589                 }
590                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
591                         node_id: their_network_key,
592                         msg: res,
593                 });
594                 Ok(())
595         }
596
597         /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
598         /// more information.
599         pub fn list_channels(&self) -> Vec<ChannelDetails> {
600                 let channel_state = self.channel_state.lock().unwrap();
601                 let mut res = Vec::with_capacity(channel_state.by_id.len());
602                 for (channel_id, channel) in channel_state.by_id.iter() {
603                         res.push(ChannelDetails {
604                                 channel_id: (*channel_id).clone(),
605                                 short_channel_id: channel.get_short_channel_id(),
606                                 remote_network_id: channel.get_their_node_id(),
607                                 channel_value_satoshis: channel.get_value_satoshis(),
608                                 user_id: channel.get_user_id(),
609                         });
610                 }
611                 res
612         }
613
614         /// Gets the list of usable channels, in random order. Useful as an argument to
615         /// Router::get_route to ensure non-announced channels are used.
616         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
617                 let channel_state = self.channel_state.lock().unwrap();
618                 let mut res = Vec::with_capacity(channel_state.by_id.len());
619                 for (channel_id, channel) in channel_state.by_id.iter() {
620                         // Note we use is_live here instead of usable which leads to somewhat confused
621                         // internal/external nomenclature, but that's ok cause that's probably what the user
622                         // really wanted anyway.
623                         if channel.is_live() {
624                                 res.push(ChannelDetails {
625                                         channel_id: (*channel_id).clone(),
626                                         short_channel_id: channel.get_short_channel_id(),
627                                         remote_network_id: channel.get_their_node_id(),
628                                         channel_value_satoshis: channel.get_value_satoshis(),
629                                         user_id: channel.get_user_id(),
630                                 });
631                         }
632                 }
633                 res
634         }
635
636         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
637         /// will be accepted on the given channel, and after additional timeout/the closing of all
638         /// pending HTLCs, the channel will be closed on chain.
639         ///
640         /// May generate a SendShutdown message event on success, which should be relayed.
641         pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
642                 let _ = self.total_consistency_lock.read().unwrap();
643
644                 let (mut failed_htlcs, chan_option) = {
645                         let mut channel_state_lock = self.channel_state.lock().unwrap();
646                         let channel_state = channel_state_lock.borrow_parts();
647                         match channel_state.by_id.entry(channel_id.clone()) {
648                                 hash_map::Entry::Occupied(mut chan_entry) => {
649                                         let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
650                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
651                                                 node_id: chan_entry.get().get_their_node_id(),
652                                                 msg: shutdown_msg
653                                         });
654                                         if chan_entry.get().is_shutdown() {
655                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
656                                                         channel_state.short_to_id.remove(&short_id);
657                                                 }
658                                                 (failed_htlcs, Some(chan_entry.remove_entry().1))
659                                         } else { (failed_htlcs, None) }
660                                 },
661                                 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
662                         }
663                 };
664                 for htlc_source in failed_htlcs.drain(..) {
665                         // unknown_next_peer...I dunno who that is anymore....
666                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
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                         // unknown_next_peer...I dunno who that is anymore....
690                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
691                 }
692                 for tx in local_txn {
693                         self.tx_broadcaster.broadcast_transaction(&tx);
694                 }
695         }
696
697         /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
698         /// the chain and rejecting new HTLCs on the given channel.
699         pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
700                 let _ = self.total_consistency_lock.read().unwrap();
701
702                 let mut chan = {
703                         let mut channel_state_lock = self.channel_state.lock().unwrap();
704                         let channel_state = channel_state_lock.borrow_parts();
705                         if let Some(chan) = channel_state.by_id.remove(channel_id) {
706                                 if let Some(short_id) = chan.get_short_channel_id() {
707                                         channel_state.short_to_id.remove(&short_id);
708                                 }
709                                 chan
710                         } else {
711                                 return;
712                         }
713                 };
714                 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
715                 self.finish_force_close_channel(chan.force_shutdown());
716                 if let Ok(update) = self.get_channel_update(&chan) {
717                         let mut channel_state = self.channel_state.lock().unwrap();
718                         channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
719                                 msg: update
720                         });
721                 }
722         }
723
724         /// Force close all channels, immediately broadcasting the latest local commitment transaction
725         /// for each to the chain and rejecting new HTLCs on each.
726         pub fn force_close_all_channels(&self) {
727                 for chan in self.list_channels() {
728                         self.force_close_channel(&chan.channel_id);
729                 }
730         }
731
732         #[inline]
733         fn gen_rho_mu_from_shared_secret(shared_secret: &[u8]) -> ([u8; 32], [u8; 32]) {
734                 assert_eq!(shared_secret.len(), 32);
735                 ({
736                         let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
737                         hmac.input(&shared_secret[..]);
738                         let mut res = [0; 32];
739                         hmac.raw_result(&mut res);
740                         res
741                 },
742                 {
743                         let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
744                         hmac.input(&shared_secret[..]);
745                         let mut res = [0; 32];
746                         hmac.raw_result(&mut res);
747                         res
748                 })
749         }
750
751         #[inline]
752         fn gen_um_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
753                 assert_eq!(shared_secret.len(), 32);
754                 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
755                 hmac.input(&shared_secret[..]);
756                 let mut res = [0; 32];
757                 hmac.raw_result(&mut res);
758                 res
759         }
760
761         #[inline]
762         fn gen_ammag_from_shared_secret(shared_secret: &[u8]) -> [u8; 32] {
763                 assert_eq!(shared_secret.len(), 32);
764                 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
765                 hmac.input(&shared_secret[..]);
766                 let mut res = [0; 32];
767                 hmac.raw_result(&mut res);
768                 res
769         }
770
771         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
772         #[inline]
773         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> {
774                 let mut blinded_priv = session_priv.clone();
775                 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
776
777                 for hop in route.hops.iter() {
778                         let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
779
780                         let mut sha = Sha256::new();
781                         sha.input(&blinded_pub.serialize()[..]);
782                         sha.input(&shared_secret[..]);
783                         let mut blinding_factor = [0u8; 32];
784                         sha.result(&mut blinding_factor);
785
786                         let ephemeral_pubkey = blinded_pub;
787
788                         blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
789                         blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
790
791                         callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
792                 }
793
794                 Ok(())
795         }
796
797         // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
798         fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
799                 let mut res = Vec::with_capacity(route.hops.len());
800
801                 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
802                         let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret[..]);
803
804                         res.push(OnionKeys {
805                                 #[cfg(test)]
806                                 shared_secret,
807                                 #[cfg(test)]
808                                 blinding_factor: _blinding_factor,
809                                 ephemeral_pubkey,
810                                 rho,
811                                 mu,
812                         });
813                 })?;
814
815                 Ok(res)
816         }
817
818         /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
819         fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
820                 let mut cur_value_msat = 0u64;
821                 let mut cur_cltv = starting_htlc_offset;
822                 let mut last_short_channel_id = 0;
823                 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
824                 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
825                 unsafe { res.set_len(route.hops.len()); }
826
827                 for (idx, hop) in route.hops.iter().enumerate().rev() {
828                         // First hop gets special values so that it can check, on receipt, that everything is
829                         // exactly as it should be (and the next hop isn't trying to probe to find out if we're
830                         // the intended recipient).
831                         let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
832                         let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
833                         res[idx] = msgs::OnionHopData {
834                                 realm: 0,
835                                 data: msgs::OnionRealm0HopData {
836                                         short_channel_id: last_short_channel_id,
837                                         amt_to_forward: value_msat,
838                                         outgoing_cltv_value: cltv,
839                                 },
840                                 hmac: [0; 32],
841                         };
842                         cur_value_msat += hop.fee_msat;
843                         if cur_value_msat >= 21000000 * 100000000 * 1000 {
844                                 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
845                         }
846                         cur_cltv += hop.cltv_expiry_delta as u32;
847                         if cur_cltv >= 500000000 {
848                                 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
849                         }
850                         last_short_channel_id = hop.short_channel_id;
851                 }
852                 Ok((res, cur_value_msat, cur_cltv))
853         }
854
855         #[inline]
856         fn shift_arr_right(arr: &mut [u8; 20*65]) {
857                 unsafe {
858                         ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
859                 }
860                 for i in 0..65 {
861                         arr[i] = 0;
862                 }
863         }
864
865         #[inline]
866         fn xor_bufs(dst: &mut[u8], src: &[u8]) {
867                 assert_eq!(dst.len(), src.len());
868
869                 for i in 0..dst.len() {
870                         dst[i] ^= src[i];
871                 }
872         }
873
874         const ZERO:[u8; 21*65] = [0; 21*65];
875         fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
876                 let mut buf = Vec::with_capacity(21*65);
877                 buf.resize(21*65, 0);
878
879                 let filler = {
880                         let iters = payloads.len() - 1;
881                         let end_len = iters * 65;
882                         let mut res = Vec::with_capacity(end_len);
883                         res.resize(end_len, 0);
884
885                         for (i, keys) in onion_keys.iter().enumerate() {
886                                 if i == payloads.len() - 1 { continue; }
887                                 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
888                                 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
889                                 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
890                         }
891                         res
892                 };
893
894                 let mut packet_data = [0; 20*65];
895                 let mut hmac_res = [0; 32];
896
897                 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
898                         ChannelManager::shift_arr_right(&mut packet_data);
899                         payload.hmac = hmac_res;
900                         packet_data[0..65].copy_from_slice(&payload.encode()[..]);
901
902                         let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
903                         chacha.process(&packet_data, &mut buf[0..20*65]);
904                         packet_data[..].copy_from_slice(&buf[0..20*65]);
905
906                         if i == 0 {
907                                 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
908                         }
909
910                         let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
911                         hmac.input(&packet_data);
912                         hmac.input(&associated_data.0[..]);
913                         hmac.raw_result(&mut hmac_res);
914                 }
915
916                 msgs::OnionPacket{
917                         version: 0,
918                         public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
919                         hop_data: packet_data,
920                         hmac: hmac_res,
921                 }
922         }
923
924         /// Encrypts a failure packet. raw_packet can either be a
925         /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
926         fn encrypt_failure_packet(shared_secret: &[u8], raw_packet: &[u8]) -> msgs::OnionErrorPacket {
927                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
928
929                 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
930                 packet_crypted.resize(raw_packet.len(), 0);
931                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
932                 chacha.process(&raw_packet, &mut packet_crypted[..]);
933                 msgs::OnionErrorPacket {
934                         data: packet_crypted,
935                 }
936         }
937
938         fn build_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
939                 assert_eq!(shared_secret.len(), 32);
940                 assert!(failure_data.len() <= 256 - 2);
941
942                 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
943
944                 let failuremsg = {
945                         let mut res = Vec::with_capacity(2 + failure_data.len());
946                         res.push(((failure_type >> 8) & 0xff) as u8);
947                         res.push(((failure_type >> 0) & 0xff) as u8);
948                         res.extend_from_slice(&failure_data[..]);
949                         res
950                 };
951                 let pad = {
952                         let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
953                         res.resize(256 - 2 - failure_data.len(), 0);
954                         res
955                 };
956                 let mut packet = msgs::DecodedOnionErrorPacket {
957                         hmac: [0; 32],
958                         failuremsg: failuremsg,
959                         pad: pad,
960                 };
961
962                 let mut hmac = Hmac::new(Sha256::new(), &um);
963                 hmac.input(&packet.encode()[32..]);
964                 hmac.raw_result(&mut packet.hmac);
965
966                 packet
967         }
968
969         #[inline]
970         fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
971                 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
972                 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
973         }
974
975         fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
976                 macro_rules! get_onion_hash {
977                         () => {
978                                 {
979                                         let mut sha = Sha256::new();
980                                         sha.input(&msg.onion_routing_packet.hop_data);
981                                         let mut onion_hash = [0; 32];
982                                         sha.result(&mut onion_hash);
983                                         onion_hash
984                                 }
985                         }
986                 }
987
988                 if let Err(_) = msg.onion_routing_packet.public_key {
989                         log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
990                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
991                                 channel_id: msg.channel_id,
992                                 htlc_id: msg.htlc_id,
993                                 sha256_of_onion: get_onion_hash!(),
994                                 failure_code: 0x8000 | 0x4000 | 6,
995                         })), self.channel_state.lock().unwrap());
996                 }
997
998                 let shared_secret = {
999                         let mut arr = [0; 32];
1000                         arr.copy_from_slice(&SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
1001                         arr
1002                 };
1003                 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
1004
1005                 let mut channel_state = None;
1006                 macro_rules! return_err {
1007                         ($msg: expr, $err_code: expr, $data: expr) => {
1008                                 {
1009                                         log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
1010                                         if channel_state.is_none() {
1011                                                 channel_state = Some(self.channel_state.lock().unwrap());
1012                                         }
1013                                         return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1014                                                 channel_id: msg.channel_id,
1015                                                 htlc_id: msg.htlc_id,
1016                                                 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
1017                                         })), channel_state.unwrap());
1018                                 }
1019                         }
1020                 }
1021
1022                 if msg.onion_routing_packet.version != 0 {
1023                         //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
1024                         //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
1025                         //the hash doesn't really serve any purpuse - in the case of hashing all data, the
1026                         //receiving node would have to brute force to figure out which version was put in the
1027                         //packet by the node that send us the message, in the case of hashing the hop_data, the
1028                         //node knows the HMAC matched, so they already know what is there...
1029                         return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
1030                 }
1031
1032                 let mut hmac = Hmac::new(Sha256::new(), &mu);
1033                 hmac.input(&msg.onion_routing_packet.hop_data);
1034                 hmac.input(&msg.payment_hash.0[..]);
1035                 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
1036                         return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
1037                 }
1038
1039                 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
1040                 let next_hop_data = {
1041                         let mut decoded = [0; 65];
1042                         chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
1043                         match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
1044                                 Err(err) => {
1045                                         let error_code = match err {
1046                                                 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
1047                                                 _ => 0x2000 | 2, // Should never happen
1048                                         };
1049                                         return_err!("Unable to decode our hop data", error_code, &[0;0]);
1050                                 },
1051                                 Ok(msg) => msg
1052                         }
1053                 };
1054
1055                 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
1056                                 // OUR PAYMENT!
1057                                 // final_expiry_too_soon
1058                                 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
1059                                         return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
1060                                 }
1061                                 // final_incorrect_htlc_amount
1062                                 if next_hop_data.data.amt_to_forward > msg.amount_msat {
1063                                         return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
1064                                 }
1065                                 // final_incorrect_cltv_expiry
1066                                 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
1067                                         return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
1068                                 }
1069
1070                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
1071                                 // message, however that would leak that we are the recipient of this payment, so
1072                                 // instead we stay symmetric with the forwarding case, only responding (after a
1073                                 // delay) once they've send us a commitment_signed!
1074
1075                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1076                                         onion_packet: None,
1077                                         payment_hash: msg.payment_hash.clone(),
1078                                         short_channel_id: 0,
1079                                         incoming_shared_secret: shared_secret,
1080                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1081                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1082                                 })
1083                         } else {
1084                                 let mut new_packet_data = [0; 20*65];
1085                                 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
1086                                 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
1087
1088                                 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
1089
1090                                 let blinding_factor = {
1091                                         let mut sha = Sha256::new();
1092                                         sha.input(&new_pubkey.serialize()[..]);
1093                                         sha.input(&shared_secret);
1094                                         let mut res = [0u8; 32];
1095                                         sha.result(&mut res);
1096                                         match SecretKey::from_slice(&self.secp_ctx, &res) {
1097                                                 Err(_) => {
1098                                                         return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1099                                                 },
1100                                                 Ok(key) => key
1101                                         }
1102                                 };
1103
1104                                 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
1105                                         return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
1106                                 }
1107
1108                                 let outgoing_packet = msgs::OnionPacket {
1109                                         version: 0,
1110                                         public_key: Ok(new_pubkey),
1111                                         hop_data: new_packet_data,
1112                                         hmac: next_hop_data.hmac.clone(),
1113                                 };
1114
1115                                 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
1116                                         onion_packet: Some(outgoing_packet),
1117                                         payment_hash: msg.payment_hash.clone(),
1118                                         short_channel_id: next_hop_data.data.short_channel_id,
1119                                         incoming_shared_secret: shared_secret,
1120                                         amt_to_forward: next_hop_data.data.amt_to_forward,
1121                                         outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
1122                                 })
1123                         };
1124
1125                 channel_state = Some(self.channel_state.lock().unwrap());
1126                 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
1127                         if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
1128                                 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
1129                                 let forwarding_id = match id_option {
1130                                         None => { // unknown_next_peer
1131                                                 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
1132                                         },
1133                                         Some(id) => id.clone(),
1134                                 };
1135                                 if let Some((err, code, chan_update)) = loop {
1136                                         let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
1137
1138                                         // Note that we could technically not return an error yet here and just hope
1139                                         // that the connection is reestablished or monitor updated by the time we get
1140                                         // around to doing the actual forward, but better to fail early if we can and
1141                                         // hopefully an attacker trying to path-trace payments cannot make this occur
1142                                         // on a small/per-node/per-channel scale.
1143                                         if !chan.is_live() { // channel_disabled
1144                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
1145                                         }
1146                                         if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
1147                                                 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
1148                                         }
1149                                         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) });
1150                                         if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
1151                                                 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())));
1152                                         }
1153                                         if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
1154                                                 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())));
1155                                         }
1156                                         let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1157                                         // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
1158                                         if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
1159                                                 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
1160                                         }
1161                                         if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
1162                                                 break Some(("CLTV expiry is too far in the future", 21, None));
1163                                         }
1164                                         break None;
1165                                 }
1166                                 {
1167                                         let mut res = Vec::with_capacity(8 + 128);
1168                                         if code == 0x1000 | 11 || code == 0x1000 | 12 {
1169                                                 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
1170                                         }
1171                                         else if code == 0x1000 | 13 {
1172                                                 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
1173                                         }
1174                                         if let Some(chan_update) = chan_update {
1175                                                 res.extend_from_slice(&chan_update.encode_with_len()[..]);
1176                                         }
1177                                         return_err!(err, code, &res[..]);
1178                                 }
1179                         }
1180                 }
1181
1182                 (pending_forward_info, channel_state.unwrap())
1183         }
1184
1185         /// only fails if the channel does not yet have an assigned short_id
1186         /// May be called with channel_state already locked!
1187         fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
1188                 let short_channel_id = match chan.get_short_channel_id() {
1189                         None => return Err(HandleError{err: "Channel not yet established", action: None}),
1190                         Some(id) => id,
1191                 };
1192
1193                 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
1194
1195                 let unsigned = msgs::UnsignedChannelUpdate {
1196                         chain_hash: self.genesis_hash,
1197                         short_channel_id: short_channel_id,
1198                         timestamp: chan.get_channel_update_count(),
1199                         flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
1200                         cltv_expiry_delta: CLTV_EXPIRY_DELTA,
1201                         htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
1202                         fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
1203                         fee_proportional_millionths: chan.get_fee_proportional_millionths(),
1204                         excess_data: Vec::new(),
1205                 };
1206
1207                 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
1208                 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key);
1209
1210                 Ok(msgs::ChannelUpdate {
1211                         signature: sig,
1212                         contents: unsigned
1213                 })
1214         }
1215
1216         /// Sends a payment along a given route.
1217         ///
1218         /// Value parameters are provided via the last hop in route, see documentation for RouteHop
1219         /// fields for more info.
1220         ///
1221         /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
1222         /// payment), we don't do anything to stop you! We always try to ensure that if the provided
1223         /// next hop knows the preimage to payment_hash they can claim an additional amount as
1224         /// specified in the last hop in the route! Thus, you should probably do your own
1225         /// payment_preimage tracking (which you should already be doing as they represent "proof of
1226         /// payment") and prevent double-sends yourself.
1227         ///
1228         /// May generate a SendHTLCs message event on success, which should be relayed.
1229         ///
1230         /// Raises APIError::RoutError when invalid route or forward parameter
1231         /// (cltv_delta, fee, node public key) is specified.
1232         /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
1233         /// (including due to previous monitor update failure or new permanent monitor update failure).
1234         /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
1235         /// relevant updates.
1236         ///
1237         /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
1238         /// and you may wish to retry via a different route immediately.
1239         /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
1240         /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
1241         /// the payment via a different route unless you intend to pay twice!
1242         pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
1243                 if route.hops.len() < 1 || route.hops.len() > 20 {
1244                         return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
1245                 }
1246                 let our_node_id = self.get_our_node_id();
1247                 for (idx, hop) in route.hops.iter().enumerate() {
1248                         if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
1249                                 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
1250                         }
1251                 }
1252
1253                 let session_priv = self.keys_manager.get_session_key();
1254
1255                 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1256
1257                 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
1258                                 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
1259                 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1260                 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1261
1262                 let _ = self.total_consistency_lock.read().unwrap();
1263
1264                 let err: Result<(), _> = loop {
1265                         let mut channel_lock = self.channel_state.lock().unwrap();
1266
1267                         let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1268                                 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1269                                 Some(id) => id.clone(),
1270                         };
1271
1272                         let channel_state = channel_lock.borrow_parts();
1273                         if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1274                                 match {
1275                                         if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1276                                                 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1277                                         }
1278                                         if !chan.get().is_live() {
1279                                                 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1280                                         }
1281                                         break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1282                                                 route: route.clone(),
1283                                                 session_priv: session_priv.clone(),
1284                                                 first_hop_htlc_msat: htlc_msat,
1285                                         }, onion_packet), channel_state, chan)
1286                                 } {
1287                                         Some((update_add, commitment_signed, chan_monitor)) => {
1288                                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1289                                                         maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst);
1290                                                         // Note that MonitorUpdateFailed here indicates (per function docs)
1291                                                         // that we will resent the commitment update once we unfree monitor
1292                                                         // updating, so we have to take special care that we don't return
1293                                                         // something else in case we will resend later!
1294                                                         return Err(APIError::MonitorUpdateFailed);
1295                                                 }
1296
1297                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1298                                                         node_id: route.hops.first().unwrap().pubkey,
1299                                                         updates: msgs::CommitmentUpdate {
1300                                                                 update_add_htlcs: vec![update_add],
1301                                                                 update_fulfill_htlcs: Vec::new(),
1302                                                                 update_fail_htlcs: Vec::new(),
1303                                                                 update_fail_malformed_htlcs: Vec::new(),
1304                                                                 update_fee: None,
1305                                                                 commitment_signed,
1306                                                         },
1307                                                 });
1308                                         },
1309                                         None => {},
1310                                 }
1311                         } else { unreachable!(); }
1312                         return Ok(());
1313                 };
1314
1315                 match handle_error!(self, err, route.hops.first().unwrap().pubkey) {
1316                         Ok(_) => unreachable!(),
1317                         Err(e) => {
1318                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1319                                 } else {
1320                                         log_error!(self, "Got bad keys: {}!", e.err);
1321                                         let mut channel_state = self.channel_state.lock().unwrap();
1322                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1323                                                 node_id: route.hops.first().unwrap().pubkey,
1324                                                 action: e.action,
1325                                         });
1326                                 }
1327                                 Err(APIError::ChannelUnavailable { err: e.err })
1328                         },
1329                 }
1330         }
1331
1332         /// Call this upon creation of a funding transaction for the given channel.
1333         ///
1334         /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1335         /// or your counterparty can steal your funds!
1336         ///
1337         /// Panics if a funding transaction has already been provided for this channel.
1338         ///
1339         /// May panic if the funding_txo is duplicative with some other channel (note that this should
1340         /// be trivially prevented by using unique funding transaction keys per-channel).
1341         pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1342                 let _ = self.total_consistency_lock.read().unwrap();
1343
1344                 let (chan, msg, chan_monitor) = {
1345                         let (res, chan) = {
1346                                 let mut channel_state = self.channel_state.lock().unwrap();
1347                                 match channel_state.by_id.remove(temporary_channel_id) {
1348                                         Some(mut chan) => {
1349                                                 (chan.get_outbound_funding_created(funding_txo)
1350                                                         .map_err(|e| if let ChannelError::Close(msg) = e {
1351                                                                 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1352                                                         } else { unreachable!(); })
1353                                                 , chan)
1354                                         },
1355                                         None => return
1356                                 }
1357                         };
1358                         match handle_error!(self, res, chan.get_their_node_id()) {
1359                                 Ok(funding_msg) => {
1360                                         (chan, funding_msg.0, funding_msg.1)
1361                                 },
1362                                 Err(e) => {
1363                                         log_error!(self, "Got bad signatures: {}!", e.err);
1364                                         let mut channel_state = self.channel_state.lock().unwrap();
1365                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1366                                                 node_id: chan.get_their_node_id(),
1367                                                 action: e.action,
1368                                         });
1369                                         return;
1370                                 },
1371                         }
1372                 };
1373                 // Because we have exclusive ownership of the channel here we can release the channel_state
1374                 // lock before add_update_monitor
1375                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1376                         unimplemented!();
1377                 }
1378
1379                 let mut channel_state = self.channel_state.lock().unwrap();
1380                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1381                         node_id: chan.get_their_node_id(),
1382                         msg: msg,
1383                 });
1384                 match channel_state.by_id.entry(chan.channel_id()) {
1385                         hash_map::Entry::Occupied(_) => {
1386                                 panic!("Generated duplicate funding txid?");
1387                         },
1388                         hash_map::Entry::Vacant(e) => {
1389                                 e.insert(chan);
1390                         }
1391                 }
1392         }
1393
1394         fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1395                 if !chan.should_announce() { return None }
1396
1397                 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1398                         Ok(res) => res,
1399                         Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1400                 };
1401                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1402                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1403
1404                 Some(msgs::AnnouncementSignatures {
1405                         channel_id: chan.channel_id(),
1406                         short_channel_id: chan.get_short_channel_id().unwrap(),
1407                         node_signature: our_node_sig,
1408                         bitcoin_signature: our_bitcoin_sig,
1409                 })
1410         }
1411
1412         /// Processes HTLCs which are pending waiting on random forward delay.
1413         ///
1414         /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1415         /// Will likely generate further events.
1416         pub fn process_pending_htlc_forwards(&self) {
1417                 let _ = self.total_consistency_lock.read().unwrap();
1418
1419                 let mut new_events = Vec::new();
1420                 let mut failed_forwards = Vec::new();
1421                 {
1422                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1423                         let channel_state = channel_state_lock.borrow_parts();
1424
1425                         if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1426                                 return;
1427                         }
1428
1429                         for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1430                                 if short_chan_id != 0 {
1431                                         let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1432                                                 Some(chan_id) => chan_id.clone(),
1433                                                 None => {
1434                                                         failed_forwards.reserve(pending_forwards.len());
1435                                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1436                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1437                                                                         short_channel_id: prev_short_channel_id,
1438                                                                         htlc_id: prev_htlc_id,
1439                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1440                                                                 });
1441                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1442                                                         }
1443                                                         continue;
1444                                                 }
1445                                         };
1446                                         let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1447
1448                                         let mut add_htlc_msgs = Vec::new();
1449                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1450                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1451                                                         short_channel_id: prev_short_channel_id,
1452                                                         htlc_id: prev_htlc_id,
1453                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1454                                                 });
1455                                                 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()) {
1456                                                         Err(_e) => {
1457                                                                 let chan_update = self.get_channel_update(forward_chan).unwrap();
1458                                                                 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1459                                                                 continue;
1460                                                         },
1461                                                         Ok(update_add) => {
1462                                                                 match update_add {
1463                                                                         Some(msg) => { add_htlc_msgs.push(msg); },
1464                                                                         None => {
1465                                                                                 // Nothing to do here...we're waiting on a remote
1466                                                                                 // revoke_and_ack before we can add anymore HTLCs. The Channel
1467                                                                                 // will automatically handle building the update_add_htlc and
1468                                                                                 // commitment_signed messages when we can.
1469                                                                                 // TODO: Do some kind of timer to set the channel as !is_live()
1470                                                                                 // as we don't really want others relying on us relaying through
1471                                                                                 // this channel currently :/.
1472                                                                         }
1473                                                                 }
1474                                                         }
1475                                                 }
1476                                         }
1477
1478                                         if !add_htlc_msgs.is_empty() {
1479                                                 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1480                                                         Ok(res) => res,
1481                                                         Err(e) => {
1482                                                                 if let ChannelError::Ignore(_) = e {
1483                                                                         panic!("Stated return value requirements in send_commitment() were not met");
1484                                                                 }
1485                                                                 //TODO: Handle...this is bad!
1486                                                                 continue;
1487                                                         },
1488                                                 };
1489                                                 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1490                                                         unimplemented!();
1491                                                 }
1492                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1493                                                         node_id: forward_chan.get_their_node_id(),
1494                                                         updates: msgs::CommitmentUpdate {
1495                                                                 update_add_htlcs: add_htlc_msgs,
1496                                                                 update_fulfill_htlcs: Vec::new(),
1497                                                                 update_fail_htlcs: Vec::new(),
1498                                                                 update_fail_malformed_htlcs: Vec::new(),
1499                                                                 update_fee: None,
1500                                                                 commitment_signed: commitment_msg,
1501                                                         },
1502                                                 });
1503                                         }
1504                                 } else {
1505                                         for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1506                                                 let prev_hop_data = HTLCPreviousHopData {
1507                                                         short_channel_id: prev_short_channel_id,
1508                                                         htlc_id: prev_htlc_id,
1509                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1510                                                 };
1511                                                 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1512                                                         hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1513                                                         hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1514                                                 };
1515                                                 new_events.push(events::Event::PaymentReceived {
1516                                                         payment_hash: forward_info.payment_hash,
1517                                                         amt: forward_info.amt_to_forward,
1518                                                 });
1519                                         }
1520                                 }
1521                         }
1522                 }
1523
1524                 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1525                         match update {
1526                                 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1527                                 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() }),
1528                         };
1529                 }
1530
1531                 if new_events.is_empty() { return }
1532                 let mut events = self.pending_events.lock().unwrap();
1533                 events.append(&mut new_events);
1534         }
1535
1536         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1537         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
1538                 let _ = self.total_consistency_lock.read().unwrap();
1539
1540                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1541                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1542                 if let Some(mut sources) = removed_source {
1543                         for htlc_with_hash in sources.drain(..) {
1544                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1545                                 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() });
1546                         }
1547                         true
1548                 } else { false }
1549         }
1550
1551         /// Fails an HTLC backwards to the sender of it to us.
1552         /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1553         /// There are several callsites that do stupid things like loop over a list of payment_hashes
1554         /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1555         /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1556         /// still-available channels.
1557         fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1558                 match source {
1559                         HTLCSource::OutboundRoute { .. } => {
1560                                 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1561                                 mem::drop(channel_state_lock);
1562                                 if let &HTLCFailReason::ErrorPacket { ref err } = &onion_error {
1563                                         let (channel_update, payment_retryable) = self.process_onion_failure(&source, err.data.clone());
1564                                         if let Some(update) = channel_update {
1565                                                 self.channel_state.lock().unwrap().pending_msg_events.push(
1566                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate {
1567                                                                 update,
1568                                                         }
1569                                                 );
1570                                         }
1571                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1572                                                 payment_hash: payment_hash.clone(),
1573                                                 rejected_by_dest: !payment_retryable,
1574                                         });
1575                                 } else {
1576                                         //TODO: Pass this back (see GH #243)
1577                                         self.pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1578                                                 payment_hash: payment_hash.clone(),
1579                                                 rejected_by_dest: false, // We failed it ourselves, can't blame them
1580                                         });
1581                                 }
1582                         },
1583                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1584                                 let err_packet = match onion_error {
1585                                         HTLCFailReason::Reason { failure_code, data } => {
1586                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1587                                                 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1588                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1589                                         },
1590                                         HTLCFailReason::ErrorPacket { err } => {
1591                                                 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1592                                                 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1593                                         }
1594                                 };
1595
1596                                 let channel_state = channel_state_lock.borrow_parts();
1597
1598                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1599                                         Some(chan_id) => chan_id.clone(),
1600                                         None => return
1601                                 };
1602
1603                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1604                                 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1605                                         Ok(Some((msg, commitment_msg, chan_monitor))) => {
1606                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1607                                                         unimplemented!();
1608                                                 }
1609                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1610                                                         node_id: chan.get_their_node_id(),
1611                                                         updates: msgs::CommitmentUpdate {
1612                                                                 update_add_htlcs: Vec::new(),
1613                                                                 update_fulfill_htlcs: Vec::new(),
1614                                                                 update_fail_htlcs: vec![msg],
1615                                                                 update_fail_malformed_htlcs: Vec::new(),
1616                                                                 update_fee: None,
1617                                                                 commitment_signed: commitment_msg,
1618                                                         },
1619                                                 });
1620                                         },
1621                                         Ok(None) => {},
1622                                         Err(_e) => {
1623                                                 //TODO: Do something with e?
1624                                                 return;
1625                                         },
1626                                 }
1627                         },
1628                 }
1629         }
1630
1631         /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1632         /// generating message events for the net layer to claim the payment, if possible. Thus, you
1633         /// should probably kick the net layer to go send messages if this returns true!
1634         ///
1635         /// May panic if called except in response to a PaymentReceived event.
1636         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1637                 let mut sha = Sha256::new();
1638                 sha.input(&payment_preimage.0[..]);
1639                 let mut payment_hash = PaymentHash([0; 32]);
1640                 sha.result(&mut payment_hash.0[..]);
1641
1642                 let _ = self.total_consistency_lock.read().unwrap();
1643
1644                 let mut channel_state = Some(self.channel_state.lock().unwrap());
1645                 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1646                 if let Some(mut sources) = removed_source {
1647                         for htlc_with_hash in sources.drain(..) {
1648                                 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1649                                 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1650                         }
1651                         true
1652                 } else { false }
1653         }
1654         fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1655                 match source {
1656                         HTLCSource::OutboundRoute { .. } => {
1657                                 mem::drop(channel_state_lock);
1658                                 let mut pending_events = self.pending_events.lock().unwrap();
1659                                 pending_events.push(events::Event::PaymentSent {
1660                                         payment_preimage
1661                                 });
1662                         },
1663                         HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1664                                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1665                                 let channel_state = channel_state_lock.borrow_parts();
1666
1667                                 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1668                                         Some(chan_id) => chan_id.clone(),
1669                                         None => {
1670                                                 // TODO: There is probably a channel manager somewhere that needs to
1671                                                 // learn the preimage as the channel already hit the chain and that's
1672                                                 // why its missing.
1673                                                 return
1674                                         }
1675                                 };
1676
1677                                 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1678                                 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1679                                         Ok((msgs, monitor_option)) => {
1680                                                 if let Some(chan_monitor) = monitor_option {
1681                                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1682                                                                 unimplemented!();// but def dont push the event...
1683                                                         }
1684                                                 }
1685                                                 if let Some((msg, commitment_signed)) = msgs {
1686                                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1687                                                                 node_id: chan.get_their_node_id(),
1688                                                                 updates: msgs::CommitmentUpdate {
1689                                                                         update_add_htlcs: Vec::new(),
1690                                                                         update_fulfill_htlcs: vec![msg],
1691                                                                         update_fail_htlcs: Vec::new(),
1692                                                                         update_fail_malformed_htlcs: Vec::new(),
1693                                                                         update_fee: None,
1694                                                                         commitment_signed,
1695                                                                 }
1696                                                         });
1697                                                 }
1698                                         },
1699                                         Err(_e) => {
1700                                                 // TODO: There is probably a channel manager somewhere that needs to
1701                                                 // learn the preimage as the channel may be about to hit the chain.
1702                                                 //TODO: Do something with e?
1703                                                 return
1704                                         },
1705                                 }
1706                         },
1707                 }
1708         }
1709
1710         /// Gets the node_id held by this ChannelManager
1711         pub fn get_our_node_id(&self) -> PublicKey {
1712                 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1713         }
1714
1715         /// Used to restore channels to normal operation after a
1716         /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1717         /// operation.
1718         pub fn test_restore_channel_monitor(&self) {
1719                 let mut close_results = Vec::new();
1720                 let mut htlc_forwards = Vec::new();
1721                 let mut htlc_failures = Vec::new();
1722                 let _ = self.total_consistency_lock.read().unwrap();
1723
1724                 {
1725                         let mut channel_lock = self.channel_state.lock().unwrap();
1726                         let channel_state = channel_lock.borrow_parts();
1727                         let short_to_id = channel_state.short_to_id;
1728                         let pending_msg_events = channel_state.pending_msg_events;
1729                         channel_state.by_id.retain(|_, channel| {
1730                                 if channel.is_awaiting_monitor_update() {
1731                                         let chan_monitor = channel.channel_monitor();
1732                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1733                                                 match e {
1734                                                         ChannelMonitorUpdateErr::PermanentFailure => {
1735                                                                 // TODO: There may be some pending HTLCs that we intended to fail
1736                                                                 // backwards when a monitor update failed. We should make sure
1737                                                                 // knowledge of those gets moved into the appropriate in-memory
1738                                                                 // ChannelMonitor and they get failed backwards once we get
1739                                                                 // on-chain confirmations.
1740                                                                 // Note I think #198 addresses this, so once its merged a test
1741                                                                 // should be written.
1742                                                                 if let Some(short_id) = channel.get_short_channel_id() {
1743                                                                         short_to_id.remove(&short_id);
1744                                                                 }
1745                                                                 close_results.push(channel.force_shutdown());
1746                                                                 if let Ok(update) = self.get_channel_update(&channel) {
1747                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1748                                                                                 msg: update
1749                                                                         });
1750                                                                 }
1751                                                                 false
1752                                                         },
1753                                                         ChannelMonitorUpdateErr::TemporaryFailure => true,
1754                                                 }
1755                                         } else {
1756                                                 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1757                                                 if !pending_forwards.is_empty() {
1758                                                         htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1759                                                 }
1760                                                 htlc_failures.append(&mut pending_failures);
1761
1762                                                 macro_rules! handle_cs { () => {
1763                                                         if let Some(update) = commitment_update {
1764                                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1765                                                                         node_id: channel.get_their_node_id(),
1766                                                                         updates: update,
1767                                                                 });
1768                                                         }
1769                                                 } }
1770                                                 macro_rules! handle_raa { () => {
1771                                                         if let Some(revoke_and_ack) = raa {
1772                                                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1773                                                                         node_id: channel.get_their_node_id(),
1774                                                                         msg: revoke_and_ack,
1775                                                                 });
1776                                                         }
1777                                                 } }
1778                                                 match order {
1779                                                         RAACommitmentOrder::CommitmentFirst => {
1780                                                                 handle_cs!();
1781                                                                 handle_raa!();
1782                                                         },
1783                                                         RAACommitmentOrder::RevokeAndACKFirst => {
1784                                                                 handle_raa!();
1785                                                                 handle_cs!();
1786                                                         },
1787                                                 }
1788                                                 true
1789                                         }
1790                                 } else { true }
1791                         });
1792                 }
1793
1794                 for failure in htlc_failures.drain(..) {
1795                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1796                 }
1797                 self.forward_htlcs(&mut htlc_forwards[..]);
1798
1799                 for res in close_results.drain(..) {
1800                         self.finish_force_close_channel(res);
1801                 }
1802         }
1803
1804         fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1805                 if msg.chain_hash != self.genesis_hash {
1806                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1807                 }
1808
1809                 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)
1810                         .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1811                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1812                 let channel_state = channel_state_lock.borrow_parts();
1813                 match channel_state.by_id.entry(channel.channel_id()) {
1814                         hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1815                         hash_map::Entry::Vacant(entry) => {
1816                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1817                                         node_id: their_node_id.clone(),
1818                                         msg: channel.get_accept_channel(),
1819                                 });
1820                                 entry.insert(channel);
1821                         }
1822                 }
1823                 Ok(())
1824         }
1825
1826         fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1827                 let (value, output_script, user_id) = {
1828                         let mut channel_lock = self.channel_state.lock().unwrap();
1829                         let channel_state = channel_lock.borrow_parts();
1830                         match channel_state.by_id.entry(msg.temporary_channel_id) {
1831                                 hash_map::Entry::Occupied(mut chan) => {
1832                                         if chan.get().get_their_node_id() != *their_node_id {
1833                                                 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1834                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1835                                         }
1836                                         try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1837                                         (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1838                                 },
1839                                 //TODO: same as above
1840                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1841                         }
1842                 };
1843                 let mut pending_events = self.pending_events.lock().unwrap();
1844                 pending_events.push(events::Event::FundingGenerationReady {
1845                         temporary_channel_id: msg.temporary_channel_id,
1846                         channel_value_satoshis: value,
1847                         output_script: output_script,
1848                         user_channel_id: user_id,
1849                 });
1850                 Ok(())
1851         }
1852
1853         fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1854                 let ((funding_msg, monitor_update), chan) = {
1855                         let mut channel_lock = self.channel_state.lock().unwrap();
1856                         let channel_state = channel_lock.borrow_parts();
1857                         match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1858                                 hash_map::Entry::Occupied(mut chan) => {
1859                                         if chan.get().get_their_node_id() != *their_node_id {
1860                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1861                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1862                                         }
1863                                         (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1864                                 },
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                 // Because we have exclusive ownership of the channel here we can release the channel_state
1869                 // lock before add_update_monitor
1870                 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1871                         unimplemented!();
1872                 }
1873                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1874                 let channel_state = channel_state_lock.borrow_parts();
1875                 match channel_state.by_id.entry(funding_msg.channel_id) {
1876                         hash_map::Entry::Occupied(_) => {
1877                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1878                         },
1879                         hash_map::Entry::Vacant(e) => {
1880                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1881                                         node_id: their_node_id.clone(),
1882                                         msg: funding_msg,
1883                                 });
1884                                 e.insert(chan);
1885                         }
1886                 }
1887                 Ok(())
1888         }
1889
1890         fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1891                 let (funding_txo, user_id) = {
1892                         let mut channel_lock = self.channel_state.lock().unwrap();
1893                         let channel_state = channel_lock.borrow_parts();
1894                         match channel_state.by_id.entry(msg.channel_id) {
1895                                 hash_map::Entry::Occupied(mut chan) => {
1896                                         if chan.get().get_their_node_id() != *their_node_id {
1897                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1898                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1899                                         }
1900                                         let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1901                                         if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1902                                                 unimplemented!();
1903                                         }
1904                                         (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1905                                 },
1906                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1907                         }
1908                 };
1909                 let mut pending_events = self.pending_events.lock().unwrap();
1910                 pending_events.push(events::Event::FundingBroadcastSafe {
1911                         funding_txo: funding_txo,
1912                         user_channel_id: user_id,
1913                 });
1914                 Ok(())
1915         }
1916
1917         fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1918                 let mut channel_state_lock = self.channel_state.lock().unwrap();
1919                 let channel_state = channel_state_lock.borrow_parts();
1920                 match channel_state.by_id.entry(msg.channel_id) {
1921                         hash_map::Entry::Occupied(mut chan) => {
1922                                 if chan.get().get_their_node_id() != *their_node_id {
1923                                         //TODO: here and below MsgHandleErrInternal, #153 case
1924                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1925                                 }
1926                                 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1927                                 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1928                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1929                                                 node_id: their_node_id.clone(),
1930                                                 msg: announcement_sigs,
1931                                         });
1932                                 }
1933                                 Ok(())
1934                         },
1935                         hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1936                 }
1937         }
1938
1939         fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1940                 let (mut dropped_htlcs, chan_option) = {
1941                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1942                         let channel_state = channel_state_lock.borrow_parts();
1943
1944                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1945                                 hash_map::Entry::Occupied(mut chan_entry) => {
1946                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1947                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1948                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1949                                         }
1950                                         let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1951                                         if let Some(msg) = shutdown {
1952                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1953                                                         node_id: their_node_id.clone(),
1954                                                         msg,
1955                                                 });
1956                                         }
1957                                         if let Some(msg) = closing_signed {
1958                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1959                                                         node_id: their_node_id.clone(),
1960                                                         msg,
1961                                                 });
1962                                         }
1963                                         if chan_entry.get().is_shutdown() {
1964                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1965                                                         channel_state.short_to_id.remove(&short_id);
1966                                                 }
1967                                                 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1968                                         } else { (dropped_htlcs, None) }
1969                                 },
1970                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1971                         }
1972                 };
1973                 for htlc_source in dropped_htlcs.drain(..) {
1974                         // unknown_next_peer...I dunno who that is anymore....
1975                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1976                 }
1977                 if let Some(chan) = chan_option {
1978                         if let Ok(update) = self.get_channel_update(&chan) {
1979                                 let mut channel_state = self.channel_state.lock().unwrap();
1980                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1981                                         msg: update
1982                                 });
1983                         }
1984                 }
1985                 Ok(())
1986         }
1987
1988         fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1989                 let (tx, chan_option) = {
1990                         let mut channel_state_lock = self.channel_state.lock().unwrap();
1991                         let channel_state = channel_state_lock.borrow_parts();
1992                         match channel_state.by_id.entry(msg.channel_id.clone()) {
1993                                 hash_map::Entry::Occupied(mut chan_entry) => {
1994                                         if chan_entry.get().get_their_node_id() != *their_node_id {
1995                                                 //TODO: here and below MsgHandleErrInternal, #153 case
1996                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1997                                         }
1998                                         let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1999                                         if let Some(msg) = closing_signed {
2000                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2001                                                         node_id: their_node_id.clone(),
2002                                                         msg,
2003                                                 });
2004                                         }
2005                                         if tx.is_some() {
2006                                                 // We're done with this channel, we've got a signed closing transaction and
2007                                                 // will send the closing_signed back to the remote peer upon return. This
2008                                                 // also implies there are no pending HTLCs left on the channel, so we can
2009                                                 // fully delete it from tracking (the channel monitor is still around to
2010                                                 // watch for old state broadcasts)!
2011                                                 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
2012                                                         channel_state.short_to_id.remove(&short_id);
2013                                                 }
2014                                                 (tx, Some(chan_entry.remove_entry().1))
2015                                         } else { (tx, None) }
2016                                 },
2017                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2018                         }
2019                 };
2020                 if let Some(broadcast_tx) = tx {
2021                         self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
2022                 }
2023                 if let Some(chan) = chan_option {
2024                         if let Ok(update) = self.get_channel_update(&chan) {
2025                                 let mut channel_state = self.channel_state.lock().unwrap();
2026                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2027                                         msg: update
2028                                 });
2029                         }
2030                 }
2031                 Ok(())
2032         }
2033
2034         fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
2035                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
2036                 //determine the state of the payment based on our response/if we forward anything/the time
2037                 //we take to respond. We should take care to avoid allowing such an attack.
2038                 //
2039                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
2040                 //us repeatedly garbled in different ways, and compare our error messages, which are
2041                 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
2042                 //but we should prevent it anyway.
2043
2044                 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
2045                 let channel_state = channel_state_lock.borrow_parts();
2046
2047                 match channel_state.by_id.entry(msg.channel_id) {
2048                         hash_map::Entry::Occupied(mut chan) => {
2049                                 if chan.get().get_their_node_id() != *their_node_id {
2050                                         //TODO: here MsgHandleErrInternal, #153 case
2051                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2052                                 }
2053                                 if !chan.get().is_usable() {
2054                                         // If the update_add is completely bogus, the call will Err and we will close,
2055                                         // but if we've sent a shutdown and they haven't acknowledged it yet, we just
2056                                         // want to reject the new HTLC and fail it backwards instead of forwarding.
2057                                         if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
2058                                                 let chan_update = self.get_channel_update(chan.get());
2059                                                 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
2060                                                         channel_id: msg.channel_id,
2061                                                         htlc_id: msg.htlc_id,
2062                                                         reason: if let Ok(update) = chan_update {
2063                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &update.encode_with_len()[..])
2064                                                         } else {
2065                                                                 // This can only happen if the channel isn't in the fully-funded
2066                                                                 // state yet, implying our counterparty is trying to route payments
2067                                                                 // over the channel back to themselves (cause no one else should
2068                                                                 // know the short_id is a lightning channel yet). We should have no
2069                                                                 // problem just calling this unknown_next_peer
2070                                                                 ChannelManager::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
2071                                                         },
2072                                                 }));
2073                                         }
2074                                 }
2075                                 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
2076                         },
2077                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2078                 }
2079                 Ok(())
2080         }
2081
2082         fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
2083                 let mut channel_lock = self.channel_state.lock().unwrap();
2084                 let htlc_source = {
2085                         let channel_state = channel_lock.borrow_parts();
2086                         match channel_state.by_id.entry(msg.channel_id) {
2087                                 hash_map::Entry::Occupied(mut chan) => {
2088                                         if chan.get().get_their_node_id() != *their_node_id {
2089                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2090                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2091                                         }
2092                                         try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
2093                                 },
2094                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2095                         }
2096                 };
2097                 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2098                 Ok(())
2099         }
2100
2101         // Process failure we got back from upstream on a payment we sent. Returns update and a boolean
2102         // indicating that the payment itself failed
2103         fn process_onion_failure(&self, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool) {
2104                 if let &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
2105                         macro_rules! onion_failure_log {
2106                                 ( $error_code_textual: expr, $error_code: expr, $reported_name: expr, $reported_value: expr ) => {
2107                                         log_trace!(self, "{}({:#x}) {}({})", $error_code_textual, $error_code, $reported_name, $reported_value);
2108                                 };
2109                                 ( $error_code_textual: expr, $error_code: expr ) => {
2110                                         log_trace!(self, "{}({})", $error_code_textual, $error_code);
2111                                 };
2112                         }
2113
2114                         const BADONION: u16 = 0x8000;
2115                         const PERM: u16 = 0x4000;
2116                         const UPDATE: u16 = 0x1000;
2117
2118                         let mut res = None;
2119                         let mut htlc_msat = *first_hop_htlc_msat;
2120
2121                         // Handle packed channel/node updates for passing back for the route handler
2122                         Self::construct_onion_keys_callback(&self.secp_ctx, route, session_priv, |shared_secret, _, _, route_hop| {
2123                                 if res.is_some() { return; }
2124
2125                                 let incoming_htlc_msat = htlc_msat;
2126                                 let amt_to_forward = htlc_msat - route_hop.fee_msat;
2127                                 htlc_msat = amt_to_forward;
2128
2129                                 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret[..]);
2130
2131                                 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
2132                                 decryption_tmp.resize(packet_decrypted.len(), 0);
2133                                 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
2134                                 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
2135                                 packet_decrypted = decryption_tmp;
2136
2137                                 let is_from_final_node = route.hops.last().unwrap().pubkey == route_hop.pubkey;
2138
2139                                 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::read(&mut Cursor::new(&packet_decrypted)) {
2140                                         let um = ChannelManager::gen_um_from_shared_secret(&shared_secret[..]);
2141                                         let mut hmac = Hmac::new(Sha256::new(), &um);
2142                                         hmac.input(&err_packet.encode()[32..]);
2143                                         let mut calc_tag = [0u8; 32];
2144                                         hmac.raw_result(&mut calc_tag);
2145
2146                                         if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
2147                                                 if err_packet.failuremsg.len() < 2 {
2148                                                         // Useless packet that we can't use but it passed HMAC, so it
2149                                                         // definitely came from the peer in question
2150                                                         res = Some((None, !is_from_final_node));
2151                                                 } else {
2152                                                         let error_code = byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]);
2153
2154                                                         match error_code & 0xff {
2155                                                                 1|2|3 => {
2156                                                                         // either from an intermediate or final node
2157                                                                         //   invalid_realm(PERM|1),
2158                                                                         //   temporary_node_failure(NODE|2)
2159                                                                         //   permanent_node_failure(PERM|NODE|2)
2160                                                                         //   required_node_feature_mssing(PERM|NODE|3)
2161                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2162                                                                                 node_id: route_hop.pubkey,
2163                                                                                 is_permanent: error_code & PERM == PERM,
2164                                                                         }), !(error_code & PERM == PERM && is_from_final_node)));
2165                                                                         // node returning invalid_realm is removed from network_map,
2166                                                                         // although NODE flag is not set, TODO: or remove channel only?
2167                                                                         // retry payment when removed node is not a final node
2168                                                                         return;
2169                                                                 },
2170                                                                 _ => {}
2171                                                         }
2172
2173                                                         if is_from_final_node {
2174                                                                 let payment_retryable = match error_code {
2175                                                                         c if c == PERM|15 => false, // unknown_payment_hash
2176                                                                         c if c == PERM|16 => false, // incorrect_payment_amount
2177                                                                         17 => true, // final_expiry_too_soon
2178                                                                         18 if err_packet.failuremsg.len() == 6 => { // final_incorrect_cltv_expiry
2179                                                                                 let _reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2180                                                                                 true
2181                                                                         },
2182                                                                         19 if err_packet.failuremsg.len() == 10 => { // final_incorrect_htlc_amount
2183                                                                                 let _reported_incoming_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2184                                                                                 true
2185                                                                         },
2186                                                                         _ => {
2187                                                                                 // A final node has sent us either an invalid code or an error_code that
2188                                                                                 // MUST be sent from the processing node, or the formmat of failuremsg
2189                                                                                 // does not coform to the spec.
2190                                                                                 // Remove it from the network map and don't may retry payment
2191                                                                                 res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2192                                                                                         node_id: route_hop.pubkey,
2193                                                                                         is_permanent: true,
2194                                                                                 }), false));
2195                                                                                 return;
2196                                                                         }
2197                                                                 };
2198                                                                 res = Some((None, payment_retryable));
2199                                                                 return;
2200                                                         }
2201
2202                                                         // now, error_code should be only from the intermediate nodes
2203                                                         match error_code {
2204                                                                 _c if error_code & PERM == PERM => {
2205                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
2206                                                                                 short_channel_id: route_hop.short_channel_id,
2207                                                                                 is_permanent: true,
2208                                                                         }), false));
2209                                                                 },
2210                                                                 _c if error_code & UPDATE == UPDATE => {
2211                                                                         let offset = match error_code {
2212                                                                                 c if c == UPDATE|7  => 0, // temporary_channel_failure
2213                                                                                 c if c == UPDATE|11 => 8, // amount_below_minimum
2214                                                                                 c if c == UPDATE|12 => 8, // fee_insufficient
2215                                                                                 c if c == UPDATE|13 => 4, // incorrect_cltv_expiry
2216                                                                                 c if c == UPDATE|14 => 0, // expiry_too_soon
2217                                                                                 c if c == UPDATE|20 => 2, // channel_disabled
2218                                                                                 _ =>  {
2219                                                                                         // node sending unknown code
2220                                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2221                                                                                                 node_id: route_hop.pubkey,
2222                                                                                                 is_permanent: true,
2223                                                                                         }), false));
2224                                                                                         return;
2225                                                                                 }
2226                                                                         };
2227
2228                                                                         if err_packet.failuremsg.len() >= offset + 2 {
2229                                                                                 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[offset+2..offset+4]) as usize;
2230                                                                                 if err_packet.failuremsg.len() >= offset + 4 + update_len {
2231                                                                                         if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&err_packet.failuremsg[offset + 4..offset + 4 + update_len])) {
2232                                                                                                 // if channel_update should NOT have caused the failure:
2233                                                                                                 // MAY treat the channel_update as invalid.
2234                                                                                                 let is_chan_update_invalid = match error_code {
2235                                                                                                         c if c == UPDATE|7 => { // temporary_channel_failure
2236                                                                                                                 false
2237                                                                                                         },
2238                                                                                                         c if c == UPDATE|11 => { // amount_below_minimum
2239                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2240                                                                                                                 onion_failure_log!("amount_below_minimum", UPDATE|11, "htlc_msat", reported_htlc_msat);
2241                                                                                                                 incoming_htlc_msat > chan_update.contents.htlc_minimum_msat
2242                                                                                                         },
2243                                                                                                         c if c == UPDATE|12 => { // fee_insufficient
2244                                                                                                                 let reported_htlc_msat = byte_utils::slice_to_be64(&err_packet.failuremsg[2..2+8]);
2245                                                                                                                 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) });
2246                                                                                                                 onion_failure_log!("fee_insufficient", UPDATE|12, "htlc_msat", reported_htlc_msat);
2247                                                                                                                 new_fee.is_none() || incoming_htlc_msat >= new_fee.unwrap() && incoming_htlc_msat >= amt_to_forward + new_fee.unwrap()
2248                                                                                                         }
2249                                                                                                         c if c == UPDATE|13 => { // incorrect_cltv_expiry
2250                                                                                                                 let reported_cltv_expiry = byte_utils::slice_to_be32(&err_packet.failuremsg[2..2+4]);
2251                                                                                                                 onion_failure_log!("incorrect_cltv_expiry", UPDATE|13, "cltv_expiry", reported_cltv_expiry);
2252                                                                                                                 route_hop.cltv_expiry_delta as u16 >= chan_update.contents.cltv_expiry_delta
2253                                                                                                         },
2254                                                                                                         c if c == UPDATE|20 => { // channel_disabled
2255                                                                                                                 let reported_flags = byte_utils::slice_to_be16(&err_packet.failuremsg[2..2+2]);
2256                                                                                                                 onion_failure_log!("channel_disabled", UPDATE|20, "flags", reported_flags);
2257                                                                                                                 chan_update.contents.flags & 0x01 == 0x01
2258                                                                                                         },
2259                                                                                                         c if c == UPDATE|21 => true, // expiry_too_far
2260                                                                                                         _ => { unreachable!(); },
2261                                                                                                 };
2262
2263                                                                                                 let msg = if is_chan_update_invalid { None } else {
2264                                                                                                         Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
2265                                                                                                                 msg: chan_update,
2266                                                                                                         })
2267                                                                                                 };
2268                                                                                                 res = Some((msg, true));
2269                                                                                                 return;
2270                                                                                         }
2271                                                                                 }
2272                                                                         }
2273                                                                 },
2274                                                                 _c if error_code & BADONION == BADONION => {
2275                                                                         //TODO
2276                                                                 },
2277                                                                 14 => { // expiry_too_soon
2278                                                                         res = Some((None, true));
2279                                                                         return;
2280                                                                 }
2281                                                                 _ => {
2282                                                                         // node sending unknown code
2283                                                                         res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
2284                                                                                 node_id: route_hop.pubkey,
2285                                                                                 is_permanent: true,
2286                                                                         }), false));
2287                                                                         return;
2288                                                                 }
2289                                                         }
2290                                                 }
2291                                         }
2292                                 }
2293                         }).expect("Route that we sent via spontaneously grew invalid keys in the middle of it?");
2294                         res.unwrap_or((None, true))
2295                 } else { ((None, true)) }
2296         }
2297
2298         fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
2299                 let mut channel_lock = self.channel_state.lock().unwrap();
2300                 let channel_state = channel_lock.borrow_parts();
2301                 match channel_state.by_id.entry(msg.channel_id) {
2302                         hash_map::Entry::Occupied(mut chan) => {
2303                                 if chan.get().get_their_node_id() != *their_node_id {
2304                                         //TODO: here and below MsgHandleErrInternal, #153 case
2305                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2306                                 }
2307                                 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
2308                         },
2309                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2310                 }
2311                 Ok(())
2312         }
2313
2314         fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
2315                 let mut channel_lock = self.channel_state.lock().unwrap();
2316                 let channel_state = channel_lock.borrow_parts();
2317                 match channel_state.by_id.entry(msg.channel_id) {
2318                         hash_map::Entry::Occupied(mut chan) => {
2319                                 if chan.get().get_their_node_id() != *their_node_id {
2320                                         //TODO: here and below MsgHandleErrInternal, #153 case
2321                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2322                                 }
2323                                 if (msg.failure_code & 0x8000) == 0 {
2324                                         try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
2325                                 }
2326                                 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);
2327                                 Ok(())
2328                         },
2329                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2330                 }
2331         }
2332
2333         fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
2334                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2335                 let channel_state = channel_state_lock.borrow_parts();
2336                 match channel_state.by_id.entry(msg.channel_id) {
2337                         hash_map::Entry::Occupied(mut chan) => {
2338                                 if chan.get().get_their_node_id() != *their_node_id {
2339                                         //TODO: here and below MsgHandleErrInternal, #153 case
2340                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2341                                 }
2342                                 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
2343                                         try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
2344                                 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2345                                         return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, commitment_signed.is_some());
2346                                         //TODO: Rebroadcast closing_signed if present on monitor update restoration
2347                                 }
2348                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2349                                         node_id: their_node_id.clone(),
2350                                         msg: revoke_and_ack,
2351                                 });
2352                                 if let Some(msg) = commitment_signed {
2353                                         channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2354                                                 node_id: their_node_id.clone(),
2355                                                 updates: msgs::CommitmentUpdate {
2356                                                         update_add_htlcs: Vec::new(),
2357                                                         update_fulfill_htlcs: Vec::new(),
2358                                                         update_fail_htlcs: Vec::new(),
2359                                                         update_fail_malformed_htlcs: Vec::new(),
2360                                                         update_fee: None,
2361                                                         commitment_signed: msg,
2362                                                 },
2363                                         });
2364                                 }
2365                                 if let Some(msg) = closing_signed {
2366                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2367                                                 node_id: their_node_id.clone(),
2368                                                 msg,
2369                                         });
2370                                 }
2371                                 Ok(())
2372                         },
2373                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2374                 }
2375         }
2376
2377         #[inline]
2378         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2379                 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2380                         let mut forward_event = None;
2381                         if !pending_forwards.is_empty() {
2382                                 let mut channel_state = self.channel_state.lock().unwrap();
2383                                 if channel_state.forward_htlcs.is_empty() {
2384                                         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));
2385                                         channel_state.next_forward = forward_event.unwrap();
2386                                 }
2387                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2388                                         match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2389                                                 hash_map::Entry::Occupied(mut entry) => {
2390                                                         entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info });
2391                                                 },
2392                                                 hash_map::Entry::Vacant(entry) => {
2393                                                         entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info }));
2394                                                 }
2395                                         }
2396                                 }
2397                         }
2398                         match forward_event {
2399                                 Some(time) => {
2400                                         let mut pending_events = self.pending_events.lock().unwrap();
2401                                         pending_events.push(events::Event::PendingHTLCsForwardable {
2402                                                 time_forwardable: time
2403                                         });
2404                                 }
2405                                 None => {},
2406                         }
2407                 }
2408         }
2409
2410         fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2411                 let (pending_forwards, mut pending_failures, short_channel_id) = {
2412                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2413                         let channel_state = channel_state_lock.borrow_parts();
2414                         match channel_state.by_id.entry(msg.channel_id) {
2415                                 hash_map::Entry::Occupied(mut chan) => {
2416                                         if chan.get().get_their_node_id() != *their_node_id {
2417                                                 //TODO: here and below MsgHandleErrInternal, #153 case
2418                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2419                                         }
2420                                         let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2421                                                 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2422                                         if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2423                                                 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, pending_forwards, pending_failures);
2424                                         }
2425                                         if let Some(updates) = commitment_update {
2426                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2427                                                         node_id: their_node_id.clone(),
2428                                                         updates,
2429                                                 });
2430                                         }
2431                                         if let Some(msg) = closing_signed {
2432                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2433                                                         node_id: their_node_id.clone(),
2434                                                         msg,
2435                                                 });
2436                                         }
2437                                         (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2438                                 },
2439                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2440                         }
2441                 };
2442                 for failure in pending_failures.drain(..) {
2443                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2444                 }
2445                 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2446
2447                 Ok(())
2448         }
2449
2450         fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2451                 let mut channel_lock = self.channel_state.lock().unwrap();
2452                 let channel_state = channel_lock.borrow_parts();
2453                 match channel_state.by_id.entry(msg.channel_id) {
2454                         hash_map::Entry::Occupied(mut chan) => {
2455                                 if chan.get().get_their_node_id() != *their_node_id {
2456                                         //TODO: here and below MsgHandleErrInternal, #153 case
2457                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2458                                 }
2459                                 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2460                         },
2461                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2462                 }
2463                 Ok(())
2464         }
2465
2466         fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2467                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2468                 let channel_state = channel_state_lock.borrow_parts();
2469
2470                 match channel_state.by_id.entry(msg.channel_id) {
2471                         hash_map::Entry::Occupied(mut chan) => {
2472                                 if chan.get().get_their_node_id() != *their_node_id {
2473                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2474                                 }
2475                                 if !chan.get().is_usable() {
2476                                         return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2477                                 }
2478
2479                                 let our_node_id = self.get_our_node_id();
2480                                 let (announcement, our_bitcoin_sig) =
2481                                         try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2482
2483                                 let were_node_one = announcement.node_id_1 == our_node_id;
2484                                 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
2485                                 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2486                                                 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2487                                         try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2488                                 }
2489
2490                                 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2491
2492                                 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2493                                         msg: msgs::ChannelAnnouncement {
2494                                                 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2495                                                 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2496                                                 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2497                                                 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2498                                                 contents: announcement,
2499                                         },
2500                                         update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2501                                 });
2502                         },
2503                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2504                 }
2505                 Ok(())
2506         }
2507
2508         fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2509                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2510                 let channel_state = channel_state_lock.borrow_parts();
2511
2512                 match channel_state.by_id.entry(msg.channel_id) {
2513                         hash_map::Entry::Occupied(mut chan) => {
2514                                 if chan.get().get_their_node_id() != *their_node_id {
2515                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2516                                 }
2517                                 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2518                                         try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2519                                 if let Some(monitor) = channel_monitor {
2520                                         if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2521                                                 // channel_reestablish doesn't guarantee the order it returns is sensical
2522                                                 // for the messages it returns, but if we're setting what messages to
2523                                                 // re-transmit on monitor update success, we need to make sure it is sane.
2524                                                 if revoke_and_ack.is_none() {
2525                                                         order = RAACommitmentOrder::CommitmentFirst;
2526                                                 }
2527                                                 if commitment_update.is_none() {
2528                                                         order = RAACommitmentOrder::RevokeAndACKFirst;
2529                                                 }
2530                                                 return_monitor_err!(self, e, channel_state, chan, order);
2531                                                 //TODO: Resend the funding_locked if needed once we get the monitor running again
2532                                         }
2533                                 }
2534                                 if let Some(msg) = funding_locked {
2535                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2536                                                 node_id: their_node_id.clone(),
2537                                                 msg
2538                                         });
2539                                 }
2540                                 macro_rules! send_raa { () => {
2541                                         if let Some(msg) = revoke_and_ack {
2542                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2543                                                         node_id: their_node_id.clone(),
2544                                                         msg
2545                                                 });
2546                                         }
2547                                 } }
2548                                 macro_rules! send_cu { () => {
2549                                         if let Some(updates) = commitment_update {
2550                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2551                                                         node_id: their_node_id.clone(),
2552                                                         updates
2553                                                 });
2554                                         }
2555                                 } }
2556                                 match order {
2557                                         RAACommitmentOrder::RevokeAndACKFirst => {
2558                                                 send_raa!();
2559                                                 send_cu!();
2560                                         },
2561                                         RAACommitmentOrder::CommitmentFirst => {
2562                                                 send_cu!();
2563                                                 send_raa!();
2564                                         },
2565                                 }
2566                                 if let Some(msg) = shutdown {
2567                                         channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2568                                                 node_id: their_node_id.clone(),
2569                                                 msg,
2570                                         });
2571                                 }
2572                                 Ok(())
2573                         },
2574                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2575                 }
2576         }
2577
2578         /// Begin Update fee process. Allowed only on an outbound channel.
2579         /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2580         /// PeerManager::process_events afterwards.
2581         /// Note: This API is likely to change!
2582         #[doc(hidden)]
2583         pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2584                 let _ = self.total_consistency_lock.read().unwrap();
2585                 let their_node_id;
2586                 let err: Result<(), _> = loop {
2587                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2588                         let channel_state = channel_state_lock.borrow_parts();
2589
2590                         match channel_state.by_id.entry(channel_id) {
2591                                 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2592                                 hash_map::Entry::Occupied(mut chan) => {
2593                                         if !chan.get().is_outbound() {
2594                                                 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2595                                         }
2596                                         if chan.get().is_awaiting_monitor_update() {
2597                                                 return Err(APIError::MonitorUpdateFailed);
2598                                         }
2599                                         if !chan.get().is_live() {
2600                                                 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2601                                         }
2602                                         their_node_id = chan.get().get_their_node_id();
2603                                         if let Some((update_fee, commitment_signed, chan_monitor)) =
2604                                                         break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2605                                         {
2606                                                 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2607                                                         unimplemented!();
2608                                                 }
2609                                                 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2610                                                         node_id: chan.get().get_their_node_id(),
2611                                                         updates: msgs::CommitmentUpdate {
2612                                                                 update_add_htlcs: Vec::new(),
2613                                                                 update_fulfill_htlcs: Vec::new(),
2614                                                                 update_fail_htlcs: Vec::new(),
2615                                                                 update_fail_malformed_htlcs: Vec::new(),
2616                                                                 update_fee: Some(update_fee),
2617                                                                 commitment_signed,
2618                                                         },
2619                                                 });
2620                                         }
2621                                 },
2622                         }
2623                         return Ok(())
2624                 };
2625
2626                 match handle_error!(self, err, their_node_id) {
2627                         Ok(_) => unreachable!(),
2628                         Err(e) => {
2629                                 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2630                                 } else {
2631                                         log_error!(self, "Got bad keys: {}!", e.err);
2632                                         let mut channel_state = self.channel_state.lock().unwrap();
2633                                         channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2634                                                 node_id: their_node_id,
2635                                                 action: e.action,
2636                                         });
2637                                 }
2638                                 Err(APIError::APIMisuseError { err: e.err })
2639                         },
2640                 }
2641         }
2642 }
2643
2644 impl events::MessageSendEventsProvider for ChannelManager {
2645         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2646                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2647                 // user to serialize a ChannelManager with pending events in it and lose those events on
2648                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2649                 {
2650                         //TODO: This behavior should be documented.
2651                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2652                                 if let Some(preimage) = htlc_update.payment_preimage {
2653                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2654                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2655                                 } else {
2656                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2657                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2658                                 }
2659                         }
2660                 }
2661
2662                 let mut ret = Vec::new();
2663                 let mut channel_state = self.channel_state.lock().unwrap();
2664                 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2665                 ret
2666         }
2667 }
2668
2669 impl events::EventsProvider for ChannelManager {
2670         fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2671                 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2672                 // user to serialize a ChannelManager with pending events in it and lose those events on
2673                 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2674                 {
2675                         //TODO: This behavior should be documented.
2676                         for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2677                                 if let Some(preimage) = htlc_update.payment_preimage {
2678                                         log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2679                                         self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2680                                 } else {
2681                                         log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2682                                         self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
2683                                 }
2684                         }
2685                 }
2686
2687                 let mut ret = Vec::new();
2688                 let mut pending_events = self.pending_events.lock().unwrap();
2689                 mem::swap(&mut ret, &mut *pending_events);
2690                 ret
2691         }
2692 }
2693
2694 impl ChainListener for ChannelManager {
2695         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2696                 let header_hash = header.bitcoin_hash();
2697                 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2698                 let _ = self.total_consistency_lock.read().unwrap();
2699                 let mut failed_channels = Vec::new();
2700                 {
2701                         let mut channel_lock = self.channel_state.lock().unwrap();
2702                         let channel_state = channel_lock.borrow_parts();
2703                         let short_to_id = channel_state.short_to_id;
2704                         let pending_msg_events = channel_state.pending_msg_events;
2705                         channel_state.by_id.retain(|_, channel| {
2706                                 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2707                                 if let Ok(Some(funding_locked)) = chan_res {
2708                                         pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2709                                                 node_id: channel.get_their_node_id(),
2710                                                 msg: funding_locked,
2711                                         });
2712                                         if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2713                                                 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2714                                                         node_id: channel.get_their_node_id(),
2715                                                         msg: announcement_sigs,
2716                                                 });
2717                                         }
2718                                         short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2719                                 } else if let Err(e) = chan_res {
2720                                         pending_msg_events.push(events::MessageSendEvent::HandleError {
2721                                                 node_id: channel.get_their_node_id(),
2722                                                 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2723                                         });
2724                                         return false;
2725                                 }
2726                                 if let Some(funding_txo) = channel.get_funding_txo() {
2727                                         for tx in txn_matched {
2728                                                 for inp in tx.input.iter() {
2729                                                         if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2730                                                                 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()));
2731                                                                 if let Some(short_id) = channel.get_short_channel_id() {
2732                                                                         short_to_id.remove(&short_id);
2733                                                                 }
2734                                                                 // It looks like our counterparty went on-chain. We go ahead and
2735                                                                 // broadcast our latest local state as well here, just in case its
2736                                                                 // some kind of SPV attack, though we expect these to be dropped.
2737                                                                 failed_channels.push(channel.force_shutdown());
2738                                                                 if let Ok(update) = self.get_channel_update(&channel) {
2739                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2740                                                                                 msg: update
2741                                                                         });
2742                                                                 }
2743                                                                 return false;
2744                                                         }
2745                                                 }
2746                                         }
2747                                 }
2748                                 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2749                                         if let Some(short_id) = channel.get_short_channel_id() {
2750                                                 short_to_id.remove(&short_id);
2751                                         }
2752                                         failed_channels.push(channel.force_shutdown());
2753                                         // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2754                                         // the latest local tx for us, so we should skip that here (it doesn't really
2755                                         // hurt anything, but does make tests a bit simpler).
2756                                         failed_channels.last_mut().unwrap().0 = Vec::new();
2757                                         if let Ok(update) = self.get_channel_update(&channel) {
2758                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2759                                                         msg: update
2760                                                 });
2761                                         }
2762                                         return false;
2763                                 }
2764                                 true
2765                         });
2766                 }
2767                 for failure in failed_channels.drain(..) {
2768                         self.finish_force_close_channel(failure);
2769                 }
2770                 self.latest_block_height.store(height as usize, Ordering::Release);
2771                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2772         }
2773
2774         /// We force-close the channel without letting our counterparty participate in the shutdown
2775         fn block_disconnected(&self, header: &BlockHeader) {
2776                 let _ = self.total_consistency_lock.read().unwrap();
2777                 let mut failed_channels = Vec::new();
2778                 {
2779                         let mut channel_lock = self.channel_state.lock().unwrap();
2780                         let channel_state = channel_lock.borrow_parts();
2781                         let short_to_id = channel_state.short_to_id;
2782                         let pending_msg_events = channel_state.pending_msg_events;
2783                         channel_state.by_id.retain(|_,  v| {
2784                                 if v.block_disconnected(header) {
2785                                         if let Some(short_id) = v.get_short_channel_id() {
2786                                                 short_to_id.remove(&short_id);
2787                                         }
2788                                         failed_channels.push(v.force_shutdown());
2789                                         if let Ok(update) = self.get_channel_update(&v) {
2790                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2791                                                         msg: update
2792                                                 });
2793                                         }
2794                                         false
2795                                 } else {
2796                                         true
2797                                 }
2798                         });
2799                 }
2800                 for failure in failed_channels.drain(..) {
2801                         self.finish_force_close_channel(failure);
2802                 }
2803                 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2804                 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2805         }
2806 }
2807
2808 impl ChannelMessageHandler for ChannelManager {
2809         //TODO: Handle errors and close channel (or so)
2810         fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2811                 let _ = self.total_consistency_lock.read().unwrap();
2812                 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2813         }
2814
2815         fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2816                 let _ = self.total_consistency_lock.read().unwrap();
2817                 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2818         }
2819
2820         fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2821                 let _ = self.total_consistency_lock.read().unwrap();
2822                 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2823         }
2824
2825         fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2826                 let _ = self.total_consistency_lock.read().unwrap();
2827                 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2828         }
2829
2830         fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2831                 let _ = self.total_consistency_lock.read().unwrap();
2832                 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2833         }
2834
2835         fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2836                 let _ = self.total_consistency_lock.read().unwrap();
2837                 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2838         }
2839
2840         fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2841                 let _ = self.total_consistency_lock.read().unwrap();
2842                 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2843         }
2844
2845         fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2846                 let _ = self.total_consistency_lock.read().unwrap();
2847                 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2848         }
2849
2850         fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2851                 let _ = self.total_consistency_lock.read().unwrap();
2852                 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2853         }
2854
2855         fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2856                 let _ = self.total_consistency_lock.read().unwrap();
2857                 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2858         }
2859
2860         fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2861                 let _ = self.total_consistency_lock.read().unwrap();
2862                 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2863         }
2864
2865         fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2866                 let _ = self.total_consistency_lock.read().unwrap();
2867                 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2868         }
2869
2870         fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2871                 let _ = self.total_consistency_lock.read().unwrap();
2872                 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2873         }
2874
2875         fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2876                 let _ = self.total_consistency_lock.read().unwrap();
2877                 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2878         }
2879
2880         fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2881                 let _ = self.total_consistency_lock.read().unwrap();
2882                 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2883         }
2884
2885         fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2886                 let _ = self.total_consistency_lock.read().unwrap();
2887                 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg), their_node_id)
2888         }
2889
2890         fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2891                 let _ = self.total_consistency_lock.read().unwrap();
2892                 let mut failed_channels = Vec::new();
2893                 let mut failed_payments = Vec::new();
2894                 {
2895                         let mut channel_state_lock = self.channel_state.lock().unwrap();
2896                         let channel_state = channel_state_lock.borrow_parts();
2897                         let short_to_id = channel_state.short_to_id;
2898                         let pending_msg_events = channel_state.pending_msg_events;
2899                         if no_connection_possible {
2900                                 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2901                                 channel_state.by_id.retain(|_, chan| {
2902                                         if chan.get_their_node_id() == *their_node_id {
2903                                                 if let Some(short_id) = chan.get_short_channel_id() {
2904                                                         short_to_id.remove(&short_id);
2905                                                 }
2906                                                 failed_channels.push(chan.force_shutdown());
2907                                                 if let Ok(update) = self.get_channel_update(&chan) {
2908                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2909                                                                 msg: update
2910                                                         });
2911                                                 }
2912                                                 false
2913                                         } else {
2914                                                 true
2915                                         }
2916                                 });
2917                         } else {
2918                                 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2919                                 channel_state.by_id.retain(|_, chan| {
2920                                         if chan.get_their_node_id() == *their_node_id {
2921                                                 //TODO: mark channel disabled (and maybe announce such after a timeout).
2922                                                 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2923                                                 if !failed_adds.is_empty() {
2924                                                         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
2925                                                         failed_payments.push((chan_update, failed_adds));
2926                                                 }
2927                                                 if chan.is_shutdown() {
2928                                                         if let Some(short_id) = chan.get_short_channel_id() {
2929                                                                 short_to_id.remove(&short_id);
2930                                                         }
2931                                                         return false;
2932                                                 }
2933                                         }
2934                                         true
2935                                 })
2936                         }
2937                 }
2938                 for failure in failed_channels.drain(..) {
2939                         self.finish_force_close_channel(failure);
2940                 }
2941                 for (chan_update, mut htlc_sources) in failed_payments {
2942                         for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2943                                 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2944                         }
2945                 }
2946         }
2947
2948         fn peer_connected(&self, their_node_id: &PublicKey) {
2949                 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2950
2951                 let _ = self.total_consistency_lock.read().unwrap();
2952                 let mut channel_state_lock = self.channel_state.lock().unwrap();
2953                 let channel_state = channel_state_lock.borrow_parts();
2954                 let pending_msg_events = channel_state.pending_msg_events;
2955                 channel_state.by_id.retain(|_, chan| {
2956                         if chan.get_their_node_id() == *their_node_id {
2957                                 if !chan.have_received_message() {
2958                                         // If we created this (outbound) channel while we were disconnected from the
2959                                         // peer we probably failed to send the open_channel message, which is now
2960                                         // lost. We can't have had anything pending related to this channel, so we just
2961                                         // drop it.
2962                                         false
2963                                 } else {
2964                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2965                                                 node_id: chan.get_their_node_id(),
2966                                                 msg: chan.get_channel_reestablish(),
2967                                         });
2968                                         true
2969                                 }
2970                         } else { true }
2971                 });
2972                 //TODO: Also re-broadcast announcement_signatures
2973         }
2974
2975         fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2976                 let _ = self.total_consistency_lock.read().unwrap();
2977
2978                 if msg.channel_id == [0; 32] {
2979                         for chan in self.list_channels() {
2980                                 if chan.remote_network_id == *their_node_id {
2981                                         self.force_close_channel(&chan.channel_id);
2982                                 }
2983                         }
2984                 } else {
2985                         self.force_close_channel(&msg.channel_id);
2986                 }
2987         }
2988 }
2989
2990 const SERIALIZATION_VERSION: u8 = 1;
2991 const MIN_SERIALIZATION_VERSION: u8 = 1;
2992
2993 impl Writeable for PendingForwardHTLCInfo {
2994         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2995                 if let &Some(ref onion) = &self.onion_packet {
2996                         1u8.write(writer)?;
2997                         onion.write(writer)?;
2998                 } else {
2999                         0u8.write(writer)?;
3000                 }
3001                 self.incoming_shared_secret.write(writer)?;
3002                 self.payment_hash.write(writer)?;
3003                 self.short_channel_id.write(writer)?;
3004                 self.amt_to_forward.write(writer)?;
3005                 self.outgoing_cltv_value.write(writer)?;
3006                 Ok(())
3007         }
3008 }
3009
3010 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
3011         fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
3012                 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
3013                         0 => None,
3014                         1 => Some(msgs::OnionPacket::read(reader)?),
3015                         _ => return Err(DecodeError::InvalidValue),
3016                 };
3017                 Ok(PendingForwardHTLCInfo {
3018                         onion_packet,
3019                         incoming_shared_secret: Readable::read(reader)?,
3020                         payment_hash: Readable::read(reader)?,
3021                         short_channel_id: Readable::read(reader)?,
3022                         amt_to_forward: Readable::read(reader)?,
3023                         outgoing_cltv_value: Readable::read(reader)?,
3024                 })
3025         }
3026 }
3027
3028 impl Writeable for HTLCFailureMsg {
3029         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3030                 match self {
3031                         &HTLCFailureMsg::Relay(ref fail_msg) => {
3032                                 0u8.write(writer)?;
3033                                 fail_msg.write(writer)?;
3034                         },
3035                         &HTLCFailureMsg::Malformed(ref fail_msg) => {
3036                                 1u8.write(writer)?;
3037                                 fail_msg.write(writer)?;
3038                         }
3039                 }
3040                 Ok(())
3041         }
3042 }
3043
3044 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
3045         fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
3046                 match <u8 as Readable<R>>::read(reader)? {
3047                         0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
3048                         1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
3049                         _ => Err(DecodeError::InvalidValue),
3050                 }
3051         }
3052 }
3053
3054 impl Writeable for PendingHTLCStatus {
3055         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3056                 match self {
3057                         &PendingHTLCStatus::Forward(ref forward_info) => {
3058                                 0u8.write(writer)?;
3059                                 forward_info.write(writer)?;
3060                         },
3061                         &PendingHTLCStatus::Fail(ref fail_msg) => {
3062                                 1u8.write(writer)?;
3063                                 fail_msg.write(writer)?;
3064                         }
3065                 }
3066                 Ok(())
3067         }
3068 }
3069
3070 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
3071         fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
3072                 match <u8 as Readable<R>>::read(reader)? {
3073                         0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
3074                         1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
3075                         _ => Err(DecodeError::InvalidValue),
3076                 }
3077         }
3078 }
3079
3080 impl_writeable!(HTLCPreviousHopData, 0, {
3081         short_channel_id,
3082         htlc_id,
3083         incoming_packet_shared_secret
3084 });
3085
3086 impl Writeable for HTLCSource {
3087         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3088                 match self {
3089                         &HTLCSource::PreviousHopData(ref hop_data) => {
3090                                 0u8.write(writer)?;
3091                                 hop_data.write(writer)?;
3092                         },
3093                         &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
3094                                 1u8.write(writer)?;
3095                                 route.write(writer)?;
3096                                 session_priv.write(writer)?;
3097                                 first_hop_htlc_msat.write(writer)?;
3098                         }
3099                 }
3100                 Ok(())
3101         }
3102 }
3103
3104 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
3105         fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
3106                 match <u8 as Readable<R>>::read(reader)? {
3107                         0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
3108                         1 => Ok(HTLCSource::OutboundRoute {
3109                                 route: Readable::read(reader)?,
3110                                 session_priv: Readable::read(reader)?,
3111                                 first_hop_htlc_msat: Readable::read(reader)?,
3112                         }),
3113                         _ => Err(DecodeError::InvalidValue),
3114                 }
3115         }
3116 }
3117
3118 impl Writeable for HTLCFailReason {
3119         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3120                 match self {
3121                         &HTLCFailReason::ErrorPacket { ref err } => {
3122                                 0u8.write(writer)?;
3123                                 err.write(writer)?;
3124                         },
3125                         &HTLCFailReason::Reason { ref failure_code, ref data } => {
3126                                 1u8.write(writer)?;
3127                                 failure_code.write(writer)?;
3128                                 data.write(writer)?;
3129                         }
3130                 }
3131                 Ok(())
3132         }
3133 }
3134
3135 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
3136         fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
3137                 match <u8 as Readable<R>>::read(reader)? {
3138                         0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
3139                         1 => Ok(HTLCFailReason::Reason {
3140                                 failure_code: Readable::read(reader)?,
3141                                 data: Readable::read(reader)?,
3142                         }),
3143                         _ => Err(DecodeError::InvalidValue),
3144                 }
3145         }
3146 }
3147
3148 impl_writeable!(HTLCForwardInfo, 0, {
3149         prev_short_channel_id,
3150         prev_htlc_id,
3151         forward_info
3152 });
3153
3154 impl Writeable for ChannelManager {
3155         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
3156                 let _ = self.total_consistency_lock.write().unwrap();
3157
3158                 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
3159                 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
3160
3161                 self.genesis_hash.write(writer)?;
3162                 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
3163                 self.last_block_hash.lock().unwrap().write(writer)?;
3164
3165                 let channel_state = self.channel_state.lock().unwrap();
3166                 let mut unfunded_channels = 0;
3167                 for (_, channel) in channel_state.by_id.iter() {
3168                         if !channel.is_funding_initiated() {
3169                                 unfunded_channels += 1;
3170                         }
3171                 }
3172                 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
3173                 for (_, channel) in channel_state.by_id.iter() {
3174                         if channel.is_funding_initiated() {
3175                                 channel.write(writer)?;
3176                         }
3177                 }
3178
3179                 (channel_state.forward_htlcs.len() as u64).write(writer)?;
3180                 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
3181                         short_channel_id.write(writer)?;
3182                         (pending_forwards.len() as u64).write(writer)?;
3183                         for forward in pending_forwards {
3184                                 forward.write(writer)?;
3185                         }
3186                 }
3187
3188                 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
3189                 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
3190                         payment_hash.write(writer)?;
3191                         (previous_hops.len() as u64).write(writer)?;
3192                         for previous_hop in previous_hops {
3193                                 previous_hop.write(writer)?;
3194                         }
3195                 }
3196
3197                 Ok(())
3198         }
3199 }
3200
3201 /// Arguments for the creation of a ChannelManager that are not deserialized.
3202 ///
3203 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3204 /// is:
3205 /// 1) Deserialize all stored ChannelMonitors.
3206 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3207 ///    ChannelManager)>::read(reader, args).
3208 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
3209 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
3210 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
3211 ///    ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
3212 /// 4) Reconnect blocks on your ChannelMonitors.
3213 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
3214 /// 6) Disconnect/connect blocks on the ChannelManager.
3215 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
3216 ///    automatically as it does in ChannelManager::new()).
3217 pub struct ChannelManagerReadArgs<'a> {
3218         /// The keys provider which will give us relevant keys. Some keys will be loaded during
3219         /// deserialization.
3220         pub keys_manager: Arc<KeysInterface>,
3221
3222         /// The fee_estimator for use in the ChannelManager in the future.
3223         ///
3224         /// No calls to the FeeEstimator will be made during deserialization.
3225         pub fee_estimator: Arc<FeeEstimator>,
3226         /// The ManyChannelMonitor for use in the ChannelManager in the future.
3227         ///
3228         /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
3229         /// you have deserialized ChannelMonitors separately and will add them to your
3230         /// ManyChannelMonitor after deserializing this ChannelManager.
3231         pub monitor: Arc<ManyChannelMonitor>,
3232         /// The ChainWatchInterface for use in the ChannelManager in the future.
3233         ///
3234         /// No calls to the ChainWatchInterface will be made during deserialization.
3235         pub chain_monitor: Arc<ChainWatchInterface>,
3236         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3237         /// used to broadcast the latest local commitment transactions of channels which must be
3238         /// force-closed during deserialization.
3239         pub tx_broadcaster: Arc<BroadcasterInterface>,
3240         /// The Logger for use in the ChannelManager and which may be used to log information during
3241         /// deserialization.
3242         pub logger: Arc<Logger>,
3243         /// Default settings used for new channels. Any existing channels will continue to use the
3244         /// runtime settings which were stored when the ChannelManager was serialized.
3245         pub default_config: UserConfig,
3246
3247         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
3248         /// value.get_funding_txo() should be the key).
3249         ///
3250         /// If a monitor is inconsistent with the channel state during deserialization the channel will
3251         /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
3252         /// is true for missing channels as well. If there is a monitor missing for which we find
3253         /// channel data Err(DecodeError::InvalidValue) will be returned.
3254         ///
3255         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
3256         /// this struct.
3257         pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
3258 }
3259
3260 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
3261         fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
3262                 let _ver: u8 = Readable::read(reader)?;
3263                 let min_ver: u8 = Readable::read(reader)?;
3264                 if min_ver > SERIALIZATION_VERSION {
3265                         return Err(DecodeError::UnknownVersion);
3266                 }
3267
3268                 let genesis_hash: Sha256dHash = Readable::read(reader)?;
3269                 let latest_block_height: u32 = Readable::read(reader)?;
3270                 let last_block_hash: Sha256dHash = Readable::read(reader)?;
3271
3272                 let mut closed_channels = Vec::new();
3273
3274                 let channel_count: u64 = Readable::read(reader)?;
3275                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
3276                 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3277                 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
3278                 for _ in 0..channel_count {
3279                         let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
3280                         if channel.last_block_connected != last_block_hash {
3281                                 return Err(DecodeError::InvalidValue);
3282                         }
3283
3284                         let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
3285                         funding_txo_set.insert(funding_txo.clone());
3286                         if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
3287                                 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
3288                                                 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
3289                                                 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
3290                                         let mut force_close_res = channel.force_shutdown();
3291                                         force_close_res.0 = monitor.get_latest_local_commitment_txn();
3292                                         closed_channels.push(force_close_res);
3293                                 } else {
3294                                         if let Some(short_channel_id) = channel.get_short_channel_id() {
3295                                                 short_to_id.insert(short_channel_id, channel.channel_id());
3296                                         }
3297                                         by_id.insert(channel.channel_id(), channel);
3298                                 }
3299                         } else {
3300                                 return Err(DecodeError::InvalidValue);
3301                         }
3302                 }
3303
3304                 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
3305                         if !funding_txo_set.contains(funding_txo) {
3306                                 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
3307                         }
3308                 }
3309
3310                 let forward_htlcs_count: u64 = Readable::read(reader)?;
3311                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
3312                 for _ in 0..forward_htlcs_count {
3313                         let short_channel_id = Readable::read(reader)?;
3314                         let pending_forwards_count: u64 = Readable::read(reader)?;
3315                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
3316                         for _ in 0..pending_forwards_count {
3317                                 pending_forwards.push(Readable::read(reader)?);
3318                         }
3319                         forward_htlcs.insert(short_channel_id, pending_forwards);
3320                 }
3321
3322                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
3323                 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
3324                 for _ in 0..claimable_htlcs_count {
3325                         let payment_hash = Readable::read(reader)?;
3326                         let previous_hops_len: u64 = Readable::read(reader)?;
3327                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
3328                         for _ in 0..previous_hops_len {
3329                                 previous_hops.push(Readable::read(reader)?);
3330                         }
3331                         claimable_htlcs.insert(payment_hash, previous_hops);
3332                 }
3333
3334                 let channel_manager = ChannelManager {
3335                         genesis_hash,
3336                         fee_estimator: args.fee_estimator,
3337                         monitor: args.monitor,
3338                         chain_monitor: args.chain_monitor,
3339                         tx_broadcaster: args.tx_broadcaster,
3340
3341                         latest_block_height: AtomicUsize::new(latest_block_height as usize),
3342                         last_block_hash: Mutex::new(last_block_hash),
3343                         secp_ctx: Secp256k1::new(),
3344
3345                         channel_state: Mutex::new(ChannelHolder {
3346                                 by_id,
3347                                 short_to_id,
3348                                 next_forward: Instant::now(),
3349                                 forward_htlcs,
3350                                 claimable_htlcs,
3351                                 pending_msg_events: Vec::new(),
3352                         }),
3353                         our_network_key: args.keys_manager.get_node_secret(),
3354
3355                         pending_events: Mutex::new(Vec::new()),
3356                         total_consistency_lock: RwLock::new(()),
3357                         keys_manager: args.keys_manager,
3358                         logger: args.logger,
3359                         default_configuration: args.default_config,
3360                 };
3361
3362                 for close_res in closed_channels.drain(..) {
3363                         channel_manager.finish_force_close_channel(close_res);
3364                         //TODO: Broadcast channel update for closed channels, but only after we've made a
3365                         //connection or two.
3366                 }
3367
3368                 Ok((last_block_hash.clone(), channel_manager))
3369         }
3370 }
3371
3372 #[cfg(test)]
3373 mod tests {
3374         use chain::chaininterface;
3375         use chain::transaction::OutPoint;
3376         use chain::chaininterface::{ChainListener, ChainWatchInterface};
3377         use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
3378         use chain::keysinterface;
3379         use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3380         use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
3381         use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
3382         use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
3383         use ln::router::{Route, RouteHop, Router};
3384         use ln::msgs;
3385         use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
3386         use util::test_utils;
3387         use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
3388         use util::errors::APIError;
3389         use util::logger::Logger;
3390         use util::ser::{Writeable, Writer, ReadableArgs};
3391         use util::config::UserConfig;
3392
3393         use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
3394         use bitcoin::util::bip143;
3395         use bitcoin::util::address::Address;
3396         use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
3397         use bitcoin::blockdata::block::{Block, BlockHeader};
3398         use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
3399         use bitcoin::blockdata::script::{Builder, Script};
3400         use bitcoin::blockdata::opcodes;
3401         use bitcoin::blockdata::constants::genesis_block;
3402         use bitcoin::network::constants::Network;
3403
3404         use hex;
3405
3406         use secp256k1::{Secp256k1, Message};
3407         use secp256k1::key::{PublicKey,SecretKey};
3408
3409         use crypto::sha2::Sha256;
3410         use crypto::digest::Digest;
3411
3412         use rand::{thread_rng,Rng};
3413
3414         use std::cell::RefCell;
3415         use std::collections::{BTreeSet, HashMap, HashSet};
3416         use std::default::Default;
3417         use std::rc::Rc;
3418         use std::sync::{Arc, Mutex};
3419         use std::sync::atomic::Ordering;
3420         use std::time::Instant;
3421         use std::mem;
3422
3423         fn build_test_onion_keys() -> Vec<OnionKeys> {
3424                 // Keys from BOLT 4, used in both test vector tests
3425                 let secp_ctx = Secp256k1::new();
3426
3427                 let route = Route {
3428                         hops: vec!(
3429                                         RouteHop {
3430                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
3431                                                 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
3432                                         },
3433                                         RouteHop {
3434                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
3435                                                 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
3436                                         },
3437                                         RouteHop {
3438                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
3439                                                 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
3440                                         },
3441                                         RouteHop {
3442                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
3443                                                 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
3444                                         },
3445                                         RouteHop {
3446                                                 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
3447                                                 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
3448                                         },
3449                         ),
3450                 };
3451
3452                 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
3453
3454                 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
3455                 assert_eq!(onion_keys.len(), route.hops.len());
3456                 onion_keys
3457         }
3458
3459         #[test]
3460         fn onion_vectors() {
3461                 // Packet creation test vectors from BOLT 4
3462                 let onion_keys = build_test_onion_keys();
3463
3464                 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
3465                 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
3466                 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
3467                 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
3468                 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
3469
3470                 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
3471                 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
3472                 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
3473                 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
3474                 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
3475
3476                 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
3477                 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
3478                 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
3479                 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
3480                 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
3481
3482                 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
3483                 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
3484                 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
3485                 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
3486                 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
3487
3488                 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
3489                 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
3490                 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
3491                 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
3492                 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
3493
3494                 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
3495                 let payloads = vec!(
3496                         msgs::OnionHopData {
3497                                 realm: 0,
3498                                 data: msgs::OnionRealm0HopData {
3499                                         short_channel_id: 0,
3500                                         amt_to_forward: 0,
3501                                         outgoing_cltv_value: 0,
3502                                 },
3503                                 hmac: [0; 32],
3504                         },
3505                         msgs::OnionHopData {
3506                                 realm: 0,
3507                                 data: msgs::OnionRealm0HopData {
3508                                         short_channel_id: 0x0101010101010101,
3509                                         amt_to_forward: 0x0100000001,
3510                                         outgoing_cltv_value: 0,
3511                                 },
3512                                 hmac: [0; 32],
3513                         },
3514                         msgs::OnionHopData {
3515                                 realm: 0,
3516                                 data: msgs::OnionRealm0HopData {
3517                                         short_channel_id: 0x0202020202020202,
3518                                         amt_to_forward: 0x0200000002,
3519                                         outgoing_cltv_value: 0,
3520                                 },
3521                                 hmac: [0; 32],
3522                         },
3523                         msgs::OnionHopData {
3524                                 realm: 0,
3525                                 data: msgs::OnionRealm0HopData {
3526                                         short_channel_id: 0x0303030303030303,
3527                                         amt_to_forward: 0x0300000003,
3528                                         outgoing_cltv_value: 0,
3529                                 },
3530                                 hmac: [0; 32],
3531                         },
3532                         msgs::OnionHopData {
3533                                 realm: 0,
3534                                 data: msgs::OnionRealm0HopData {
3535                                         short_channel_id: 0x0404040404040404,
3536                                         amt_to_forward: 0x0400000004,
3537                                         outgoing_cltv_value: 0,
3538                                 },
3539                                 hmac: [0; 32],
3540                         },
3541                 );
3542
3543                 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
3544                 // Just check the final packet encoding, as it includes all the per-hop vectors in it
3545                 // anyway...
3546                 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
3547         }
3548
3549         #[test]
3550         fn test_failure_packet_onion() {
3551                 // Returning Errors test vectors from BOLT 4
3552
3553                 let onion_keys = build_test_onion_keys();
3554                 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret[..], 0x2002, &[0; 0]);
3555                 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
3556
3557                 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret[..], &onion_error.encode()[..]);
3558                 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
3559
3560                 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret[..], &onion_packet_1.data[..]);
3561                 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
3562
3563                 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret[..], &onion_packet_2.data[..]);
3564                 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
3565
3566                 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret[..], &onion_packet_3.data[..]);
3567                 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
3568
3569                 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret[..], &onion_packet_4.data[..]);
3570                 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
3571         }
3572
3573         fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
3574                 assert!(chain.does_match_tx(tx));
3575                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3576                 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
3577                 for i in 2..100 {
3578                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3579                         chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
3580                 }
3581         }
3582
3583         struct Node {
3584                 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
3585                 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
3586                 chan_monitor: Arc<test_utils::TestChannelMonitor>,
3587                 node: Arc<ChannelManager>,
3588                 router: Router,
3589                 node_seed: [u8; 32],
3590                 network_payment_count: Rc<RefCell<u8>>,
3591                 network_chan_count: Rc<RefCell<u32>>,
3592         }
3593         impl Drop for Node {
3594                 fn drop(&mut self) {
3595                         if !::std::thread::panicking() {
3596                                 // Check that we processed all pending events
3597                                 assert_eq!(self.node.get_and_clear_pending_msg_events().len(), 0);
3598                                 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
3599                                 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
3600                         }
3601                 }
3602         }
3603
3604         fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3605                 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
3606         }
3607
3608         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) {
3609                 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
3610                 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
3611                 (announcement, as_update, bs_update, channel_id, tx)
3612         }
3613
3614         macro_rules! get_revoke_commit_msgs {
3615                 ($node: expr, $node_id: expr) => {
3616                         {
3617                                 let events = $node.node.get_and_clear_pending_msg_events();
3618                                 assert_eq!(events.len(), 2);
3619                                 (match events[0] {
3620                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3621                                                 assert_eq!(*node_id, $node_id);
3622                                                 (*msg).clone()
3623                                         },
3624                                         _ => panic!("Unexpected event"),
3625                                 }, match events[1] {
3626                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3627                                                 assert_eq!(*node_id, $node_id);
3628                                                 assert!(updates.update_add_htlcs.is_empty());
3629                                                 assert!(updates.update_fulfill_htlcs.is_empty());
3630                                                 assert!(updates.update_fail_htlcs.is_empty());
3631                                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
3632                                                 assert!(updates.update_fee.is_none());
3633                                                 updates.commitment_signed.clone()
3634                                         },
3635                                         _ => panic!("Unexpected event"),
3636                                 })
3637                         }
3638                 }
3639         }
3640
3641         macro_rules! get_event_msg {
3642                 ($node: expr, $event_type: path, $node_id: expr) => {
3643                         {
3644                                 let events = $node.node.get_and_clear_pending_msg_events();
3645                                 assert_eq!(events.len(), 1);
3646                                 match events[0] {
3647                                         $event_type { ref node_id, ref msg } => {
3648                                                 assert_eq!(*node_id, $node_id);
3649                                                 (*msg).clone()
3650                                         },
3651                                         _ => panic!("Unexpected event"),
3652                                 }
3653                         }
3654                 }
3655         }
3656
3657         macro_rules! get_htlc_update_msgs {
3658                 ($node: expr, $node_id: expr) => {
3659                         {
3660                                 let events = $node.node.get_and_clear_pending_msg_events();
3661                                 assert_eq!(events.len(), 1);
3662                                 match events[0] {
3663                                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3664                                                 assert_eq!(*node_id, $node_id);
3665                                                 (*updates).clone()
3666                                         },
3667                                         _ => panic!("Unexpected event"),
3668                                 }
3669                         }
3670                 }
3671         }
3672
3673         macro_rules! get_feerate {
3674                 ($node: expr, $channel_id: expr) => {
3675                         {
3676                                 let chan_lock = $node.node.channel_state.lock().unwrap();
3677                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
3678                                 chan.get_feerate()
3679                         }
3680                 }
3681         }
3682
3683
3684         fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
3685                 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
3686                 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();
3687                 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();
3688
3689                 let chan_id = *node_a.network_chan_count.borrow();
3690                 let tx;
3691                 let funding_output;
3692
3693                 let events_2 = node_a.node.get_and_clear_pending_events();
3694                 assert_eq!(events_2.len(), 1);
3695                 match events_2[0] {
3696                         Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
3697                                 assert_eq!(*channel_value_satoshis, channel_value);
3698                                 assert_eq!(user_channel_id, 42);
3699
3700                                 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
3701                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3702                                 }]};
3703                                 funding_output = OutPoint::new(tx.txid(), 0);
3704
3705                                 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3706                                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3707                                 assert_eq!(added_monitors.len(), 1);
3708                                 assert_eq!(added_monitors[0].0, funding_output);
3709                                 added_monitors.clear();
3710                         },
3711                         _ => panic!("Unexpected event"),
3712                 }
3713
3714                 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();
3715                 {
3716                         let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3717                         assert_eq!(added_monitors.len(), 1);
3718                         assert_eq!(added_monitors[0].0, funding_output);
3719                         added_monitors.clear();
3720                 }
3721
3722                 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();
3723                 {
3724                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3725                         assert_eq!(added_monitors.len(), 1);
3726                         assert_eq!(added_monitors[0].0, funding_output);
3727                         added_monitors.clear();
3728                 }
3729
3730                 let events_4 = node_a.node.get_and_clear_pending_events();
3731                 assert_eq!(events_4.len(), 1);
3732                 match events_4[0] {
3733                         Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
3734                                 assert_eq!(user_channel_id, 42);
3735                                 assert_eq!(*funding_txo, funding_output);
3736                         },
3737                         _ => panic!("Unexpected event"),
3738                 };
3739
3740                 tx
3741         }
3742
3743         fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
3744                 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
3745                 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();
3746
3747                 let channel_id;
3748
3749                 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
3750                 let events_6 = node_a.node.get_and_clear_pending_msg_events();
3751                 assert_eq!(events_6.len(), 2);
3752                 ((match events_6[0] {
3753                         MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3754                                 channel_id = msg.channel_id.clone();
3755                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3756                                 msg.clone()
3757                         },
3758                         _ => panic!("Unexpected event"),
3759                 }, match events_6[1] {
3760                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3761                                 assert_eq!(*node_id, node_b.node.get_our_node_id());
3762                                 msg.clone()
3763                         },
3764                         _ => panic!("Unexpected event"),
3765                 }), channel_id)
3766         }
3767
3768         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) {
3769                 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
3770                 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
3771                 (msgs, chan_id, tx)
3772         }
3773
3774         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) {
3775                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
3776                 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
3777                 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
3778
3779                 let events_7 = node_b.node.get_and_clear_pending_msg_events();
3780                 assert_eq!(events_7.len(), 1);
3781                 let (announcement, bs_update) = match events_7[0] {
3782                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3783                                 (msg, update_msg)
3784                         },
3785                         _ => panic!("Unexpected event"),
3786                 };
3787
3788                 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3789                 let events_8 = node_a.node.get_and_clear_pending_msg_events();
3790                 assert_eq!(events_8.len(), 1);
3791                 let as_update = match events_8[0] {
3792                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3793                                 assert!(*announcement == *msg);
3794                                 update_msg
3795                         },
3796                         _ => panic!("Unexpected event"),
3797                 };
3798
3799                 *node_a.network_chan_count.borrow_mut() += 1;
3800
3801                 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
3802         }
3803
3804         fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
3805                 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
3806         }
3807
3808         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) {
3809                 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
3810                 for node in nodes {
3811                         assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
3812                         node.router.handle_channel_update(&chan_announcement.1).unwrap();
3813                         node.router.handle_channel_update(&chan_announcement.2).unwrap();
3814                 }
3815                 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
3816         }
3817
3818         macro_rules! check_spends {
3819                 ($tx: expr, $spends_tx: expr) => {
3820                         {
3821                                 let mut funding_tx_map = HashMap::new();
3822                                 let spends_tx = $spends_tx;
3823                                 funding_tx_map.insert(spends_tx.txid(), spends_tx);
3824                                 $tx.verify(&funding_tx_map).unwrap();
3825                         }
3826                 }
3827         }
3828
3829         macro_rules! get_closing_signed_broadcast {
3830                 ($node: expr, $dest_pubkey: expr) => {
3831                         {
3832                                 let events = $node.get_and_clear_pending_msg_events();
3833                                 assert!(events.len() == 1 || events.len() == 2);
3834                                 (match events[events.len() - 1] {
3835                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
3836                                                 assert_eq!(msg.contents.flags & 2, 2);
3837                                                 msg.clone()
3838                                         },
3839                                         _ => panic!("Unexpected event"),
3840                                 }, if events.len() == 2 {
3841                                         match events[0] {
3842                                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3843                                                         assert_eq!(*node_id, $dest_pubkey);
3844                                                         Some(msg.clone())
3845                                                 },
3846                                                 _ => panic!("Unexpected event"),
3847                                         }
3848                                 } else { None })
3849                         }
3850                 }
3851         }
3852
3853         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) {
3854                 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) };
3855                 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
3856                 let (tx_a, tx_b);
3857
3858                 node_a.close_channel(channel_id).unwrap();
3859                 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
3860
3861                 let events_1 = node_b.get_and_clear_pending_msg_events();
3862                 assert!(events_1.len() >= 1);
3863                 let shutdown_b = match events_1[0] {
3864                         MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
3865                                 assert_eq!(node_id, &node_a.get_our_node_id());
3866                                 msg.clone()
3867                         },
3868                         _ => panic!("Unexpected event"),
3869                 };
3870
3871                 let closing_signed_b = if !close_inbound_first {
3872                         assert_eq!(events_1.len(), 1);
3873                         None
3874                 } else {
3875                         Some(match events_1[1] {
3876                                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
3877                                         assert_eq!(node_id, &node_a.get_our_node_id());
3878                                         msg.clone()
3879                                 },
3880                                 _ => panic!("Unexpected event"),
3881                         })
3882                 };
3883
3884                 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
3885                 let (as_update, bs_update) = if close_inbound_first {
3886                         assert!(node_a.get_and_clear_pending_msg_events().is_empty());
3887                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3888                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3889                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3890                         let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3891
3892                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
3893                         let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3894                         assert!(none_b.is_none());
3895                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3896                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3897                         (as_update, bs_update)
3898                 } else {
3899                         let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
3900
3901                         node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
3902                         assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
3903                         tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
3904                         let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
3905
3906                         node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
3907                         let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
3908                         assert!(none_a.is_none());
3909                         assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
3910                         tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
3911                         (as_update, bs_update)
3912                 };
3913                 assert_eq!(tx_a, tx_b);
3914                 check_spends!(tx_a, funding_tx);
3915
3916                 (as_update, bs_update, tx_a)
3917         }
3918
3919         struct SendEvent {
3920                 node_id: PublicKey,
3921                 msgs: Vec<msgs::UpdateAddHTLC>,
3922                 commitment_msg: msgs::CommitmentSigned,
3923         }
3924         impl SendEvent {
3925                 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
3926                         assert!(updates.update_fulfill_htlcs.is_empty());
3927                         assert!(updates.update_fail_htlcs.is_empty());
3928                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3929                         assert!(updates.update_fee.is_none());
3930                         SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
3931                 }
3932
3933                 fn from_event(event: MessageSendEvent) -> SendEvent {
3934                         match event {
3935                                 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
3936                                 _ => panic!("Unexpected event type!"),
3937                         }
3938                 }
3939
3940                 fn from_node(node: &Node) -> SendEvent {
3941                         let mut events = node.node.get_and_clear_pending_msg_events();
3942                         assert_eq!(events.len(), 1);
3943                         SendEvent::from_event(events.pop().unwrap())
3944                 }
3945         }
3946
3947         macro_rules! check_added_monitors {
3948                 ($node: expr, $count: expr) => {
3949                         {
3950                                 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3951                                 assert_eq!(added_monitors.len(), $count);
3952                                 added_monitors.clear();
3953                         }
3954                 }
3955         }
3956
3957         macro_rules! commitment_signed_dance {
3958                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
3959                         {
3960                                 check_added_monitors!($node_a, 0);
3961                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3962                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
3963                                 check_added_monitors!($node_a, 1);
3964                                 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
3965                         }
3966                 };
3967                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
3968                         {
3969                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
3970                                 check_added_monitors!($node_b, 0);
3971                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3972                                 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3973                                 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
3974                                 check_added_monitors!($node_b, 1);
3975                                 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
3976                                 let (bs_revoke_and_ack, extra_msg_option) = {
3977                                         let events = $node_b.node.get_and_clear_pending_msg_events();
3978                                         assert!(events.len() <= 2);
3979                                         (match events[0] {
3980                                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3981                                                         assert_eq!(*node_id, $node_a.node.get_our_node_id());
3982                                                         (*msg).clone()
3983                                                 },
3984                                                 _ => panic!("Unexpected event"),
3985                                         }, events.get(1).map(|e| e.clone()))
3986                                 };
3987                                 check_added_monitors!($node_b, 1);
3988                                 if $fail_backwards {
3989                                         assert!($node_a.node.get_and_clear_pending_events().is_empty());
3990                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3991                                 }
3992                                 (extra_msg_option, bs_revoke_and_ack)
3993                         }
3994                 };
3995                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
3996                         {
3997                                 check_added_monitors!($node_a, 0);
3998                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
3999                                 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
4000                                 check_added_monitors!($node_a, 1);
4001                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4002                                 assert!(extra_msg_option.is_none());
4003                                 bs_revoke_and_ack
4004                         }
4005                 };
4006                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
4007                         {
4008                                 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
4009                                 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4010                                 {
4011                                         let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
4012                                         if $fail_backwards {
4013                                                 assert_eq!(added_monitors.len(), 2);
4014                                                 assert!(added_monitors[0].0 != added_monitors[1].0);
4015                                         } else {
4016                                                 assert_eq!(added_monitors.len(), 1);
4017                                         }
4018                                         added_monitors.clear();
4019                                 }
4020                                 extra_msg_option
4021                         }
4022                 };
4023                 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
4024                         {
4025                                 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
4026                         }
4027                 };
4028                 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
4029                         {
4030                                 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
4031                                 if $fail_backwards {
4032                                         let channel_state = $node_a.node.channel_state.lock().unwrap();
4033                                         assert_eq!(channel_state.pending_msg_events.len(), 1);
4034                                         if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
4035                                                 assert_ne!(*node_id, $node_b.node.get_our_node_id());
4036                                         } else { panic!("Unexpected event"); }
4037                                 } else {
4038                                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
4039                                 }
4040                         }
4041                 }
4042         }
4043
4044         macro_rules! get_payment_preimage_hash {
4045                 ($node: expr) => {
4046                         {
4047                                 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
4048                                 *$node.network_payment_count.borrow_mut() += 1;
4049                                 let mut payment_hash = PaymentHash([0; 32]);
4050                                 let mut sha = Sha256::new();
4051                                 sha.input(&payment_preimage.0[..]);
4052                                 sha.result(&mut payment_hash.0[..]);
4053                                 (payment_preimage, payment_hash)
4054                         }
4055                 }
4056         }
4057
4058         fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4059                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4060
4061                 let mut payment_event = {
4062                         origin_node.node.send_payment(route, our_payment_hash).unwrap();
4063                         check_added_monitors!(origin_node, 1);
4064
4065                         let mut events = origin_node.node.get_and_clear_pending_msg_events();
4066                         assert_eq!(events.len(), 1);
4067                         SendEvent::from_event(events.remove(0))
4068                 };
4069                 let mut prev_node = origin_node;
4070
4071                 for (idx, &node) in expected_route.iter().enumerate() {
4072                         assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
4073
4074                         node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4075                         check_added_monitors!(node, 0);
4076                         commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
4077
4078                         let events_1 = node.node.get_and_clear_pending_events();
4079                         assert_eq!(events_1.len(), 1);
4080                         match events_1[0] {
4081                                 Event::PendingHTLCsForwardable { .. } => { },
4082                                 _ => panic!("Unexpected event"),
4083                         };
4084
4085                         node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4086                         node.node.process_pending_htlc_forwards();
4087
4088                         if idx == expected_route.len() - 1 {
4089                                 let events_2 = node.node.get_and_clear_pending_events();
4090                                 assert_eq!(events_2.len(), 1);
4091                                 match events_2[0] {
4092                                         Event::PaymentReceived { ref payment_hash, amt } => {
4093                                                 assert_eq!(our_payment_hash, *payment_hash);
4094                                                 assert_eq!(amt, recv_value);
4095                                         },
4096                                         _ => panic!("Unexpected event"),
4097                                 }
4098                         } else {
4099                                 let mut events_2 = node.node.get_and_clear_pending_msg_events();
4100                                 assert_eq!(events_2.len(), 1);
4101                                 check_added_monitors!(node, 1);
4102                                 payment_event = SendEvent::from_event(events_2.remove(0));
4103                                 assert_eq!(payment_event.msgs.len(), 1);
4104                         }
4105
4106                         prev_node = node;
4107                 }
4108
4109                 (our_payment_preimage, our_payment_hash)
4110         }
4111
4112         fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
4113                 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
4114                 check_added_monitors!(expected_route.last().unwrap(), 1);
4115
4116                 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
4117                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4118                 macro_rules! get_next_msgs {
4119                         ($node: expr) => {
4120                                 {
4121                                         let events = $node.node.get_and_clear_pending_msg_events();
4122                                         assert_eq!(events.len(), 1);
4123                                         match events[0] {
4124                                                 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 } } => {
4125                                                         assert!(update_add_htlcs.is_empty());
4126                                                         assert_eq!(update_fulfill_htlcs.len(), 1);
4127                                                         assert!(update_fail_htlcs.is_empty());
4128                                                         assert!(update_fail_malformed_htlcs.is_empty());
4129                                                         assert!(update_fee.is_none());
4130                                                         expected_next_node = node_id.clone();
4131                                                         Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
4132                                                 },
4133                                                 _ => panic!("Unexpected event"),
4134                                         }
4135                                 }
4136                         }
4137                 }
4138
4139                 macro_rules! last_update_fulfill_dance {
4140                         ($node: expr, $prev_node: expr) => {
4141                                 {
4142                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4143                                         check_added_monitors!($node, 0);
4144                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4145                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4146                                 }
4147                         }
4148                 }
4149                 macro_rules! mid_update_fulfill_dance {
4150                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
4151                                 {
4152                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4153                                         check_added_monitors!($node, 1);
4154                                         let new_next_msgs = if $new_msgs {
4155                                                 get_next_msgs!($node)
4156                                         } else {
4157                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
4158                                                 None
4159                                         };
4160                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
4161                                         next_msgs = new_next_msgs;
4162                                 }
4163                         }
4164                 }
4165
4166                 let mut prev_node = expected_route.last().unwrap();
4167                 for (idx, node) in expected_route.iter().rev().enumerate() {
4168                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4169                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
4170                         if next_msgs.is_some() {
4171                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
4172                         } else if update_next_msgs {
4173                                 next_msgs = get_next_msgs!(node);
4174                         } else {
4175                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
4176                         }
4177                         if !skip_last && idx == expected_route.len() - 1 {
4178                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4179                         }
4180
4181                         prev_node = node;
4182                 }
4183
4184                 if !skip_last {
4185                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
4186                         let events = origin_node.node.get_and_clear_pending_events();
4187                         assert_eq!(events.len(), 1);
4188                         match events[0] {
4189                                 Event::PaymentSent { payment_preimage } => {
4190                                         assert_eq!(payment_preimage, our_payment_preimage);
4191                                 },
4192                                 _ => panic!("Unexpected event"),
4193                         }
4194                 }
4195         }
4196
4197         fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
4198                 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
4199         }
4200
4201         const TEST_FINAL_CLTV: u32 = 32;
4202
4203         fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
4204                 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();
4205                 assert_eq!(route.hops.len(), expected_route.len());
4206                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4207                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4208                 }
4209
4210                 send_along_route(origin_node, route, expected_route, recv_value)
4211         }
4212
4213         fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
4214                 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();
4215                 assert_eq!(route.hops.len(), expected_route.len());
4216                 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
4217                         assert_eq!(hop.pubkey, node.node.get_our_node_id());
4218                 }
4219
4220                 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
4221
4222                 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
4223                 match err {
4224                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
4225                         _ => panic!("Unknown error variants"),
4226                 };
4227         }
4228
4229         fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
4230                 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
4231                 claim_payment(&origin, expected_route, our_payment_preimage);
4232         }
4233
4234         fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
4235                 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
4236                 check_added_monitors!(expected_route.last().unwrap(), 1);
4237
4238                 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
4239                 macro_rules! update_fail_dance {
4240                         ($node: expr, $prev_node: expr, $last_node: expr) => {
4241                                 {
4242                                         $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
4243                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
4244                                 }
4245                         }
4246                 }
4247
4248                 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
4249                 let mut prev_node = expected_route.last().unwrap();
4250                 for (idx, node) in expected_route.iter().rev().enumerate() {
4251                         assert_eq!(expected_next_node, node.node.get_our_node_id());
4252                         if next_msgs.is_some() {
4253                                 // We may be the "last node" for the purpose of the commitment dance if we're
4254                                 // skipping the last node (implying it is disconnected) and we're the
4255                                 // second-to-last node!
4256                                 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
4257                         }
4258
4259                         let events = node.node.get_and_clear_pending_msg_events();
4260                         if !skip_last || idx != expected_route.len() - 1 {
4261                                 assert_eq!(events.len(), 1);
4262                                 match events[0] {
4263                                         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 } } => {
4264                                                 assert!(update_add_htlcs.is_empty());
4265                                                 assert!(update_fulfill_htlcs.is_empty());
4266                                                 assert_eq!(update_fail_htlcs.len(), 1);
4267                                                 assert!(update_fail_malformed_htlcs.is_empty());
4268                                                 assert!(update_fee.is_none());
4269                                                 expected_next_node = node_id.clone();
4270                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
4271                                         },
4272                                         _ => panic!("Unexpected event"),
4273                                 }
4274                         } else {
4275                                 assert!(events.is_empty());
4276                         }
4277                         if !skip_last && idx == expected_route.len() - 1 {
4278                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
4279                         }
4280
4281                         prev_node = node;
4282                 }
4283
4284                 if !skip_last {
4285                         update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
4286
4287                         let events = origin_node.node.get_and_clear_pending_events();
4288                         assert_eq!(events.len(), 1);
4289                         match events[0] {
4290                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
4291                                         assert_eq!(payment_hash, our_payment_hash);
4292                                         assert!(rejected_by_dest);
4293                                 },
4294                                 _ => panic!("Unexpected event"),
4295                         }
4296                 }
4297         }
4298
4299         fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
4300                 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
4301         }
4302
4303         fn create_network(node_count: usize) -> Vec<Node> {
4304                 let mut nodes = Vec::new();
4305                 let mut rng = thread_rng();
4306                 let secp_ctx = Secp256k1::new();
4307
4308                 let chan_count = Rc::new(RefCell::new(0));
4309                 let payment_count = Rc::new(RefCell::new(0));
4310
4311                 for i in 0..node_count {
4312                         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
4313                         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
4314                         let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
4315                         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
4316                         let mut seed = [0; 32];
4317                         rng.fill_bytes(&mut seed);
4318                         let keys_manager = Arc::new(keysinterface::KeysManager::new(&seed, Network::Testnet, Arc::clone(&logger)));
4319                         let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
4320                         let mut config = UserConfig::new();
4321                         config.channel_options.announced_channel = true;
4322                         config.channel_limits.force_announced_channel_preference = false;
4323                         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();
4324                         let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
4325                         nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, node_seed: seed,
4326                                 network_payment_count: payment_count.clone(),
4327                                 network_chan_count: chan_count.clone(),
4328                         });
4329                 }
4330
4331                 nodes
4332         }
4333
4334         #[test]
4335         fn test_async_inbound_update_fee() {
4336                 let mut nodes = create_network(2);
4337                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4338                 let channel_id = chan.2;
4339
4340                 // balancing
4341                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4342
4343                 // A                                        B
4344                 // update_fee                            ->
4345                 // send (1) commitment_signed            -.
4346                 //                                       <- update_add_htlc/commitment_signed
4347                 // send (2) RAA (awaiting remote revoke) -.
4348                 // (1) commitment_signed is delivered    ->
4349                 //                                       .- send (3) RAA (awaiting remote revoke)
4350                 // (2) RAA is delivered                  ->
4351                 //                                       .- send (4) commitment_signed
4352                 //                                       <- (3) RAA is delivered
4353                 // send (5) commitment_signed            -.
4354                 //                                       <- (4) commitment_signed is delivered
4355                 // send (6) RAA                          -.
4356                 // (5) commitment_signed is delivered    ->
4357                 //                                       <- RAA
4358                 // (6) RAA is delivered                  ->
4359
4360                 // First nodes[0] generates an update_fee
4361                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4362                 check_added_monitors!(nodes[0], 1);
4363
4364                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4365                 assert_eq!(events_0.len(), 1);
4366                 let (update_msg, commitment_signed) = match events_0[0] { // (1)
4367                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4368                                 (update_fee.as_ref(), commitment_signed)
4369                         },
4370                         _ => panic!("Unexpected event"),
4371                 };
4372
4373                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4374
4375                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4376                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4377                 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();
4378                 check_added_monitors!(nodes[1], 1);
4379
4380                 let payment_event = {
4381                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4382                         assert_eq!(events_1.len(), 1);
4383                         SendEvent::from_event(events_1.remove(0))
4384                 };
4385                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4386                 assert_eq!(payment_event.msgs.len(), 1);
4387
4388                 // ...now when the messages get delivered everyone should be happy
4389                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4390                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4391                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4392                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4393                 check_added_monitors!(nodes[0], 1);
4394
4395                 // deliver(1), generate (3):
4396                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4397                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4398                 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
4399                 check_added_monitors!(nodes[1], 1);
4400
4401                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
4402                 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4403                 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
4404                 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
4405                 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
4406                 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
4407                 assert!(bs_update.update_fee.is_none()); // (4)
4408                 check_added_monitors!(nodes[1], 1);
4409
4410                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
4411                 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4412                 assert!(as_update.update_add_htlcs.is_empty()); // (5)
4413                 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
4414                 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
4415                 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
4416                 assert!(as_update.update_fee.is_none()); // (5)
4417                 check_added_monitors!(nodes[0], 1);
4418
4419                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
4420                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4421                 // only (6) so get_event_msg's assert(len == 1) passes
4422                 check_added_monitors!(nodes[0], 1);
4423
4424                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
4425                 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4426                 check_added_monitors!(nodes[1], 1);
4427
4428                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4429                 check_added_monitors!(nodes[0], 1);
4430
4431                 let events_2 = nodes[0].node.get_and_clear_pending_events();
4432                 assert_eq!(events_2.len(), 1);
4433                 match events_2[0] {
4434                         Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
4435                         _ => panic!("Unexpected event"),
4436                 }
4437
4438                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
4439                 check_added_monitors!(nodes[1], 1);
4440         }
4441
4442         #[test]
4443         fn test_update_fee_unordered_raa() {
4444                 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
4445                 // crash in an earlier version of the update_fee patch)
4446                 let mut nodes = create_network(2);
4447                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4448                 let channel_id = chan.2;
4449
4450                 // balancing
4451                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4452
4453                 // First nodes[0] generates an update_fee
4454                 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
4455                 check_added_monitors!(nodes[0], 1);
4456
4457                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4458                 assert_eq!(events_0.len(), 1);
4459                 let update_msg = match events_0[0] { // (1)
4460                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
4461                                 update_fee.as_ref()
4462                         },
4463                         _ => panic!("Unexpected event"),
4464                 };
4465
4466                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4467
4468                 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
4469                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4470                 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();
4471                 check_added_monitors!(nodes[1], 1);
4472
4473                 let payment_event = {
4474                         let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
4475                         assert_eq!(events_1.len(), 1);
4476                         SendEvent::from_event(events_1.remove(0))
4477                 };
4478                 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
4479                 assert_eq!(payment_event.msgs.len(), 1);
4480
4481                 // ...now when the messages get delivered everyone should be happy
4482                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4483                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
4484                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4485                 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
4486                 check_added_monitors!(nodes[0], 1);
4487
4488                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
4489                 check_added_monitors!(nodes[1], 1);
4490
4491                 // We can't continue, sadly, because our (1) now has a bogus signature
4492         }
4493
4494         #[test]
4495         fn test_multi_flight_update_fee() {
4496                 let nodes = create_network(2);
4497                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4498                 let channel_id = chan.2;
4499
4500                 // A                                        B
4501                 // update_fee/commitment_signed          ->
4502                 //                                       .- send (1) RAA and (2) commitment_signed
4503                 // update_fee (never committed)          ->
4504                 // (3) update_fee                        ->
4505                 // We have to manually generate the above update_fee, it is allowed by the protocol but we
4506                 // don't track which updates correspond to which revoke_and_ack responses so we're in
4507                 // AwaitingRAA mode and will not generate the update_fee yet.
4508                 //                                       <- (1) RAA delivered
4509                 // (3) is generated and send (4) CS      -.
4510                 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
4511                 // know the per_commitment_point to use for it.
4512                 //                                       <- (2) commitment_signed delivered
4513                 // revoke_and_ack                        ->
4514                 //                                          B should send no response here
4515                 // (4) commitment_signed delivered       ->
4516                 //                                       <- RAA/commitment_signed delivered
4517                 // revoke_and_ack                        ->
4518
4519                 // First nodes[0] generates an update_fee
4520                 let initial_feerate = get_feerate!(nodes[0], channel_id);
4521                 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
4522                 check_added_monitors!(nodes[0], 1);
4523
4524                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4525                 assert_eq!(events_0.len(), 1);
4526                 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
4527                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
4528                                 (update_fee.as_ref().unwrap(), commitment_signed)
4529                         },
4530                         _ => panic!("Unexpected event"),
4531                 };
4532
4533                 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
4534                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
4535                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
4536                 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4537                 check_added_monitors!(nodes[1], 1);
4538
4539                 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
4540                 // transaction:
4541                 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
4542                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4543                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4544
4545                 // Create the (3) update_fee message that nodes[0] will generate before it does...
4546                 let mut update_msg_2 = msgs::UpdateFee {
4547                         channel_id: update_msg_1.channel_id.clone(),
4548                         feerate_per_kw: (initial_feerate + 30) as u32,
4549                 };
4550
4551                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4552
4553                 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
4554                 // Deliver (3)
4555                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
4556
4557                 // Deliver (1), generating (3) and (4)
4558                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
4559                 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4560                 check_added_monitors!(nodes[0], 1);
4561                 assert!(as_second_update.update_add_htlcs.is_empty());
4562                 assert!(as_second_update.update_fulfill_htlcs.is_empty());
4563                 assert!(as_second_update.update_fail_htlcs.is_empty());
4564                 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
4565                 // Check that the update_fee newly generated matches what we delivered:
4566                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
4567                 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
4568
4569                 // Deliver (2) commitment_signed
4570                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
4571                 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4572                 check_added_monitors!(nodes[0], 1);
4573                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4574
4575                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
4576                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4577                 check_added_monitors!(nodes[1], 1);
4578
4579                 // Delever (4)
4580                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
4581                 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4582                 check_added_monitors!(nodes[1], 1);
4583
4584                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
4585                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4586                 check_added_monitors!(nodes[0], 1);
4587
4588                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
4589                 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4590                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4591                 check_added_monitors!(nodes[0], 1);
4592
4593                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
4594                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4595                 check_added_monitors!(nodes[1], 1);
4596         }
4597
4598         #[test]
4599         fn test_update_fee_vanilla() {
4600                 let nodes = create_network(2);
4601                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4602                 let channel_id = chan.2;
4603
4604                 let feerate = get_feerate!(nodes[0], channel_id);
4605                 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
4606                 check_added_monitors!(nodes[0], 1);
4607
4608                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4609                 assert_eq!(events_0.len(), 1);
4610                 let (update_msg, commitment_signed) = match events_0[0] {
4611                                 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 } } => {
4612                                 (update_fee.as_ref(), commitment_signed)
4613                         },
4614                         _ => panic!("Unexpected event"),
4615                 };
4616                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4617
4618                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4619                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4620                 check_added_monitors!(nodes[1], 1);
4621
4622                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4623                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4624                 check_added_monitors!(nodes[0], 1);
4625
4626                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4627                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4628                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4629                 check_added_monitors!(nodes[0], 1);
4630
4631                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4632                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4633                 check_added_monitors!(nodes[1], 1);
4634         }
4635
4636         #[test]
4637         fn test_update_fee_that_funder_cannot_afford() {
4638                 let nodes = create_network(2);
4639                 let channel_value = 1888;
4640                 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
4641                 let channel_id = chan.2;
4642
4643                 let feerate = 260;
4644                 nodes[0].node.update_fee(channel_id, feerate).unwrap();
4645                 check_added_monitors!(nodes[0], 1);
4646                 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4647
4648                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
4649
4650                 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
4651
4652                 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
4653                 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
4654                 {
4655                         let chan_lock = nodes[1].node.channel_state.lock().unwrap();
4656                         let chan = chan_lock.by_id.get(&channel_id).unwrap();
4657
4658                         //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
4659                         let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
4660                         let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
4661                         let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
4662                         actual_fee = channel_value - actual_fee;
4663                         assert_eq!(total_fee, actual_fee);
4664                 } //drop the mutex
4665
4666                 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
4667                 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
4668                 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
4669                 check_added_monitors!(nodes[0], 1);
4670
4671                 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4672
4673                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
4674
4675                 //While producing the commitment_signed response after handling a received update_fee request the
4676                 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
4677                 //Should produce and error.
4678                 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
4679
4680                 assert!(match err.err {
4681                         "Funding remote cannot afford proposed new fee" => true,
4682                         _ => false,
4683                 });
4684
4685                 //clear the message we could not handle
4686                 nodes[1].node.get_and_clear_pending_msg_events();
4687         }
4688
4689         #[test]
4690         fn test_update_fee_with_fundee_update_add_htlc() {
4691                 let mut nodes = create_network(2);
4692                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4693                 let channel_id = chan.2;
4694
4695                 // balancing
4696                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4697
4698                 let feerate = get_feerate!(nodes[0], channel_id);
4699                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4700                 check_added_monitors!(nodes[0], 1);
4701
4702                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4703                 assert_eq!(events_0.len(), 1);
4704                 let (update_msg, commitment_signed) = match events_0[0] {
4705                                 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 } } => {
4706                                 (update_fee.as_ref(), commitment_signed)
4707                         },
4708                         _ => panic!("Unexpected event"),
4709                 };
4710                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4711                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4712                 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4713                 check_added_monitors!(nodes[1], 1);
4714
4715                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
4716
4717                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
4718
4719                 // nothing happens since node[1] is in AwaitingRemoteRevoke
4720                 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
4721                 {
4722                         let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
4723                         assert_eq!(added_monitors.len(), 0);
4724                         added_monitors.clear();
4725                 }
4726                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4727                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4728                 // node[1] has nothing to do
4729
4730                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4731                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4732                 check_added_monitors!(nodes[0], 1);
4733
4734                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
4735                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4736                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4737                 check_added_monitors!(nodes[0], 1);
4738                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4739                 check_added_monitors!(nodes[1], 1);
4740                 // AwaitingRemoteRevoke ends here
4741
4742                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4743                 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
4744                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
4745                 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
4746                 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
4747                 assert_eq!(commitment_update.update_fee.is_none(), true);
4748
4749                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
4750                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4751                 check_added_monitors!(nodes[0], 1);
4752                 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4753
4754                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
4755                 check_added_monitors!(nodes[1], 1);
4756                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4757
4758                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
4759                 check_added_monitors!(nodes[1], 1);
4760                 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4761                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4762
4763                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
4764                 check_added_monitors!(nodes[0], 1);
4765                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4766
4767                 let events = nodes[0].node.get_and_clear_pending_events();
4768                 assert_eq!(events.len(), 1);
4769                 match events[0] {
4770                         Event::PendingHTLCsForwardable { .. } => { },
4771                         _ => panic!("Unexpected event"),
4772                 };
4773                 nodes[0].node.channel_state.lock().unwrap().next_forward = Instant::now();
4774                 nodes[0].node.process_pending_htlc_forwards();
4775
4776                 let events = nodes[0].node.get_and_clear_pending_events();
4777                 assert_eq!(events.len(), 1);
4778                 match events[0] {
4779                         Event::PaymentReceived { .. } => { },
4780                         _ => panic!("Unexpected event"),
4781                 };
4782
4783                 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
4784
4785                 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
4786                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
4787                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4788         }
4789
4790         #[test]
4791         fn test_update_fee() {
4792                 let nodes = create_network(2);
4793                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4794                 let channel_id = chan.2;
4795
4796                 // A                                        B
4797                 // (1) update_fee/commitment_signed      ->
4798                 //                                       <- (2) revoke_and_ack
4799                 //                                       .- send (3) commitment_signed
4800                 // (4) update_fee/commitment_signed      ->
4801                 //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
4802                 //                                       <- (3) commitment_signed delivered
4803                 // send (6) revoke_and_ack               -.
4804                 //                                       <- (5) deliver revoke_and_ack
4805                 // (6) deliver revoke_and_ack            ->
4806                 //                                       .- send (7) commitment_signed in response to (4)
4807                 //                                       <- (7) deliver commitment_signed
4808                 // revoke_and_ack                        ->
4809
4810                 // Create and deliver (1)...
4811                 let feerate = get_feerate!(nodes[0], channel_id);
4812                 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
4813                 check_added_monitors!(nodes[0], 1);
4814
4815                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4816                 assert_eq!(events_0.len(), 1);
4817                 let (update_msg, commitment_signed) = match events_0[0] {
4818                                 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 } } => {
4819                                 (update_fee.as_ref(), commitment_signed)
4820                         },
4821                         _ => panic!("Unexpected event"),
4822                 };
4823                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4824
4825                 // Generate (2) and (3):
4826                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4827                 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4828                 check_added_monitors!(nodes[1], 1);
4829
4830                 // Deliver (2):
4831                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4832                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4833                 check_added_monitors!(nodes[0], 1);
4834
4835                 // Create and deliver (4)...
4836                 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
4837                 check_added_monitors!(nodes[0], 1);
4838                 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
4839                 assert_eq!(events_0.len(), 1);
4840                 let (update_msg, commitment_signed) = match events_0[0] {
4841                                 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 } } => {
4842                                 (update_fee.as_ref(), commitment_signed)
4843                         },
4844                         _ => panic!("Unexpected event"),
4845                 };
4846
4847                 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
4848                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
4849                 check_added_monitors!(nodes[1], 1);
4850                 // ... creating (5)
4851                 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4852                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4853
4854                 // Handle (3), creating (6):
4855                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
4856                 check_added_monitors!(nodes[0], 1);
4857                 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4858                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4859
4860                 // Deliver (5):
4861                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
4862                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4863                 check_added_monitors!(nodes[0], 1);
4864
4865                 // Deliver (6), creating (7):
4866                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
4867                 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4868                 assert!(commitment_update.update_add_htlcs.is_empty());
4869                 assert!(commitment_update.update_fulfill_htlcs.is_empty());
4870                 assert!(commitment_update.update_fail_htlcs.is_empty());
4871                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
4872                 assert!(commitment_update.update_fee.is_none());
4873                 check_added_monitors!(nodes[1], 1);
4874
4875                 // Deliver (7)
4876                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
4877                 check_added_monitors!(nodes[0], 1);
4878                 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4879                 // No commitment_signed so get_event_msg's assert(len == 1) passes
4880
4881                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
4882                 check_added_monitors!(nodes[1], 1);
4883                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4884
4885                 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
4886                 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
4887                 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
4888         }
4889
4890         #[test]
4891         fn pre_funding_lock_shutdown_test() {
4892                 // Test sending a shutdown prior to funding_locked after funding generation
4893                 let nodes = create_network(2);
4894                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
4895                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4896                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4897                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
4898
4899                 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
4900                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4901                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4902                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4903                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4904
4905                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4906                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4907                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4908                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4909                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4910                 assert!(node_0_none.is_none());
4911
4912                 assert!(nodes[0].node.list_channels().is_empty());
4913                 assert!(nodes[1].node.list_channels().is_empty());
4914         }
4915
4916         #[test]
4917         fn updates_shutdown_wait() {
4918                 // Test sending a shutdown with outstanding updates pending
4919                 let mut nodes = create_network(3);
4920                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4921                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4922                 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4923                 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4924
4925                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
4926
4927                 nodes[0].node.close_channel(&chan_1.2).unwrap();
4928                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
4929                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
4930                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
4931                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
4932
4933                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4934                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4935
4936                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4937                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
4938                 else { panic!("New sends should fail!") };
4939                 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
4940                 else { panic!("New sends should fail!") };
4941
4942                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4943                 check_added_monitors!(nodes[2], 1);
4944                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4945                 assert!(updates.update_add_htlcs.is_empty());
4946                 assert!(updates.update_fail_htlcs.is_empty());
4947                 assert!(updates.update_fail_malformed_htlcs.is_empty());
4948                 assert!(updates.update_fee.is_none());
4949                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4950                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4951                 check_added_monitors!(nodes[1], 1);
4952                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4953                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4954
4955                 assert!(updates_2.update_add_htlcs.is_empty());
4956                 assert!(updates_2.update_fail_htlcs.is_empty());
4957                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
4958                 assert!(updates_2.update_fee.is_none());
4959                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
4960                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
4961                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
4962
4963                 let events = nodes[0].node.get_and_clear_pending_events();
4964                 assert_eq!(events.len(), 1);
4965                 match events[0] {
4966                         Event::PaymentSent { ref payment_preimage } => {
4967                                 assert_eq!(our_payment_preimage, *payment_preimage);
4968                         },
4969                         _ => panic!("Unexpected event"),
4970                 }
4971
4972                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
4973                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
4974                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
4975                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
4976                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
4977                 assert!(node_0_none.is_none());
4978
4979                 assert!(nodes[0].node.list_channels().is_empty());
4980
4981                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4982                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
4983                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
4984                 assert!(nodes[1].node.list_channels().is_empty());
4985                 assert!(nodes[2].node.list_channels().is_empty());
4986         }
4987
4988         #[test]
4989         fn htlc_fail_async_shutdown() {
4990                 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
4991                 let mut nodes = create_network(3);
4992                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4993                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4994
4995                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4996                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4997                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4998                 check_added_monitors!(nodes[0], 1);
4999                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5000                 assert_eq!(updates.update_add_htlcs.len(), 1);
5001                 assert!(updates.update_fulfill_htlcs.is_empty());
5002                 assert!(updates.update_fail_htlcs.is_empty());
5003                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5004                 assert!(updates.update_fee.is_none());
5005
5006                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5007                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5008                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5009                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5010
5011                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5012                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5013                 check_added_monitors!(nodes[1], 1);
5014                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5015                 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
5016
5017                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5018                 assert!(updates_2.update_add_htlcs.is_empty());
5019                 assert!(updates_2.update_fulfill_htlcs.is_empty());
5020                 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
5021                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5022                 assert!(updates_2.update_fee.is_none());
5023
5024                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
5025                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5026
5027                 let events = nodes[0].node.get_and_clear_pending_events();
5028                 assert_eq!(events.len(), 1);
5029                 match events[0] {
5030                         Event::PaymentFailed { ref payment_hash, ref rejected_by_dest } => {
5031                                 assert_eq!(our_payment_hash, *payment_hash);
5032                                 assert!(!rejected_by_dest);
5033                         },
5034                         _ => panic!("Unexpected event"),
5035                 }
5036
5037                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5038                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5039                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5040                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5041                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5042                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5043                 assert!(node_0_none.is_none());
5044
5045                 assert!(nodes[0].node.list_channels().is_empty());
5046
5047                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5048                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5049                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5050                 assert!(nodes[1].node.list_channels().is_empty());
5051                 assert!(nodes[2].node.list_channels().is_empty());
5052         }
5053
5054         fn do_test_shutdown_rebroadcast(recv_count: u8) {
5055                 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
5056                 // messages delivered prior to disconnect
5057                 let nodes = create_network(3);
5058                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5059                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5060
5061                 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
5062
5063                 nodes[1].node.close_channel(&chan_1.2).unwrap();
5064                 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5065                 if recv_count > 0 {
5066                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
5067                         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5068                         if recv_count > 1 {
5069                                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
5070                         }
5071                 }
5072
5073                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5074                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5075
5076                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5077                 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5078                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5079                 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5080
5081                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
5082                 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5083                 assert!(node_1_shutdown == node_1_2nd_shutdown);
5084
5085                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
5086                 let node_0_2nd_shutdown = if recv_count > 0 {
5087                         let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5088                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5089                         node_0_2nd_shutdown
5090                 } else {
5091                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5092                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
5093                         get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
5094                 };
5095                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
5096
5097                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5098                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5099
5100                 assert!(nodes[2].node.claim_funds(our_payment_preimage));
5101                 check_added_monitors!(nodes[2], 1);
5102                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5103                 assert!(updates.update_add_htlcs.is_empty());
5104                 assert!(updates.update_fail_htlcs.is_empty());
5105                 assert!(updates.update_fail_malformed_htlcs.is_empty());
5106                 assert!(updates.update_fee.is_none());
5107                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5108                 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5109                 check_added_monitors!(nodes[1], 1);
5110                 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5111                 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
5112
5113                 assert!(updates_2.update_add_htlcs.is_empty());
5114                 assert!(updates_2.update_fail_htlcs.is_empty());
5115                 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
5116                 assert!(updates_2.update_fee.is_none());
5117                 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
5118                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
5119                 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
5120
5121                 let events = nodes[0].node.get_and_clear_pending_events();
5122                 assert_eq!(events.len(), 1);
5123                 match events[0] {
5124                         Event::PaymentSent { ref payment_preimage } => {
5125                                 assert_eq!(our_payment_preimage, *payment_preimage);
5126                         },
5127                         _ => panic!("Unexpected event"),
5128                 }
5129
5130                 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5131                 if recv_count > 0 {
5132                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
5133                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5134                         assert!(node_1_closing_signed.is_some());
5135                 }
5136
5137                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5138                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5139
5140                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5141                 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
5142                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5143                 if recv_count == 0 {
5144                         // If all closing_signeds weren't delivered we can just resume where we left off...
5145                         let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5146
5147                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
5148                         let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5149                         assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
5150
5151                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
5152                         let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5153                         assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
5154
5155                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
5156                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5157
5158                         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
5159                         let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
5160                         assert!(node_0_closing_signed == node_0_2nd_closing_signed);
5161
5162                         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
5163                         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
5164                         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
5165                         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
5166                         assert!(node_0_none.is_none());
5167                 } else {
5168                         // If one node, however, received + responded with an identical closing_signed we end
5169                         // up erroring and node[0] will try to broadcast its own latest commitment transaction.
5170                         // There isn't really anything better we can do simply, but in the future we might
5171                         // explore storing a set of recently-closed channels that got disconnected during
5172                         // closing_signed and avoiding broadcasting local commitment txn for some timeout to
5173                         // give our counterparty enough time to (potentially) broadcast a cooperative closing
5174                         // transaction.
5175                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5176
5177                         if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
5178                                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
5179                                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
5180                                 let msgs::ErrorMessage {ref channel_id, ..} = msg;
5181                                 assert_eq!(*channel_id, chan_1.2);
5182                         } else { panic!("Needed SendErrorMessage close"); }
5183
5184                         // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
5185                         // checks it, but in this case nodes[0] didn't ever get a chance to receive a
5186                         // closing_signed so we do it ourselves
5187                         let events = nodes[0].node.get_and_clear_pending_msg_events();
5188                         assert_eq!(events.len(), 1);
5189                         match events[0] {
5190                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5191                                         assert_eq!(msg.contents.flags & 2, 2);
5192                                 },
5193                                 _ => panic!("Unexpected event"),
5194                         }
5195                 }
5196
5197                 assert!(nodes[0].node.list_channels().is_empty());
5198
5199                 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
5200                 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
5201                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
5202                 assert!(nodes[1].node.list_channels().is_empty());
5203                 assert!(nodes[2].node.list_channels().is_empty());
5204         }
5205
5206         #[test]
5207         fn test_shutdown_rebroadcast() {
5208                 do_test_shutdown_rebroadcast(0);
5209                 do_test_shutdown_rebroadcast(1);
5210                 do_test_shutdown_rebroadcast(2);
5211         }
5212
5213         #[test]
5214         fn fake_network_test() {
5215                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5216                 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
5217                 let nodes = create_network(4);
5218
5219                 // Create some initial channels
5220                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5221                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5222                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5223
5224                 // Rebalance the network a bit by relaying one payment through all the channels...
5225                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5226                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5227                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5228                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
5229
5230                 // Send some more payments
5231                 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
5232                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
5233                 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
5234
5235                 // Test failure packets
5236                 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
5237                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
5238
5239                 // Add a new channel that skips 3
5240                 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
5241
5242                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
5243                 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
5244                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5245                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5246                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5247                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5248                 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
5249
5250                 // Do some rebalance loop payments, simultaneously
5251                 let mut hops = Vec::with_capacity(3);
5252                 hops.push(RouteHop {
5253                         pubkey: nodes[2].node.get_our_node_id(),
5254                         short_channel_id: chan_2.0.contents.short_channel_id,
5255                         fee_msat: 0,
5256                         cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
5257                 });
5258                 hops.push(RouteHop {
5259                         pubkey: nodes[3].node.get_our_node_id(),
5260                         short_channel_id: chan_3.0.contents.short_channel_id,
5261                         fee_msat: 0,
5262                         cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
5263                 });
5264                 hops.push(RouteHop {
5265                         pubkey: nodes[1].node.get_our_node_id(),
5266                         short_channel_id: chan_4.0.contents.short_channel_id,
5267                         fee_msat: 1000000,
5268                         cltv_expiry_delta: TEST_FINAL_CLTV,
5269                 });
5270                 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;
5271                 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;
5272                 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
5273
5274                 let mut hops = Vec::with_capacity(3);
5275                 hops.push(RouteHop {
5276                         pubkey: nodes[3].node.get_our_node_id(),
5277                         short_channel_id: chan_4.0.contents.short_channel_id,
5278                         fee_msat: 0,
5279                         cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
5280                 });
5281                 hops.push(RouteHop {
5282                         pubkey: nodes[2].node.get_our_node_id(),
5283                         short_channel_id: chan_3.0.contents.short_channel_id,
5284                         fee_msat: 0,
5285                         cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
5286                 });
5287                 hops.push(RouteHop {
5288                         pubkey: nodes[1].node.get_our_node_id(),
5289                         short_channel_id: chan_2.0.contents.short_channel_id,
5290                         fee_msat: 1000000,
5291                         cltv_expiry_delta: TEST_FINAL_CLTV,
5292                 });
5293                 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;
5294                 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;
5295                 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
5296
5297                 // Claim the rebalances...
5298                 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
5299                 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
5300
5301                 // Add a duplicate new channel from 2 to 4
5302                 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
5303
5304                 // Send some payments across both channels
5305                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5306                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5307                 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
5308
5309                 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
5310
5311                 //TODO: Test that routes work again here as we've been notified that the channel is full
5312
5313                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
5314                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
5315                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
5316
5317                 // Close down the channels...
5318                 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
5319                 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
5320                 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
5321                 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
5322                 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
5323         }
5324
5325         #[test]
5326         fn duplicate_htlc_test() {
5327                 // Test that we accept duplicate payment_hash HTLCs across the network and that
5328                 // claiming/failing them are all separate and don't effect each other
5329                 let mut nodes = create_network(6);
5330
5331                 // Create some initial channels to route via 3 to 4/5 from 0/1/2
5332                 create_announced_chan_between_nodes(&nodes, 0, 3);
5333                 create_announced_chan_between_nodes(&nodes, 1, 3);
5334                 create_announced_chan_between_nodes(&nodes, 2, 3);
5335                 create_announced_chan_between_nodes(&nodes, 3, 4);
5336                 create_announced_chan_between_nodes(&nodes, 3, 5);
5337
5338                 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
5339
5340                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5341                 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
5342
5343                 *nodes[0].network_payment_count.borrow_mut() -= 1;
5344                 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
5345
5346                 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
5347                 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
5348                 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
5349         }
5350
5351         #[derive(PartialEq)]
5352         enum HTLCType { NONE, TIMEOUT, SUCCESS }
5353         /// Tests that the given node has broadcast transactions for the given Channel
5354         ///
5355         /// First checks that the latest local commitment tx has been broadcast, unless an explicit
5356         /// commitment_tx is provided, which may be used to test that a remote commitment tx was
5357         /// broadcast and the revoked outputs were claimed.
5358         ///
5359         /// Next tests that there is (or is not) a transaction that spends the commitment transaction
5360         /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
5361         ///
5362         /// All broadcast transactions must be accounted for in one of the above three types of we'll
5363         /// also fail.
5364         fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
5365                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5366                 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
5367
5368                 let mut res = Vec::with_capacity(2);
5369                 node_txn.retain(|tx| {
5370                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
5371                                 check_spends!(tx, chan.3.clone());
5372                                 if commitment_tx.is_none() {
5373                                         res.push(tx.clone());
5374                                 }
5375                                 false
5376                         } else { true }
5377                 });
5378                 if let Some(explicit_tx) = commitment_tx {
5379                         res.push(explicit_tx.clone());
5380                 }
5381
5382                 assert_eq!(res.len(), 1);
5383
5384                 if has_htlc_tx != HTLCType::NONE {
5385                         node_txn.retain(|tx| {
5386                                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
5387                                         check_spends!(tx, res[0].clone());
5388                                         if has_htlc_tx == HTLCType::TIMEOUT {
5389                                                 assert!(tx.lock_time != 0);
5390                                         } else {
5391                                                 assert!(tx.lock_time == 0);
5392                                         }
5393                                         res.push(tx.clone());
5394                                         false
5395                                 } else { true }
5396                         });
5397                         assert!(res.len() == 2 || res.len() == 3);
5398                         if res.len() == 3 {
5399                                 assert_eq!(res[1], res[2]);
5400                         }
5401                 }
5402
5403                 assert!(node_txn.is_empty());
5404                 res
5405         }
5406
5407         /// Tests that the given node has broadcast a claim transaction against the provided revoked
5408         /// HTLC transaction.
5409         fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
5410                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5411                 assert_eq!(node_txn.len(), 1);
5412                 node_txn.retain(|tx| {
5413                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
5414                                 check_spends!(tx, revoked_tx.clone());
5415                                 false
5416                         } else { true }
5417                 });
5418                 assert!(node_txn.is_empty());
5419         }
5420
5421         fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
5422                 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
5423
5424                 assert!(node_txn.len() >= 1);
5425                 assert_eq!(node_txn[0].input.len(), 1);
5426                 let mut found_prev = false;
5427
5428                 for tx in prev_txn {
5429                         if node_txn[0].input[0].previous_output.txid == tx.txid() {
5430                                 check_spends!(node_txn[0], tx.clone());
5431                                 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
5432                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
5433
5434                                 found_prev = true;
5435                                 break;
5436                         }
5437                 }
5438                 assert!(found_prev);
5439
5440                 let mut res = Vec::new();
5441                 mem::swap(&mut *node_txn, &mut res);
5442                 res
5443         }
5444
5445         fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
5446                 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
5447                 assert_eq!(events_1.len(), 1);
5448                 let as_update = match events_1[0] {
5449                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5450                                 msg.clone()
5451                         },
5452                         _ => panic!("Unexpected event"),
5453                 };
5454
5455                 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
5456                 assert_eq!(events_2.len(), 1);
5457                 let bs_update = match events_2[0] {
5458                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5459                                 msg.clone()
5460                         },
5461                         _ => panic!("Unexpected event"),
5462                 };
5463
5464                 for node in nodes {
5465                         node.router.handle_channel_update(&as_update).unwrap();
5466                         node.router.handle_channel_update(&bs_update).unwrap();
5467                 }
5468         }
5469
5470         macro_rules! expect_pending_htlcs_forwardable {
5471                 ($node: expr) => {{
5472                         let events = $node.node.get_and_clear_pending_events();
5473                         assert_eq!(events.len(), 1);
5474                         match events[0] {
5475                                 Event::PendingHTLCsForwardable { .. } => { },
5476                                 _ => panic!("Unexpected event"),
5477                         };
5478                         $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
5479                         $node.node.process_pending_htlc_forwards();
5480                 }}
5481         }
5482
5483         fn do_channel_reserve_test(test_recv: bool) {
5484                 use util::rng;
5485                 use std::sync::atomic::Ordering;
5486                 use ln::msgs::HandleError;
5487
5488                 macro_rules! get_channel_value_stat {
5489                         ($node: expr, $channel_id: expr) => {{
5490                                 let chan_lock = $node.node.channel_state.lock().unwrap();
5491                                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
5492                                 chan.get_value_stat()
5493                         }}
5494                 }
5495
5496                 let mut nodes = create_network(3);
5497                 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
5498                 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
5499
5500                 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
5501                 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
5502
5503                 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
5504                 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
5505
5506                 macro_rules! get_route_and_payment_hash {
5507                         ($recv_value: expr) => {{
5508                                 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
5509                                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5510                                 (route, payment_hash, payment_preimage)
5511                         }}
5512                 };
5513
5514                 macro_rules! expect_forward {
5515                         ($node: expr) => {{
5516                                 let mut events = $node.node.get_and_clear_pending_msg_events();
5517                                 assert_eq!(events.len(), 1);
5518                                 check_added_monitors!($node, 1);
5519                                 let payment_event = SendEvent::from_event(events.remove(0));
5520                                 payment_event
5521                         }}
5522                 }
5523
5524                 macro_rules! expect_payment_received {
5525                         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
5526                                 let events = $node.node.get_and_clear_pending_events();
5527                                 assert_eq!(events.len(), 1);
5528                                 match events[0] {
5529                                         Event::PaymentReceived { ref payment_hash, amt } => {
5530                                                 assert_eq!($expected_payment_hash, *payment_hash);
5531                                                 assert_eq!($expected_recv_value, amt);
5532                                         },
5533                                         _ => panic!("Unexpected event"),
5534                                 }
5535                         }
5536                 };
5537
5538                 let feemsat = 239; // somehow we know?
5539                 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
5540
5541                 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
5542
5543                 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
5544                 {
5545                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
5546                         assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
5547                         let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
5548                         match err {
5549                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
5550                                 _ => panic!("Unknown error variants"),
5551                         }
5552                 }
5553
5554                 let mut htlc_id = 0;
5555                 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
5556                 // nodes[0]'s wealth
5557                 loop {
5558                         let amt_msat = recv_value_0 + total_fee_msat;
5559                         if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
5560                                 break;
5561                         }
5562                         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
5563                         htlc_id += 1;
5564
5565                         let (stat01_, stat11_, stat12_, stat22_) = (
5566                                 get_channel_value_stat!(nodes[0], chan_1.2),
5567                                 get_channel_value_stat!(nodes[1], chan_1.2),
5568                                 get_channel_value_stat!(nodes[1], chan_2.2),
5569                                 get_channel_value_stat!(nodes[2], chan_2.2),
5570                         );
5571
5572                         assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
5573                         assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
5574                         assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
5575                         assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
5576                         stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
5577                 }
5578
5579                 {
5580                         let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
5581                         // attempt to get channel_reserve violation
5582                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
5583                         let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
5584                         match err {
5585                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5586                                 _ => panic!("Unknown error variants"),
5587                         }
5588                 }
5589
5590                 // adding pending output
5591                 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
5592                 let amt_msat_1 = recv_value_1 + total_fee_msat;
5593
5594                 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
5595                 let payment_event_1 = {
5596                         nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
5597                         check_added_monitors!(nodes[0], 1);
5598
5599                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5600                         assert_eq!(events.len(), 1);
5601                         SendEvent::from_event(events.remove(0))
5602                 };
5603                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
5604
5605                 // channel reserve test with htlc pending output > 0
5606                 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
5607                 {
5608                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5609                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5610                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5611                                 _ => panic!("Unknown error variants"),
5612                         }
5613                 }
5614
5615                 {
5616                         // test channel_reserve test on nodes[1] side
5617                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
5618
5619                         // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
5620                         let secp_ctx = Secp256k1::new();
5621                         let session_priv = SecretKey::from_slice(&secp_ctx, &{
5622                                 let mut session_key = [0; 32];
5623                                 rng::fill_bytes(&mut session_key);
5624                                 session_key
5625                         }).expect("RNG is bad!");
5626
5627                         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5628                         let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
5629                         let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height).unwrap();
5630                         let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5631                         let msg = msgs::UpdateAddHTLC {
5632                                 channel_id: chan_1.2,
5633                                 htlc_id,
5634                                 amount_msat: htlc_msat,
5635                                 payment_hash: our_payment_hash,
5636                                 cltv_expiry: htlc_cltv,
5637                                 onion_routing_packet: onion_packet,
5638                         };
5639
5640                         if test_recv {
5641                                 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
5642                                 match err {
5643                                         HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
5644                                 }
5645                                 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
5646                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5647                                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5648                                 let channel_close_broadcast = nodes[1].node.get_and_clear_pending_msg_events();
5649                                 assert_eq!(channel_close_broadcast.len(), 1);
5650                                 match channel_close_broadcast[0] {
5651                                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
5652                                                 assert_eq!(msg.contents.flags & 2, 2);
5653                                         },
5654                                         _ => panic!("Unexpected event"),
5655                                 }
5656                                 return;
5657                         }
5658                 }
5659
5660                 // split the rest to test holding cell
5661                 let recv_value_21 = recv_value_2/2;
5662                 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
5663                 {
5664                         let stat = get_channel_value_stat!(nodes[0], chan_1.2);
5665                         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);
5666                 }
5667
5668                 // now see if they go through on both sides
5669                 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
5670                 // but this will stuck in the holding cell
5671                 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
5672                 check_added_monitors!(nodes[0], 0);
5673                 let events = nodes[0].node.get_and_clear_pending_events();
5674                 assert_eq!(events.len(), 0);
5675
5676                 // test with outbound holding cell amount > 0
5677                 {
5678                         let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
5679                         match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
5680                                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
5681                                 _ => panic!("Unknown error variants"),
5682                         }
5683                 }
5684
5685                 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
5686                 // this will also stuck in the holding cell
5687                 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
5688                 check_added_monitors!(nodes[0], 0);
5689                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
5690                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5691
5692                 // flush the pending htlc
5693                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
5694                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5695                 check_added_monitors!(nodes[1], 1);
5696
5697                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
5698                 check_added_monitors!(nodes[0], 1);
5699                 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5700
5701                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
5702                 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
5703                 // No commitment_signed so get_event_msg's assert(len == 1) passes
5704                 check_added_monitors!(nodes[0], 1);
5705
5706                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
5707                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5708                 check_added_monitors!(nodes[1], 1);
5709
5710                 expect_pending_htlcs_forwardable!(nodes[1]);
5711
5712                 let ref payment_event_11 = expect_forward!(nodes[1]);
5713                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
5714                 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
5715
5716                 expect_pending_htlcs_forwardable!(nodes[2]);
5717                 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
5718
5719                 // flush the htlcs in the holding cell
5720                 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
5721                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
5722                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
5723                 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
5724                 expect_pending_htlcs_forwardable!(nodes[1]);
5725
5726                 let ref payment_event_3 = expect_forward!(nodes[1]);
5727                 assert_eq!(payment_event_3.msgs.len(), 2);
5728                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
5729                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
5730
5731                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
5732                 expect_pending_htlcs_forwardable!(nodes[2]);
5733
5734                 let events = nodes[2].node.get_and_clear_pending_events();
5735                 assert_eq!(events.len(), 2);
5736                 match events[0] {
5737                         Event::PaymentReceived { ref payment_hash, amt } => {
5738                                 assert_eq!(our_payment_hash_21, *payment_hash);
5739                                 assert_eq!(recv_value_21, amt);
5740                         },
5741                         _ => panic!("Unexpected event"),
5742                 }
5743                 match events[1] {
5744                         Event::PaymentReceived { ref payment_hash, amt } => {
5745                                 assert_eq!(our_payment_hash_22, *payment_hash);
5746                                 assert_eq!(recv_value_22, amt);
5747                         },
5748                         _ => panic!("Unexpected event"),
5749                 }
5750
5751                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
5752                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
5753                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
5754
5755                 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);
5756                 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
5757                 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
5758                 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
5759
5760                 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
5761                 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
5762         }
5763
5764         #[test]
5765         fn channel_reserve_test() {
5766                 do_channel_reserve_test(false);
5767                 do_channel_reserve_test(true);
5768         }
5769
5770         #[test]
5771         fn channel_monitor_network_test() {
5772                 // Simple test which builds a network of ChannelManagers, connects them to each other, and
5773                 // tests that ChannelMonitor is able to recover from various states.
5774                 let nodes = create_network(5);
5775
5776                 // Create some initial channels
5777                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5778                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5779                 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5780                 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5781
5782                 // Rebalance the network a bit by relaying one payment through all the channels...
5783                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5784                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5785                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5786                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
5787
5788                 // Simple case with no pending HTLCs:
5789                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
5790                 {
5791                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
5792                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5793                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5794                         test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
5795                 }
5796                 get_announce_close_broadcast_events(&nodes, 0, 1);
5797                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5798                 assert_eq!(nodes[1].node.list_channels().len(), 1);
5799
5800                 // One pending HTLC is discarded by the force-close:
5801                 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
5802
5803                 // Simple case of one pending HTLC to HTLC-Timeout
5804                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
5805                 {
5806                         let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
5807                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5808                         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
5809                         test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
5810                 }
5811                 get_announce_close_broadcast_events(&nodes, 1, 2);
5812                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5813                 assert_eq!(nodes[2].node.list_channels().len(), 1);
5814
5815                 macro_rules! claim_funds {
5816                         ($node: expr, $prev_node: expr, $preimage: expr) => {
5817                                 {
5818                                         assert!($node.node.claim_funds($preimage));
5819                                         check_added_monitors!($node, 1);
5820
5821                                         let events = $node.node.get_and_clear_pending_msg_events();
5822                                         assert_eq!(events.len(), 1);
5823                                         match events[0] {
5824                                                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
5825                                                         assert!(update_add_htlcs.is_empty());
5826                                                         assert!(update_fail_htlcs.is_empty());
5827                                                         assert_eq!(*node_id, $prev_node.node.get_our_node_id());
5828                                                 },
5829                                                 _ => panic!("Unexpected event"),
5830                                         };
5831                                 }
5832                         }
5833                 }
5834
5835                 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
5836                 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
5837                 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
5838                 {
5839                         let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
5840
5841                         // Claim the payment on nodes[3], giving it knowledge of the preimage
5842                         claim_funds!(nodes[3], nodes[2], payment_preimage_1);
5843
5844                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5845                         nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
5846
5847                         check_preimage_claim(&nodes[3], &node_txn);
5848                 }
5849                 get_announce_close_broadcast_events(&nodes, 2, 3);
5850                 assert_eq!(nodes[2].node.list_channels().len(), 0);
5851                 assert_eq!(nodes[3].node.list_channels().len(), 1);
5852
5853                 { // Cheat and reset nodes[4]'s height to 1
5854                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
5856                 }
5857
5858                 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
5859                 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
5860                 // One pending HTLC to time out:
5861                 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
5862                 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
5863                 // buffer space).
5864
5865                 {
5866                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5867                         nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5868                         for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
5869                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5870                                 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5871                         }
5872
5873                         let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
5874
5875                         // Claim the payment on nodes[4], giving it knowledge of the preimage
5876                         claim_funds!(nodes[4], nodes[3], payment_preimage_2);
5877
5878                         header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5879                         nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
5880                         for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
5881                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5882                                 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
5883                         }
5884
5885                         test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
5886
5887                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5888                         nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
5889
5890                         check_preimage_claim(&nodes[4], &node_txn);
5891                 }
5892                 get_announce_close_broadcast_events(&nodes, 3, 4);
5893                 assert_eq!(nodes[3].node.list_channels().len(), 0);
5894                 assert_eq!(nodes[4].node.list_channels().len(), 0);
5895         }
5896
5897         #[test]
5898         fn test_justice_tx() {
5899                 // Test justice txn built on revoked HTLC-Success tx, against both sides
5900
5901                 let nodes = create_network(2);
5902                 // Create some new channels:
5903                 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
5904
5905                 // A pending HTLC which will be revoked:
5906                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5907                 // Get the will-be-revoked local txn from nodes[0]
5908                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5909                 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
5910                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5911                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
5912                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
5913                 assert_eq!(revoked_local_txn[1].input.len(), 1);
5914                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
5915                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
5916                 // Revoke the old state
5917                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5918
5919                 {
5920                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5921                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5922                         {
5923                                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5924                                 assert_eq!(node_txn.len(), 3);
5925                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5926                                 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
5927
5928                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5929                                 node_txn.swap_remove(0);
5930                         }
5931                         test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
5932
5933                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5934                         let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
5935                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5936                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5937                         test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
5938                 }
5939                 get_announce_close_broadcast_events(&nodes, 0, 1);
5940
5941                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5942                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5943
5944                 // We test justice_tx build by A on B's revoked HTLC-Success tx
5945                 // Create some new channels:
5946                 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
5947
5948                 // A pending HTLC which will be revoked:
5949                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5950                 // Get the will-be-revoked local txn from B
5951                 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5952                 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
5953                 assert_eq!(revoked_local_txn[0].input.len(), 1);
5954                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
5955                 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
5956                 // Revoke the old state
5957                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
5958                 {
5959                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5960                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5961                         {
5962                                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5963                                 assert_eq!(node_txn.len(), 3);
5964                                 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
5965                                 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
5966
5967                                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5968                                 node_txn.swap_remove(0);
5969                         }
5970                         test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
5971
5972                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5973                         let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
5974                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5975                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
5976                         test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
5977                 }
5978                 get_announce_close_broadcast_events(&nodes, 0, 1);
5979                 assert_eq!(nodes[0].node.list_channels().len(), 0);
5980                 assert_eq!(nodes[1].node.list_channels().len(), 0);
5981         }
5982
5983         #[test]
5984         fn revoked_output_claim() {
5985                 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
5986                 // transaction is broadcast by its counterparty
5987                 let nodes = create_network(2);
5988                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5989                 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
5990                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5991                 assert_eq!(revoked_local_txn.len(), 1);
5992                 // Only output is the full channel value back to nodes[0]:
5993                 assert_eq!(revoked_local_txn[0].output.len(), 1);
5994                 // Send a payment through, updating everyone's latest commitment txn
5995                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
5996
5997                 // Inform nodes[1] that nodes[0] broadcast a stale tx
5998                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5999                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6000                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6001                 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
6002
6003                 assert_eq!(node_txn[0], node_txn[2]);
6004
6005                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6006                 check_spends!(node_txn[1], chan_1.3.clone());
6007
6008                 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
6009                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6010                 get_announce_close_broadcast_events(&nodes, 0, 1);
6011         }
6012
6013         #[test]
6014         fn claim_htlc_outputs_shared_tx() {
6015                 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
6016                 let nodes = create_network(2);
6017
6018                 // Create some new channel:
6019                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6020
6021                 // Rebalance the network to generate htlc in the two directions
6022                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6023                 // 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
6024                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6025                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6026
6027                 // Get the will-be-revoked local txn from node[0]
6028                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6029                 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
6030                 assert_eq!(revoked_local_txn[0].input.len(), 1);
6031                 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
6032                 assert_eq!(revoked_local_txn[1].input.len(), 1);
6033                 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
6034                 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
6035                 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
6036
6037                 //Revoke the old state
6038                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6039
6040                 {
6041                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6042                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6043                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6044
6045                         let events = nodes[1].node.get_and_clear_pending_events();
6046                         assert_eq!(events.len(), 1);
6047                         match events[0] {
6048                                 Event::PaymentFailed { payment_hash, .. } => {
6049                                         assert_eq!(payment_hash, payment_hash_2);
6050                                 },
6051                                 _ => panic!("Unexpected event"),
6052                         }
6053
6054                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6055                         assert_eq!(node_txn.len(), 4);
6056
6057                         assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
6058                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
6059
6060                         assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
6061
6062                         let mut witness_lens = BTreeSet::new();
6063                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6064                         witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
6065                         witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
6066                         assert_eq!(witness_lens.len(), 3);
6067                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6068                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6069                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6070
6071                         // Next nodes[1] broadcasts its current local tx state:
6072                         assert_eq!(node_txn[1].input.len(), 1);
6073                         assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
6074
6075                         assert_eq!(node_txn[2].input.len(), 1);
6076                         let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
6077                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6078                         assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
6079                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6080                         assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
6081                 }
6082                 get_announce_close_broadcast_events(&nodes, 0, 1);
6083                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6084                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6085         }
6086
6087         #[test]
6088         fn claim_htlc_outputs_single_tx() {
6089                 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
6090                 let nodes = create_network(2);
6091
6092                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6093
6094                 // Rebalance the network to generate htlc in the two directions
6095                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6096                 // 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
6097                 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
6098                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6099                 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
6100
6101                 // Get the will-be-revoked local txn from node[0]
6102                 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6103
6104                 //Revoke the old state
6105                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
6106
6107                 {
6108                         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6109                         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6110                         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
6111
6112                         let events = nodes[1].node.get_and_clear_pending_events();
6113                         assert_eq!(events.len(), 1);
6114                         match events[0] {
6115                                 Event::PaymentFailed { payment_hash, .. } => {
6116                                         assert_eq!(payment_hash, payment_hash_2);
6117                                 },
6118                                 _ => panic!("Unexpected event"),
6119                         }
6120
6121                         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6122                         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)
6123
6124                         assert_eq!(node_txn[0], node_txn[7]);
6125                         assert_eq!(node_txn[1], node_txn[8]);
6126                         assert_eq!(node_txn[2], node_txn[9]);
6127                         assert_eq!(node_txn[3], node_txn[10]);
6128                         assert_eq!(node_txn[4], node_txn[11]);
6129                         assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
6130                         assert_eq!(node_txn[4], node_txn[6]);
6131
6132                         assert_eq!(node_txn[0].input.len(), 1);
6133                         assert_eq!(node_txn[1].input.len(), 1);
6134                         assert_eq!(node_txn[2].input.len(), 1);
6135
6136                         let mut revoked_tx_map = HashMap::new();
6137                         revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
6138                         node_txn[0].verify(&revoked_tx_map).unwrap();
6139                         node_txn[1].verify(&revoked_tx_map).unwrap();
6140                         node_txn[2].verify(&revoked_tx_map).unwrap();
6141
6142                         let mut witness_lens = BTreeSet::new();
6143                         witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
6144                         witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
6145                         witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
6146                         assert_eq!(witness_lens.len(), 3);
6147                         assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
6148                         assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
6149                         assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
6150
6151                         assert_eq!(node_txn[3].input.len(), 1);
6152                         check_spends!(node_txn[3], chan_1.3.clone());
6153
6154                         assert_eq!(node_txn[4].input.len(), 1);
6155                         let witness_script = node_txn[4].input[0].witness.last().unwrap();
6156                         assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
6157                         assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
6158                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
6159                         assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
6160                 }
6161                 get_announce_close_broadcast_events(&nodes, 0, 1);
6162                 assert_eq!(nodes[0].node.list_channels().len(), 0);
6163                 assert_eq!(nodes[1].node.list_channels().len(), 0);
6164         }
6165
6166         #[test]
6167         fn test_htlc_on_chain_success() {
6168                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6169                 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
6170                 // broadcasting the right event to other nodes in payment path.
6171                 // A --------------------> B ----------------------> C (preimage)
6172                 // First, C should claim the HTLC output via HTLC-Success when its own latest local
6173                 // commitment transaction was broadcast.
6174                 // Then, B should learn the preimage from said transactions, attempting to claim backwards
6175                 // towards B.
6176                 // B should be able to claim via preimage if A then broadcasts its local tx.
6177                 // Finally, when A sees B's latest local commitment transaction it should be able to claim
6178                 // the HTLC output via the preimage it learned (which, once confirmed should generate a
6179                 // PaymentSent event).
6180
6181                 let nodes = create_network(3);
6182
6183                 // Create some initial channels
6184                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6185                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6186
6187                 // Rebalance the network a bit by relaying one payment through all the channels...
6188                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6189                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6190
6191                 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6192                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6193
6194                 // Broadcast legit commitment tx from C on B's chain
6195                 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
6196                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6197                 assert_eq!(commitment_tx.len(), 1);
6198                 check_spends!(commitment_tx[0], chan_2.3.clone());
6199                 nodes[2].node.claim_funds(our_payment_preimage);
6200                 check_added_monitors!(nodes[2], 1);
6201                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6202                 assert!(updates.update_add_htlcs.is_empty());
6203                 assert!(updates.update_fail_htlcs.is_empty());
6204                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6205                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
6206
6207                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6208                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6209                 assert_eq!(events.len(), 1);
6210                 match events[0] {
6211                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6212                         _ => panic!("Unexpected event"),
6213                 }
6214                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
6215                 assert_eq!(node_txn.len(), 3);
6216                 assert_eq!(node_txn[1], commitment_tx[0]);
6217                 assert_eq!(node_txn[0], node_txn[2]);
6218                 check_spends!(node_txn[0], commitment_tx[0].clone());
6219                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6220                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6221                 assert_eq!(node_txn[0].lock_time, 0);
6222
6223                 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
6224                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
6225                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6226                 {
6227                         let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
6228                         assert_eq!(added_monitors.len(), 1);
6229                         assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
6230                         added_monitors.clear();
6231                 }
6232                 assert_eq!(events.len(), 2);
6233                 match events[0] {
6234                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6235                         _ => panic!("Unexpected event"),
6236                 }
6237                 match events[1] {
6238                         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, .. } } => {
6239                                 assert!(update_add_htlcs.is_empty());
6240                                 assert!(update_fail_htlcs.is_empty());
6241                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6242                                 assert!(update_fail_malformed_htlcs.is_empty());
6243                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6244                         },
6245                         _ => panic!("Unexpected event"),
6246                 };
6247                 {
6248                         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
6249                         // commitment transaction with a corresponding HTLC-Timeout transaction, as well as a
6250                         // timeout-claim of the output that nodes[2] just claimed via success.
6251                         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)
6252                         assert_eq!(node_txn.len(), 4);
6253                         assert_eq!(node_txn[0], node_txn[3]);
6254                         check_spends!(node_txn[0], commitment_tx[0].clone());
6255                         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6256                         assert_ne!(node_txn[0].lock_time, 0);
6257                         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6258                         check_spends!(node_txn[1], chan_2.3.clone());
6259                         check_spends!(node_txn[2], node_txn[1].clone());
6260                         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6261                         assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6262                         assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6263                         assert_ne!(node_txn[2].lock_time, 0);
6264                         node_txn.clear();
6265                 }
6266
6267                 // Broadcast legit commitment tx from A on B's chain
6268                 // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
6269                 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6270                 check_spends!(commitment_tx[0], chan_1.3.clone());
6271                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6272                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6273                 assert_eq!(events.len(), 1);
6274                 match events[0] {
6275                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6276                         _ => panic!("Unexpected event"),
6277                 }
6278                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
6279                 assert_eq!(node_txn.len(), 3);
6280                 assert_eq!(node_txn[0], node_txn[2]);
6281                 check_spends!(node_txn[0], commitment_tx[0].clone());
6282                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6283                 assert_eq!(node_txn[0].lock_time, 0);
6284                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
6285                 check_spends!(node_txn[1], chan_1.3.clone());
6286                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6287                 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
6288                 // we already checked the same situation with A.
6289
6290                 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
6291                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
6292                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6293                 assert_eq!(events.len(), 1);
6294                 match events[0] {
6295                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6296                         _ => panic!("Unexpected event"),
6297                 }
6298                 let events = nodes[0].node.get_and_clear_pending_events();
6299                 assert_eq!(events.len(), 1);
6300                 match events[0] {
6301                         Event::PaymentSent { payment_preimage } => {
6302                                 assert_eq!(payment_preimage, our_payment_preimage);
6303                         },
6304                         _ => panic!("Unexpected event"),
6305                 }
6306                 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)
6307                 assert_eq!(node_txn.len(), 4);
6308                 assert_eq!(node_txn[0], node_txn[3]);
6309                 check_spends!(node_txn[0], commitment_tx[0].clone());
6310                 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6311                 assert_ne!(node_txn[0].lock_time, 0);
6312                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6313                 check_spends!(node_txn[1], chan_1.3.clone());
6314                 check_spends!(node_txn[2], node_txn[1].clone());
6315                 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
6316                 assert_eq!(node_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6317                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
6318                 assert_ne!(node_txn[2].lock_time, 0);
6319         }
6320
6321         #[test]
6322         fn test_htlc_on_chain_timeout() {
6323                 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
6324                 // ChainWatchInterface and timeout the HTLC  bacward accordingly. So here we test that ChannelManager is
6325                 // broadcasting the right event to other nodes in payment path.
6326                 // A ------------------> B ----------------------> C (timeout)
6327                 //    B's commitment tx                 C's commitment tx
6328                 //            \                                  \
6329                 //         B's HTLC timeout tx               B's timeout tx
6330
6331                 let nodes = create_network(3);
6332
6333                 // Create some intial channels
6334                 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6335                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6336
6337                 // Rebalance the network a bit by relaying one payment thorugh all the channels...
6338                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6339                 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
6340
6341                 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
6342                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6343
6344                 // Brodacast legit commitment tx from C on B's chain
6345                 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6346                 check_spends!(commitment_tx[0], chan_2.3.clone());
6347                 nodes[2].node.fail_htlc_backwards(&payment_hash, PaymentFailReason::PreimageUnknown);
6348                 {
6349                         let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
6350                         assert_eq!(added_monitors.len(), 1);
6351                         added_monitors.clear();
6352                 }
6353                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6354                 assert_eq!(events.len(), 1);
6355                 match events[0] {
6356                         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, .. } } => {
6357                                 assert!(update_add_htlcs.is_empty());
6358                                 assert!(!update_fail_htlcs.is_empty());
6359                                 assert!(update_fulfill_htlcs.is_empty());
6360                                 assert!(update_fail_malformed_htlcs.is_empty());
6361                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
6362                         },
6363                         _ => panic!("Unexpected event"),
6364                 };
6365                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
6366                 let events = nodes[2].node.get_and_clear_pending_msg_events();
6367                 assert_eq!(events.len(), 1);
6368                 match events[0] {
6369                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6370                         _ => panic!("Unexpected event"),
6371                 }
6372                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
6373                 assert_eq!(node_txn.len(), 1);
6374                 check_spends!(node_txn[0], chan_2.3.clone());
6375                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
6376
6377                 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
6378                 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
6379                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6380                 let timeout_tx;
6381                 {
6382                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6383                         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)
6384                         assert_eq!(node_txn[0], node_txn[5]);
6385                         assert_eq!(node_txn[1], node_txn[6]);
6386                         assert_eq!(node_txn[2], node_txn[7]);
6387                         check_spends!(node_txn[0], commitment_tx[0].clone());
6388                         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6389                         check_spends!(node_txn[1], chan_2.3.clone());
6390                         check_spends!(node_txn[2], node_txn[1].clone());
6391                         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6392                         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6393                         check_spends!(node_txn[3], chan_2.3.clone());
6394                         check_spends!(node_txn[4], node_txn[3].clone());
6395                         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
6396                         assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6397                         timeout_tx = node_txn[0].clone();
6398                         node_txn.clear();
6399                 }
6400
6401                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
6402                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6403                 check_added_monitors!(nodes[1], 1);
6404                 assert_eq!(events.len(), 2);
6405                 match events[0] {
6406                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6407                         _ => panic!("Unexpected event"),
6408                 }
6409                 match events[1] {
6410                         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, .. } } => {
6411                                 assert!(update_add_htlcs.is_empty());
6412                                 assert!(!update_fail_htlcs.is_empty());
6413                                 assert!(update_fulfill_htlcs.is_empty());
6414                                 assert!(update_fail_malformed_htlcs.is_empty());
6415                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6416                         },
6417                         _ => panic!("Unexpected event"),
6418                 };
6419                 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
6420                 assert_eq!(node_txn.len(), 0);
6421
6422                 // Broadcast legit commitment tx from B on A's chain
6423                 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6424                 check_spends!(commitment_tx[0], chan_1.3.clone());
6425
6426                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
6427                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6428                 assert_eq!(events.len(), 1);
6429                 match events[0] {
6430                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6431                         _ => panic!("Unexpected event"),
6432                 }
6433                 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
6434                 assert_eq!(node_txn.len(), 4);
6435                 assert_eq!(node_txn[0], node_txn[3]);
6436                 check_spends!(node_txn[0], commitment_tx[0].clone());
6437                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6438                 check_spends!(node_txn[1], chan_1.3.clone());
6439                 check_spends!(node_txn[2], node_txn[1].clone());
6440                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
6441                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6442         }
6443
6444         #[test]
6445         fn test_simple_commitment_revoked_fail_backward() {
6446                 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
6447                 // and fail backward accordingly.
6448
6449                 let nodes = create_network(3);
6450
6451                 // Create some initial channels
6452                 create_announced_chan_between_nodes(&nodes, 0, 1);
6453                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6454
6455                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6456                 // Get the will-be-revoked local txn from nodes[2]
6457                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6458                 // Revoke the old state
6459                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6460
6461                 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6462
6463                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6464                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6465                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6466                 check_added_monitors!(nodes[1], 1);
6467                 assert_eq!(events.len(), 2);
6468                 match events[0] {
6469                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6470                         _ => panic!("Unexpected event"),
6471                 }
6472                 match events[1] {
6473                         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, .. } } => {
6474                                 assert!(update_add_htlcs.is_empty());
6475                                 assert_eq!(update_fail_htlcs.len(), 1);
6476                                 assert!(update_fulfill_htlcs.is_empty());
6477                                 assert!(update_fail_malformed_htlcs.is_empty());
6478                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6479
6480                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6481                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6482
6483                                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6484                                 assert_eq!(events.len(), 1);
6485                                 match events[0] {
6486                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6487                                         _ => panic!("Unexpected event"),
6488                                 }
6489                                 let events = nodes[0].node.get_and_clear_pending_events();
6490                                 assert_eq!(events.len(), 1);
6491                                 match events[0] {
6492                                         Event::PaymentFailed { .. } => {},
6493                                         _ => panic!("Unexpected event"),
6494                                 }
6495                         },
6496                         _ => panic!("Unexpected event"),
6497                 }
6498         }
6499
6500         fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool) {
6501                 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
6502                 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
6503                 // commitment transaction anymore.
6504                 // To do this, we have the peer which will broadcast a revoked commitment transaction send
6505                 // a number of update_fail/commitment_signed updates without ever sending the RAA in
6506                 // response to our commitment_signed. This is somewhat misbehavior-y, though not
6507                 // technically disallowed and we should probably handle it reasonably.
6508                 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
6509                 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
6510                 // transactions:
6511                 // * Once we move it out of our holding cell/add it, we will immediately include it in a
6512                 //   commitment_signed (implying it will be in the latest remote commitment transaction).
6513                 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
6514                 //   and once they revoke the previous commitment transaction (allowing us to send a new
6515                 //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
6516                 let mut nodes = create_network(3);
6517
6518                 // Create some initial channels
6519                 create_announced_chan_between_nodes(&nodes, 0, 1);
6520                 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6521
6522                 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6523                 // Get the will-be-revoked local txn from nodes[2]
6524                 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
6525                 // Revoke the old state
6526                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
6527
6528                 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6529                 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6530                 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
6531
6532                 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, PaymentFailReason::PreimageUnknown));
6533                 check_added_monitors!(nodes[2], 1);
6534                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6535                 assert!(updates.update_add_htlcs.is_empty());
6536                 assert!(updates.update_fulfill_htlcs.is_empty());
6537                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6538                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6539                 assert!(updates.update_fee.is_none());
6540                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6541                 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
6542                 // Drop the last RAA from 3 -> 2
6543
6544                 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, PaymentFailReason::PreimageUnknown));
6545                 check_added_monitors!(nodes[2], 1);
6546                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6547                 assert!(updates.update_add_htlcs.is_empty());
6548                 assert!(updates.update_fulfill_htlcs.is_empty());
6549                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6550                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6551                 assert!(updates.update_fee.is_none());
6552                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6553                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6554                 check_added_monitors!(nodes[1], 1);
6555                 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
6556                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6557                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6558                 check_added_monitors!(nodes[2], 1);
6559
6560                 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, PaymentFailReason::PreimageUnknown));
6561                 check_added_monitors!(nodes[2], 1);
6562                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6563                 assert!(updates.update_add_htlcs.is_empty());
6564                 assert!(updates.update_fulfill_htlcs.is_empty());
6565                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6566                 assert_eq!(updates.update_fail_htlcs.len(), 1);
6567                 assert!(updates.update_fee.is_none());
6568                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6569                 // At this point first_payment_hash has dropped out of the latest two commitment
6570                 // transactions that nodes[1] is tracking...
6571                 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
6572                 check_added_monitors!(nodes[1], 1);
6573                 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
6574                 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
6575                 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
6576                 check_added_monitors!(nodes[2], 1);
6577
6578                 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
6579                 // on nodes[2]'s RAA.
6580                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
6581                 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6582                 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
6583                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6584                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6585                 check_added_monitors!(nodes[1], 0);
6586
6587                 if deliver_bs_raa {
6588                         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
6589                         // One monitor for the new revocation preimage, one as we generate a commitment for
6590                         // nodes[0] to fail first_payment_hash backwards.
6591                         check_added_monitors!(nodes[1], 2);
6592                 }
6593
6594                 let mut failed_htlcs = HashSet::new();
6595                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
6596
6597                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6598                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6599
6600                 let events = nodes[1].node.get_and_clear_pending_events();
6601                 assert_eq!(events.len(), 1);
6602                 match events[0] {
6603                         Event::PaymentFailed { ref payment_hash, .. } => {
6604                                 assert_eq!(*payment_hash, fourth_payment_hash);
6605                         },
6606                         _ => panic!("Unexpected event"),
6607                 }
6608
6609                 if !deliver_bs_raa {
6610                         // If we delivered the RAA already then we already failed first_payment_hash backwards.
6611                         check_added_monitors!(nodes[1], 1);
6612                 }
6613
6614                 let events = nodes[1].node.get_and_clear_pending_msg_events();
6615                 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
6616                 match events[if deliver_bs_raa { 2 } else { 0 }] {
6617                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
6618                         _ => panic!("Unexpected event"),
6619                 }
6620                 if deliver_bs_raa {
6621                         match events[0] {
6622                                 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, .. } } => {
6623                                         assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
6624                                         assert_eq!(update_add_htlcs.len(), 1);
6625                                         assert!(update_fulfill_htlcs.is_empty());
6626                                         assert!(update_fail_htlcs.is_empty());
6627                                         assert!(update_fail_malformed_htlcs.is_empty());
6628                                 },
6629                                 _ => panic!("Unexpected event"),
6630                         }
6631                 }
6632                 // Due to the way backwards-failing occurs we do the updates in two steps.
6633                 let updates = match events[1] {
6634                         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, .. } } => {
6635                                 assert!(update_add_htlcs.is_empty());
6636                                 assert_eq!(update_fail_htlcs.len(), 1);
6637                                 assert!(update_fulfill_htlcs.is_empty());
6638                                 assert!(update_fail_malformed_htlcs.is_empty());
6639                                 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
6640
6641                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
6642                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
6643                                 check_added_monitors!(nodes[0], 1);
6644                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6645                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
6646                                 check_added_monitors!(nodes[1], 1);
6647                                 let bs_second_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6648                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
6649                                 check_added_monitors!(nodes[1], 1);
6650                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6651                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6652                                 check_added_monitors!(nodes[0], 1);
6653
6654                                 if !deliver_bs_raa {
6655                                         // If we delievered B's RAA we got an unknown preimage error, not something
6656                                         // that we should update our routing table for.
6657                                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6658                                         assert_eq!(events.len(), 1);
6659                                         match events[0] {
6660                                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6661                                                 _ => panic!("Unexpected event"),
6662                                         }
6663                                 }
6664                                 let events = nodes[0].node.get_and_clear_pending_events();
6665                                 assert_eq!(events.len(), 1);
6666                                 match events[0] {
6667                                         Event::PaymentFailed { ref payment_hash, .. } => {
6668                                                 assert!(failed_htlcs.insert(payment_hash.0));
6669                                         },
6670                                         _ => panic!("Unexpected event"),
6671                                 }
6672
6673                                 bs_second_update
6674                         },
6675                         _ => panic!("Unexpected event"),
6676                 };
6677
6678                 assert!(updates.update_add_htlcs.is_empty());
6679                 assert_eq!(updates.update_fail_htlcs.len(), 2);
6680                 assert!(updates.update_fulfill_htlcs.is_empty());
6681                 assert!(updates.update_fail_malformed_htlcs.is_empty());
6682                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
6683                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
6684                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6685
6686                 let events = nodes[0].node.get_and_clear_pending_msg_events();
6687                 assert_eq!(events.len(), 2);
6688                 for event in events {
6689                         match event {
6690                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6691                                 _ => panic!("Unexpected event"),
6692                         }
6693                 }
6694
6695                 let events = nodes[0].node.get_and_clear_pending_events();
6696                 assert_eq!(events.len(), 2);
6697                 match events[0] {
6698                         Event::PaymentFailed { ref payment_hash, .. } => {
6699                                 assert!(failed_htlcs.insert(payment_hash.0));
6700                         },
6701                         _ => panic!("Unexpected event"),
6702                 }
6703                 match events[1] {
6704                         Event::PaymentFailed { ref payment_hash, .. } => {
6705                                 assert!(failed_htlcs.insert(payment_hash.0));
6706                         },
6707                         _ => panic!("Unexpected event"),
6708                 }
6709
6710                 assert!(failed_htlcs.contains(&first_payment_hash.0));
6711                 assert!(failed_htlcs.contains(&second_payment_hash.0));
6712                 assert!(failed_htlcs.contains(&third_payment_hash.0));
6713         }
6714
6715         #[test]
6716         fn test_commitment_revoked_fail_backward_exhaustive() {
6717                 do_test_commitment_revoked_fail_backward_exhaustive(false);
6718                 do_test_commitment_revoked_fail_backward_exhaustive(true);
6719         }
6720
6721         #[test]
6722         fn test_htlc_ignore_latest_remote_commitment() {
6723                 // Test that HTLC transactions spending the latest remote commitment transaction are simply
6724                 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
6725                 let nodes = create_network(2);
6726                 create_announced_chan_between_nodes(&nodes, 0, 1);
6727
6728                 route_payment(&nodes[0], &[&nodes[1]], 10000000);
6729                 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
6730                 {
6731                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6732                         assert_eq!(events.len(), 1);
6733                         match events[0] {
6734                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6735                                         assert_eq!(flags & 0b10, 0b10);
6736                                 },
6737                                 _ => panic!("Unexpected event"),
6738                         }
6739                 }
6740
6741                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6742                 assert_eq!(node_txn.len(), 2);
6743
6744                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6745                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6746
6747                 {
6748                         let events = nodes[1].node.get_and_clear_pending_msg_events();
6749                         assert_eq!(events.len(), 1);
6750                         match events[0] {
6751                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6752                                         assert_eq!(flags & 0b10, 0b10);
6753                                 },
6754                                 _ => panic!("Unexpected event"),
6755                         }
6756                 }
6757
6758                 // Duplicate the block_connected call since this may happen due to other listeners
6759                 // registering new transactions
6760                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
6761         }
6762
6763         #[test]
6764         fn test_force_close_fail_back() {
6765                 // Check which HTLCs are failed-backwards on channel force-closure
6766                 let mut nodes = create_network(3);
6767                 create_announced_chan_between_nodes(&nodes, 0, 1);
6768                 create_announced_chan_between_nodes(&nodes, 1, 2);
6769
6770                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
6771
6772                 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6773
6774                 let mut payment_event = {
6775                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6776                         check_added_monitors!(nodes[0], 1);
6777
6778                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6779                         assert_eq!(events.len(), 1);
6780                         SendEvent::from_event(events.remove(0))
6781                 };
6782
6783                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6784                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6785
6786                 let events_1 = nodes[1].node.get_and_clear_pending_events();
6787                 assert_eq!(events_1.len(), 1);
6788                 match events_1[0] {
6789                         Event::PendingHTLCsForwardable { .. } => { },
6790                         _ => panic!("Unexpected event"),
6791                 };
6792
6793                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
6794                 nodes[1].node.process_pending_htlc_forwards();
6795
6796                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6797                 assert_eq!(events_2.len(), 1);
6798                 payment_event = SendEvent::from_event(events_2.remove(0));
6799                 assert_eq!(payment_event.msgs.len(), 1);
6800
6801                 check_added_monitors!(nodes[1], 1);
6802                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6803                 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
6804                 check_added_monitors!(nodes[2], 1);
6805                 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6806
6807                 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
6808                 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
6809                 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
6810
6811                 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
6812                 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6813                 assert_eq!(events_3.len(), 1);
6814                 match events_3[0] {
6815                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6816                                 assert_eq!(flags & 0b10, 0b10);
6817                         },
6818                         _ => panic!("Unexpected event"),
6819                 }
6820
6821                 let tx = {
6822                         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6823                         // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
6824                         // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
6825                         // back to nodes[1] upon timeout otherwise.
6826                         assert_eq!(node_txn.len(), 1);
6827                         node_txn.remove(0)
6828                 };
6829
6830                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6831                 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6832
6833                 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6834                 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
6835                 assert_eq!(events_4.len(), 1);
6836                 match events_4[0] {
6837                         MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6838                                 assert_eq!(flags & 0b10, 0b10);
6839                         },
6840                         _ => panic!("Unexpected event"),
6841                 }
6842
6843                 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
6844                 {
6845                         let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
6846                         monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
6847                                 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
6848                 }
6849                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
6850                 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
6851                 assert_eq!(node_txn.len(), 1);
6852                 assert_eq!(node_txn[0].input.len(), 1);
6853                 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
6854                 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
6855                 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
6856
6857                 check_spends!(node_txn[0], tx);
6858         }
6859
6860         #[test]
6861         fn test_unconf_chan() {
6862                 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
6863                 let nodes = create_network(2);
6864                 create_announced_chan_between_nodes(&nodes, 0, 1);
6865
6866                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6867                 assert_eq!(channel_state.by_id.len(), 1);
6868                 assert_eq!(channel_state.short_to_id.len(), 1);
6869                 mem::drop(channel_state);
6870
6871                 let mut headers = Vec::new();
6872                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6873                 headers.push(header.clone());
6874                 for _i in 2..100 {
6875                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6876                         headers.push(header.clone());
6877                 }
6878                 while !headers.is_empty() {
6879                         nodes[0].node.block_disconnected(&headers.pop().unwrap());
6880                 }
6881                 {
6882                         let events = nodes[0].node.get_and_clear_pending_msg_events();
6883                         assert_eq!(events.len(), 1);
6884                         match events[0] {
6885                                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
6886                                         assert_eq!(flags & 0b10, 0b10);
6887                                 },
6888                                 _ => panic!("Unexpected event"),
6889                         }
6890                 }
6891                 let channel_state = nodes[0].node.channel_state.lock().unwrap();
6892                 assert_eq!(channel_state.by_id.len(), 0);
6893                 assert_eq!(channel_state.short_to_id.len(), 0);
6894         }
6895
6896         macro_rules! get_chan_reestablish_msgs {
6897                 ($src_node: expr, $dst_node: expr) => {
6898                         {
6899                                 let mut res = Vec::with_capacity(1);
6900                                 for msg in $src_node.node.get_and_clear_pending_msg_events() {
6901                                         if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6902                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6903                                                 res.push(msg.clone());
6904                                         } else {
6905                                                 panic!("Unexpected event")
6906                                         }
6907                                 }
6908                                 res
6909                         }
6910                 }
6911         }
6912
6913         macro_rules! handle_chan_reestablish_msgs {
6914                 ($src_node: expr, $dst_node: expr) => {
6915                         {
6916                                 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
6917                                 let mut idx = 0;
6918                                 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
6919                                         idx += 1;
6920                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6921                                         Some(msg.clone())
6922                                 } else {
6923                                         None
6924                                 };
6925
6926                                 let mut revoke_and_ack = None;
6927                                 let mut commitment_update = None;
6928                                 let order = if let Some(ev) = msg_events.get(idx) {
6929                                         idx += 1;
6930                                         match ev {
6931                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6932                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6933                                                         revoke_and_ack = Some(msg.clone());
6934                                                         RAACommitmentOrder::RevokeAndACKFirst
6935                                                 },
6936                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6937                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6938                                                         commitment_update = Some(updates.clone());
6939                                                         RAACommitmentOrder::CommitmentFirst
6940                                                 },
6941                                                 _ => panic!("Unexpected event"),
6942                                         }
6943                                 } else {
6944                                         RAACommitmentOrder::CommitmentFirst
6945                                 };
6946
6947                                 if let Some(ev) = msg_events.get(idx) {
6948                                         match ev {
6949                                                 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
6950                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6951                                                         assert!(revoke_and_ack.is_none());
6952                                                         revoke_and_ack = Some(msg.clone());
6953                                                 },
6954                                                 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
6955                                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
6956                                                         assert!(commitment_update.is_none());
6957                                                         commitment_update = Some(updates.clone());
6958                                                 },
6959                                                 _ => panic!("Unexpected event"),
6960                                         }
6961                                 }
6962
6963                                 (funding_locked, revoke_and_ack, commitment_update, order)
6964                         }
6965                 }
6966         }
6967
6968         /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
6969         /// for claims/fails they are separated out.
6970         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)) {
6971                 node_a.node.peer_connected(&node_b.node.get_our_node_id());
6972                 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
6973                 node_b.node.peer_connected(&node_a.node.get_our_node_id());
6974                 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
6975
6976                 if send_funding_locked.0 {
6977                         // If a expects a funding_locked, it better not think it has received a revoke_and_ack
6978                         // from b
6979                         for reestablish in reestablish_1.iter() {
6980                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6981                         }
6982                 }
6983                 if send_funding_locked.1 {
6984                         // If b expects a funding_locked, it better not think it has received a revoke_and_ack
6985                         // from a
6986                         for reestablish in reestablish_2.iter() {
6987                                 assert_eq!(reestablish.next_remote_commitment_number, 0);
6988                         }
6989                 }
6990                 if send_funding_locked.0 || send_funding_locked.1 {
6991                         // If we expect any funding_locked's, both sides better have set
6992                         // next_local_commitment_number to 1
6993                         for reestablish in reestablish_1.iter() {
6994                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6995                         }
6996                         for reestablish in reestablish_2.iter() {
6997                                 assert_eq!(reestablish.next_local_commitment_number, 1);
6998                         }
6999                 }
7000
7001                 let mut resp_1 = Vec::new();
7002                 for msg in reestablish_1 {
7003                         node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
7004                         resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
7005                 }
7006                 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7007                         check_added_monitors!(node_b, 1);
7008                 } else {
7009                         check_added_monitors!(node_b, 0);
7010                 }
7011
7012                 let mut resp_2 = Vec::new();
7013                 for msg in reestablish_2 {
7014                         node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
7015                         resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
7016                 }
7017                 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7018                         check_added_monitors!(node_a, 1);
7019                 } else {
7020                         check_added_monitors!(node_a, 0);
7021                 }
7022
7023                 // We dont yet support both needing updates, as that would require a different commitment dance:
7024                 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
7025                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
7026
7027                 for chan_msgs in resp_1.drain(..) {
7028                         if send_funding_locked.0 {
7029                                 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7030                                 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
7031                                 if !announcement_event.is_empty() {
7032                                         assert_eq!(announcement_event.len(), 1);
7033                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7034                                                 //TODO: Test announcement_sigs re-sending
7035                                         } else { panic!("Unexpected event!"); }
7036                                 }
7037                         } else {
7038                                 assert!(chan_msgs.0.is_none());
7039                         }
7040                         if pending_raa.0 {
7041                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7042                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7043                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7044                                 check_added_monitors!(node_a, 1);
7045                         } else {
7046                                 assert!(chan_msgs.1.is_none());
7047                         }
7048                         if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
7049                                 let commitment_update = chan_msgs.2.unwrap();
7050                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7051                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
7052                                 } else {
7053                                         assert!(commitment_update.update_add_htlcs.is_empty());
7054                                 }
7055                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7056                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7057                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7058                                 for update_add in commitment_update.update_add_htlcs {
7059                                         node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
7060                                 }
7061                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7062                                         node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
7063                                 }
7064                                 for update_fail in commitment_update.update_fail_htlcs {
7065                                         node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
7066                                 }
7067
7068                                 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
7069                                         commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
7070                                 } else {
7071                                         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7072                                         check_added_monitors!(node_a, 1);
7073                                         let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
7074                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7075                                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7076                                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7077                                         check_added_monitors!(node_b, 1);
7078                                 }
7079                         } else {
7080                                 assert!(chan_msgs.2.is_none());
7081                         }
7082                 }
7083
7084                 for chan_msgs in resp_2.drain(..) {
7085                         if send_funding_locked.1 {
7086                                 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
7087                                 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
7088                                 if !announcement_event.is_empty() {
7089                                         assert_eq!(announcement_event.len(), 1);
7090                                         if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
7091                                                 //TODO: Test announcement_sigs re-sending
7092                                         } else { panic!("Unexpected event!"); }
7093                                 }
7094                         } else {
7095                                 assert!(chan_msgs.0.is_none());
7096                         }
7097                         if pending_raa.1 {
7098                                 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
7099                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
7100                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
7101                                 check_added_monitors!(node_b, 1);
7102                         } else {
7103                                 assert!(chan_msgs.1.is_none());
7104                         }
7105                         if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
7106                                 let commitment_update = chan_msgs.2.unwrap();
7107                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7108                                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
7109                                 }
7110                                 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
7111                                 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
7112                                 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
7113                                 for update_add in commitment_update.update_add_htlcs {
7114                                         node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
7115                                 }
7116                                 for update_fulfill in commitment_update.update_fulfill_htlcs {
7117                                         node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
7118                                 }
7119                                 for update_fail in commitment_update.update_fail_htlcs {
7120                                         node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
7121                                 }
7122
7123                                 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
7124                                         commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
7125                                 } else {
7126                                         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
7127                                         check_added_monitors!(node_b, 1);
7128                                         let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
7129                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
7130                                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7131                                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
7132                                         check_added_monitors!(node_a, 1);
7133                                 }
7134                         } else {
7135                                 assert!(chan_msgs.2.is_none());
7136                         }
7137                 }
7138         }
7139
7140         #[test]
7141         fn test_simple_peer_disconnect() {
7142                 // Test that we can reconnect when there are no lost messages
7143                 let nodes = create_network(3);
7144                 create_announced_chan_between_nodes(&nodes, 0, 1);
7145                 create_announced_chan_between_nodes(&nodes, 1, 2);
7146
7147                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7148                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7149                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7150
7151                 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7152                 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7153                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
7154                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
7155
7156                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7157                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7158                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7159
7160                 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7161                 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
7162                 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7163                 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
7164
7165                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7166                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7167
7168                 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
7169                 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
7170
7171                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
7172                 {
7173                         let events = nodes[0].node.get_and_clear_pending_events();
7174                         assert_eq!(events.len(), 2);
7175                         match events[0] {
7176                                 Event::PaymentSent { payment_preimage } => {
7177                                         assert_eq!(payment_preimage, payment_preimage_3);
7178                                 },
7179                                 _ => panic!("Unexpected event"),
7180                         }
7181                         match events[1] {
7182                                 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
7183                                         assert_eq!(payment_hash, payment_hash_5);
7184                                         assert!(rejected_by_dest);
7185                                 },
7186                                 _ => panic!("Unexpected event"),
7187                         }
7188                 }
7189
7190                 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
7191                 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
7192         }
7193
7194         fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
7195                 // Test that we can reconnect when in-flight HTLC updates get dropped
7196                 let mut nodes = create_network(2);
7197                 if messages_delivered == 0 {
7198                         create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
7199                         // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
7200                 } else {
7201                         create_announced_chan_between_nodes(&nodes, 0, 1);
7202                 }
7203
7204                 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();
7205                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7206
7207                 let payment_event = {
7208                         nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
7209                         check_added_monitors!(nodes[0], 1);
7210
7211                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7212                         assert_eq!(events.len(), 1);
7213                         SendEvent::from_event(events.remove(0))
7214                 };
7215                 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
7216
7217                 if messages_delivered < 2 {
7218                         // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
7219                 } else {
7220                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7221                         if messages_delivered >= 3 {
7222                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7223                                 check_added_monitors!(nodes[1], 1);
7224                                 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7225
7226                                 if messages_delivered >= 4 {
7227                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7228                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7229                                         check_added_monitors!(nodes[0], 1);
7230
7231                                         if messages_delivered >= 5 {
7232                                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
7233                                                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7234                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7235                                                 check_added_monitors!(nodes[0], 1);
7236
7237                                                 if messages_delivered >= 6 {
7238                                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7239                                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7240                                                         check_added_monitors!(nodes[1], 1);
7241                                                 }
7242                                         }
7243                                 }
7244                         }
7245                 }
7246
7247                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7248                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7249                 if messages_delivered < 3 {
7250                         // Even if the funding_locked messages get exchanged, as long as nothing further was
7251                         // received on either side, both sides will need to resend them.
7252                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
7253                 } else if messages_delivered == 3 {
7254                         // nodes[0] still wants its RAA + commitment_signed
7255                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
7256                 } else if messages_delivered == 4 {
7257                         // nodes[0] still wants its commitment_signed
7258                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
7259                 } else if messages_delivered == 5 {
7260                         // nodes[1] still wants its final RAA
7261                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
7262                 } else if messages_delivered == 6 {
7263                         // Everything was delivered...
7264                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7265                 }
7266
7267                 let events_1 = nodes[1].node.get_and_clear_pending_events();
7268                 assert_eq!(events_1.len(), 1);
7269                 match events_1[0] {
7270                         Event::PendingHTLCsForwardable { .. } => { },
7271                         _ => panic!("Unexpected event"),
7272                 };
7273
7274                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7275                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7276                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7277
7278                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7279                 nodes[1].node.process_pending_htlc_forwards();
7280
7281                 let events_2 = nodes[1].node.get_and_clear_pending_events();
7282                 assert_eq!(events_2.len(), 1);
7283                 match events_2[0] {
7284                         Event::PaymentReceived { ref payment_hash, amt } => {
7285                                 assert_eq!(payment_hash_1, *payment_hash);
7286                                 assert_eq!(amt, 1000000);
7287                         },
7288                         _ => panic!("Unexpected event"),
7289                 }
7290
7291                 nodes[1].node.claim_funds(payment_preimage_1);
7292                 check_added_monitors!(nodes[1], 1);
7293
7294                 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
7295                 assert_eq!(events_3.len(), 1);
7296                 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
7297                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
7298                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7299                                 assert!(updates.update_add_htlcs.is_empty());
7300                                 assert!(updates.update_fail_htlcs.is_empty());
7301                                 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7302                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
7303                                 assert!(updates.update_fee.is_none());
7304                                 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
7305                         },
7306                         _ => panic!("Unexpected event"),
7307                 };
7308
7309                 if messages_delivered >= 1 {
7310                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
7311
7312                         let events_4 = nodes[0].node.get_and_clear_pending_events();
7313                         assert_eq!(events_4.len(), 1);
7314                         match events_4[0] {
7315                                 Event::PaymentSent { ref payment_preimage } => {
7316                                         assert_eq!(payment_preimage_1, *payment_preimage);
7317                                 },
7318                                 _ => panic!("Unexpected event"),
7319                         }
7320
7321                         if messages_delivered >= 2 {
7322                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
7323                                 check_added_monitors!(nodes[0], 1);
7324                                 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7325
7326                                 if messages_delivered >= 3 {
7327                                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7328                                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7329                                         check_added_monitors!(nodes[1], 1);
7330
7331                                         if messages_delivered >= 4 {
7332                                                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
7333                                                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7334                                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7335                                                 check_added_monitors!(nodes[1], 1);
7336
7337                                                 if messages_delivered >= 5 {
7338                                                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7339                                                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7340                                                         check_added_monitors!(nodes[0], 1);
7341                                                 }
7342                                         }
7343                                 }
7344                         }
7345                 }
7346
7347                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7348                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7349                 if messages_delivered < 2 {
7350                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
7351                         //TODO: Deduplicate PaymentSent events, then enable this if:
7352                         //if messages_delivered < 1 {
7353                                 let events_4 = nodes[0].node.get_and_clear_pending_events();
7354                                 assert_eq!(events_4.len(), 1);
7355                                 match events_4[0] {
7356                                         Event::PaymentSent { ref payment_preimage } => {
7357                                                 assert_eq!(payment_preimage_1, *payment_preimage);
7358                                         },
7359                                         _ => panic!("Unexpected event"),
7360                                 }
7361                         //}
7362                 } else if messages_delivered == 2 {
7363                         // nodes[0] still wants its RAA + commitment_signed
7364                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
7365                 } else if messages_delivered == 3 {
7366                         // nodes[0] still wants its commitment_signed
7367                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
7368                 } else if messages_delivered == 4 {
7369                         // nodes[1] still wants its final RAA
7370                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
7371                 } else if messages_delivered == 5 {
7372                         // Everything was delivered...
7373                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7374                 }
7375
7376                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7377                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7378                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7379
7380                 // Channel should still work fine...
7381                 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
7382                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7383         }
7384
7385         #[test]
7386         fn test_drop_messages_peer_disconnect_a() {
7387                 do_test_drop_messages_peer_disconnect(0);
7388                 do_test_drop_messages_peer_disconnect(1);
7389                 do_test_drop_messages_peer_disconnect(2);
7390                 do_test_drop_messages_peer_disconnect(3);
7391         }
7392
7393         #[test]
7394         fn test_drop_messages_peer_disconnect_b() {
7395                 do_test_drop_messages_peer_disconnect(4);
7396                 do_test_drop_messages_peer_disconnect(5);
7397                 do_test_drop_messages_peer_disconnect(6);
7398         }
7399
7400         #[test]
7401         fn test_funding_peer_disconnect() {
7402                 // Test that we can lock in our funding tx while disconnected
7403                 let nodes = create_network(2);
7404                 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
7405
7406                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7407                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7408
7409                 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
7410                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7411                 assert_eq!(events_1.len(), 1);
7412                 match events_1[0] {
7413                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7414                                 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7415                         },
7416                         _ => panic!("Unexpected event"),
7417                 }
7418
7419                 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7420
7421                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7422                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7423
7424                 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
7425                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7426                 assert_eq!(events_2.len(), 2);
7427                 match events_2[0] {
7428                         MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
7429                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7430                         },
7431                         _ => panic!("Unexpected event"),
7432                 }
7433                 match events_2[1] {
7434                         MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
7435                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7436                         },
7437                         _ => panic!("Unexpected event"),
7438                 }
7439
7440                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7441
7442                 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
7443                 // rebroadcasting announcement_signatures upon reconnect.
7444
7445                 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();
7446                 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
7447                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
7448         }
7449
7450         #[test]
7451         fn test_drop_messages_peer_disconnect_dual_htlc() {
7452                 // Test that we can handle reconnecting when both sides of a channel have pending
7453                 // commitment_updates when we disconnect.
7454                 let mut nodes = create_network(2);
7455                 create_announced_chan_between_nodes(&nodes, 0, 1);
7456
7457                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7458
7459                 // Now try to send a second payment which will fail to send
7460                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7461                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7462
7463                 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
7464                 check_added_monitors!(nodes[0], 1);
7465
7466                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7467                 assert_eq!(events_1.len(), 1);
7468                 match events_1[0] {
7469                         MessageSendEvent::UpdateHTLCs { .. } => {},
7470                         _ => panic!("Unexpected event"),
7471                 }
7472
7473                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7474                 check_added_monitors!(nodes[1], 1);
7475
7476                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7477                 assert_eq!(events_2.len(), 1);
7478                 match events_2[0] {
7479                         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 } } => {
7480                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7481                                 assert!(update_add_htlcs.is_empty());
7482                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7483                                 assert!(update_fail_htlcs.is_empty());
7484                                 assert!(update_fail_malformed_htlcs.is_empty());
7485                                 assert!(update_fee.is_none());
7486
7487                                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7488                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7489                                 assert_eq!(events_3.len(), 1);
7490                                 match events_3[0] {
7491                                         Event::PaymentSent { ref payment_preimage } => {
7492                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7493                                         },
7494                                         _ => panic!("Unexpected event"),
7495                                 }
7496
7497                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
7498                                 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7499                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7500                                 check_added_monitors!(nodes[0], 1);
7501                         },
7502                         _ => panic!("Unexpected event"),
7503                 }
7504
7505                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7506                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7507
7508                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7509                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7510                 assert_eq!(reestablish_1.len(), 1);
7511                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7512                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7513                 assert_eq!(reestablish_2.len(), 1);
7514
7515                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7516                 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7517                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7518                 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7519
7520                 assert!(as_resp.0.is_none());
7521                 assert!(bs_resp.0.is_none());
7522
7523                 assert!(bs_resp.1.is_none());
7524                 assert!(bs_resp.2.is_none());
7525
7526                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7527
7528                 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
7529                 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
7530                 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7531                 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7532                 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
7533                 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();
7534                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7535                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7536                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7537                 check_added_monitors!(nodes[1], 1);
7538
7539                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
7540                 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7541                 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
7542                 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
7543                 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
7544                 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
7545                 assert!(bs_second_commitment_signed.update_fee.is_none());
7546                 check_added_monitors!(nodes[1], 1);
7547
7548                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7549                 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7550                 assert!(as_commitment_signed.update_add_htlcs.is_empty());
7551                 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
7552                 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
7553                 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
7554                 assert!(as_commitment_signed.update_fee.is_none());
7555                 check_added_monitors!(nodes[0], 1);
7556
7557                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
7558                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7559                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7560                 check_added_monitors!(nodes[0], 1);
7561
7562                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
7563                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7564                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7565                 check_added_monitors!(nodes[1], 1);
7566
7567                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
7568                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7569                 check_added_monitors!(nodes[1], 1);
7570
7571                 let events_4 = nodes[1].node.get_and_clear_pending_events();
7572                 assert_eq!(events_4.len(), 1);
7573                 match events_4[0] {
7574                         Event::PendingHTLCsForwardable { .. } => { },
7575                         _ => panic!("Unexpected event"),
7576                 };
7577
7578                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
7579                 nodes[1].node.process_pending_htlc_forwards();
7580
7581                 let events_5 = nodes[1].node.get_and_clear_pending_events();
7582                 assert_eq!(events_5.len(), 1);
7583                 match events_5[0] {
7584                         Event::PaymentReceived { ref payment_hash, amt: _ } => {
7585                                 assert_eq!(payment_hash_2, *payment_hash);
7586                         },
7587                         _ => panic!("Unexpected event"),
7588                 }
7589
7590                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
7591                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7592                 check_added_monitors!(nodes[0], 1);
7593
7594                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
7595         }
7596
7597         #[test]
7598         fn test_simple_monitor_permanent_update_fail() {
7599                 // Test that we handle a simple permanent monitor update failure
7600                 let mut nodes = create_network(2);
7601                 create_announced_chan_between_nodes(&nodes, 0, 1);
7602
7603                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7604                 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7605
7606                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7607                 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
7608                 check_added_monitors!(nodes[0], 1);
7609
7610                 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
7611                 assert_eq!(events_1.len(), 2);
7612                 match events_1[0] {
7613                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7614                         _ => panic!("Unexpected event"),
7615                 };
7616                 match events_1[1] {
7617                         MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
7618                         _ => panic!("Unexpected event"),
7619                 };
7620
7621                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7622                 // PaymentFailed event
7623
7624                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7625         }
7626
7627         fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
7628                 // Test that we can recover from a simple temporary monitor update failure optionally with
7629                 // a disconnect in between
7630                 let mut nodes = create_network(2);
7631                 create_announced_chan_between_nodes(&nodes, 0, 1);
7632
7633                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7634                 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
7635
7636                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7637                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
7638                 check_added_monitors!(nodes[0], 1);
7639
7640                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7641                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7642                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7643
7644                 if disconnect {
7645                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7646                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7647                         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7648                 }
7649
7650                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7651                 nodes[0].node.test_restore_channel_monitor();
7652                 check_added_monitors!(nodes[0], 1);
7653
7654                 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
7655                 assert_eq!(events_2.len(), 1);
7656                 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
7657                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7658                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7659                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7660
7661                 expect_pending_htlcs_forwardable!(nodes[1]);
7662
7663                 let events_3 = nodes[1].node.get_and_clear_pending_events();
7664                 assert_eq!(events_3.len(), 1);
7665                 match events_3[0] {
7666                         Event::PaymentReceived { ref payment_hash, amt } => {
7667                                 assert_eq!(payment_hash_1, *payment_hash);
7668                                 assert_eq!(amt, 1000000);
7669                         },
7670                         _ => panic!("Unexpected event"),
7671                 }
7672
7673                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
7674
7675                 // Now set it to failed again...
7676                 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7677                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7678                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
7679                 check_added_monitors!(nodes[0], 1);
7680
7681                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7682                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7683                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7684
7685                 if disconnect {
7686                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7687                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7688                         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
7689                 }
7690
7691                 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
7692                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
7693                 nodes[0].node.test_restore_channel_monitor();
7694                 check_added_monitors!(nodes[0], 1);
7695
7696                 let events_5 = nodes[0].node.get_and_clear_pending_msg_events();
7697                 assert_eq!(events_5.len(), 1);
7698                 match events_5[0] {
7699                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
7700                         _ => panic!("Unexpected event"),
7701                 }
7702
7703                 // TODO: Once we hit the chain with the failure transaction we should check that we get a
7704                 // PaymentFailed event
7705
7706                 assert_eq!(nodes[0].node.list_channels().len(), 0);
7707         }
7708
7709         #[test]
7710         fn test_simple_monitor_temporary_update_fail() {
7711                 do_test_simple_monitor_temporary_update_fail(false);
7712                 do_test_simple_monitor_temporary_update_fail(true);
7713         }
7714
7715         fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
7716                 let disconnect_flags = 8 | 16;
7717
7718                 // Test that we can recover from a temporary monitor update failure with some in-flight
7719                 // HTLCs going on at the same time potentially with some disconnection thrown in.
7720                 // * First we route a payment, then get a temporary monitor update failure when trying to
7721                 //   route a second payment. We then claim the first payment.
7722                 // * If disconnect_count is set, we will disconnect at this point (which is likely as
7723                 //   TemporaryFailure likely indicates net disconnect which resulted in failing to update
7724                 //   the ChannelMonitor on a watchtower).
7725                 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
7726                 //   immediately, otherwise we wait sconnect and deliver them via the reconnect
7727                 //   channel_reestablish processing (ie disconnect_count & 16 makes no sense if
7728                 //   disconnect_count & !disconnect_flags is 0).
7729                 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
7730                 //   through message sending, potentially disconnect/reconnecting multiple times based on
7731                 //   disconnect_count, to get the update_fulfill_htlc through.
7732                 // * We then walk through more message exchanges to get the original update_add_htlc
7733                 //   through, swapping message ordering based on disconnect_count & 8 and optionally
7734                 //   disconnect/reconnecting based on disconnect_count.
7735                 let mut nodes = create_network(2);
7736                 create_announced_chan_between_nodes(&nodes, 0, 1);
7737
7738                 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7739
7740                 // Now try to send a second payment which will fail to send
7741                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
7742                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
7743
7744                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
7745                 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
7746                 check_added_monitors!(nodes[0], 1);
7747
7748                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7749                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7750                 assert_eq!(nodes[0].node.list_channels().len(), 1);
7751
7752                 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
7753                 // but nodes[0] won't respond since it is frozen.
7754                 assert!(nodes[1].node.claim_funds(payment_preimage_1));
7755                 check_added_monitors!(nodes[1], 1);
7756                 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7757                 assert_eq!(events_2.len(), 1);
7758                 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
7759                         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 } } => {
7760                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7761                                 assert!(update_add_htlcs.is_empty());
7762                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7763                                 assert!(update_fail_htlcs.is_empty());
7764                                 assert!(update_fail_malformed_htlcs.is_empty());
7765                                 assert!(update_fee.is_none());
7766
7767                                 if (disconnect_count & 16) == 0 {
7768                                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
7769                                         let events_3 = nodes[0].node.get_and_clear_pending_events();
7770                                         assert_eq!(events_3.len(), 1);
7771                                         match events_3[0] {
7772                                                 Event::PaymentSent { ref payment_preimage } => {
7773                                                         assert_eq!(*payment_preimage, payment_preimage_1);
7774                                                 },
7775                                                 _ => panic!("Unexpected event"),
7776                                         }
7777
7778                                         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) {
7779                                                 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
7780                                         } else { panic!(); }
7781                                 }
7782
7783                                 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
7784                         },
7785                         _ => panic!("Unexpected event"),
7786                 };
7787
7788                 if disconnect_count & !disconnect_flags > 0 {
7789                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7790                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7791                 }
7792
7793                 // Now fix monitor updating...
7794                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
7795                 nodes[0].node.test_restore_channel_monitor();
7796                 check_added_monitors!(nodes[0], 1);
7797
7798                 macro_rules! disconnect_reconnect_peers { () => { {
7799                         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7800                         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7801
7802                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7803                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7804                         assert_eq!(reestablish_1.len(), 1);
7805                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7806                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7807                         assert_eq!(reestablish_2.len(), 1);
7808
7809                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7810                         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7811                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7812                         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7813
7814                         assert!(as_resp.0.is_none());
7815                         assert!(bs_resp.0.is_none());
7816
7817                         (reestablish_1, reestablish_2, as_resp, bs_resp)
7818                 } } }
7819
7820                 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
7821                         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
7822                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7823
7824                         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
7825                         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7826                         assert_eq!(reestablish_1.len(), 1);
7827                         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
7828                         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7829                         assert_eq!(reestablish_2.len(), 1);
7830
7831                         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
7832                         check_added_monitors!(nodes[0], 0);
7833                         let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7834                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
7835                         check_added_monitors!(nodes[1], 0);
7836                         let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7837
7838                         assert!(as_resp.0.is_none());
7839                         assert!(bs_resp.0.is_none());
7840
7841                         assert!(bs_resp.1.is_none());
7842                         if (disconnect_count & 16) == 0 {
7843                                 assert!(bs_resp.2.is_none());
7844
7845                                 assert!(as_resp.1.is_some());
7846                                 assert!(as_resp.2.is_some());
7847                                 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
7848                         } else {
7849                                 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
7850                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
7851                                 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
7852                                 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
7853                                 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
7854                                 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
7855
7856                                 assert!(as_resp.1.is_none());
7857
7858                                 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();
7859                                 let events_3 = nodes[0].node.get_and_clear_pending_events();
7860                                 assert_eq!(events_3.len(), 1);
7861                                 match events_3[0] {
7862                                         Event::PaymentSent { ref payment_preimage } => {
7863                                                 assert_eq!(*payment_preimage, payment_preimage_1);
7864                                         },
7865                                         _ => panic!("Unexpected event"),
7866                                 }
7867
7868                                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
7869                                 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
7870                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
7871                                 check_added_monitors!(nodes[0], 1);
7872
7873                                 as_resp.1 = Some(as_resp_raa);
7874                                 bs_resp.2 = None;
7875                         }
7876
7877                         if disconnect_count & !disconnect_flags > 1 {
7878                                 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
7879
7880                                 if (disconnect_count & 16) == 0 {
7881                                         assert!(reestablish_1 == second_reestablish_1);
7882                                         assert!(reestablish_2 == second_reestablish_2);
7883                                 }
7884                                 assert!(as_resp == second_as_resp);
7885                                 assert!(bs_resp == second_bs_resp);
7886                         }
7887
7888                         (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
7889                 } else {
7890                         let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
7891                         assert_eq!(events_4.len(), 2);
7892                         (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
7893                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
7894                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7895                                         msg.clone()
7896                                 },
7897                                 _ => panic!("Unexpected event"),
7898                         })
7899                 };
7900
7901                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
7902
7903                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
7904                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
7905                 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
7906                 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
7907                 check_added_monitors!(nodes[1], 1);
7908
7909                 if disconnect_count & !disconnect_flags > 2 {
7910                         let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7911
7912                         assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7913                         assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7914
7915                         assert!(as_resp.2.is_none());
7916                         assert!(bs_resp.2.is_none());
7917                 }
7918
7919                 let as_commitment_update;
7920                 let bs_second_commitment_update;
7921
7922                 macro_rules! handle_bs_raa { () => {
7923                         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
7924                         as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7925                         assert!(as_commitment_update.update_add_htlcs.is_empty());
7926                         assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
7927                         assert!(as_commitment_update.update_fail_htlcs.is_empty());
7928                         assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
7929                         assert!(as_commitment_update.update_fee.is_none());
7930                         check_added_monitors!(nodes[0], 1);
7931                 } }
7932
7933                 macro_rules! handle_initial_raa { () => {
7934                         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
7935                         bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7936                         assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
7937                         assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
7938                         assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
7939                         assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
7940                         assert!(bs_second_commitment_update.update_fee.is_none());
7941                         check_added_monitors!(nodes[1], 1);
7942                 } }
7943
7944                 if (disconnect_count & 8) == 0 {
7945                         handle_bs_raa!();
7946
7947                         if disconnect_count & !disconnect_flags > 3 {
7948                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7949
7950                                 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
7951                                 assert!(bs_resp.1.is_none());
7952
7953                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7954                                 assert!(bs_resp.2.is_none());
7955
7956                                 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7957                         }
7958
7959                         handle_initial_raa!();
7960
7961                         if disconnect_count & !disconnect_flags > 4 {
7962                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7963
7964                                 assert!(as_resp.1.is_none());
7965                                 assert!(bs_resp.1.is_none());
7966
7967                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7968                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7969                         }
7970                 } else {
7971                         handle_initial_raa!();
7972
7973                         if disconnect_count & !disconnect_flags > 3 {
7974                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7975
7976                                 assert!(as_resp.1.is_none());
7977                                 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
7978
7979                                 assert!(as_resp.2.is_none());
7980                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7981
7982                                 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
7983                         }
7984
7985                         handle_bs_raa!();
7986
7987                         if disconnect_count & !disconnect_flags > 4 {
7988                                 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
7989
7990                                 assert!(as_resp.1.is_none());
7991                                 assert!(bs_resp.1.is_none());
7992
7993                                 assert!(as_resp.2.unwrap() == as_commitment_update);
7994                                 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
7995                         }
7996                 }
7997
7998                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
7999                 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8000                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8001                 check_added_monitors!(nodes[0], 1);
8002
8003                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
8004                 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
8005                 // No commitment_signed so get_event_msg's assert(len == 1) passes
8006                 check_added_monitors!(nodes[1], 1);
8007
8008                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
8009                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8010                 check_added_monitors!(nodes[1], 1);
8011
8012                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
8013                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8014                 check_added_monitors!(nodes[0], 1);
8015
8016                 expect_pending_htlcs_forwardable!(nodes[1]);
8017
8018                 let events_5 = nodes[1].node.get_and_clear_pending_events();
8019                 assert_eq!(events_5.len(), 1);
8020                 match events_5[0] {
8021                         Event::PaymentReceived { ref payment_hash, amt } => {
8022                                 assert_eq!(payment_hash_2, *payment_hash);
8023                                 assert_eq!(amt, 1000000);
8024                         },
8025                         _ => panic!("Unexpected event"),
8026                 }
8027
8028                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
8029         }
8030
8031         #[test]
8032         fn test_monitor_temporary_update_fail_a() {
8033                 do_test_monitor_temporary_update_fail(0);
8034                 do_test_monitor_temporary_update_fail(1);
8035                 do_test_monitor_temporary_update_fail(2);
8036                 do_test_monitor_temporary_update_fail(3);
8037                 do_test_monitor_temporary_update_fail(4);
8038                 do_test_monitor_temporary_update_fail(5);
8039         }
8040
8041         #[test]
8042         fn test_monitor_temporary_update_fail_b() {
8043                 do_test_monitor_temporary_update_fail(2 | 8);
8044                 do_test_monitor_temporary_update_fail(3 | 8);
8045                 do_test_monitor_temporary_update_fail(4 | 8);
8046                 do_test_monitor_temporary_update_fail(5 | 8);
8047         }
8048
8049         #[test]
8050         fn test_monitor_temporary_update_fail_c() {
8051                 do_test_monitor_temporary_update_fail(1 | 16);
8052                 do_test_monitor_temporary_update_fail(2 | 16);
8053                 do_test_monitor_temporary_update_fail(3 | 16);
8054                 do_test_monitor_temporary_update_fail(2 | 8 | 16);
8055                 do_test_monitor_temporary_update_fail(3 | 8 | 16);
8056         }
8057
8058         #[test]
8059         fn test_monitor_update_fail_cs() {
8060                 // Tests handling of a monitor update failure when processing an incoming commitment_signed
8061                 let mut nodes = create_network(2);
8062                 create_announced_chan_between_nodes(&nodes, 0, 1);
8063
8064                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8065                 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
8066                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
8067                 check_added_monitors!(nodes[0], 1);
8068
8069                 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8070                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8071
8072                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8073                 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() {
8074                         assert_eq!(err, "Failed to update ChannelMonitor");
8075                 } else { panic!(); }
8076                 check_added_monitors!(nodes[1], 1);
8077                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8078
8079                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
8080                 nodes[1].node.test_restore_channel_monitor();
8081                 check_added_monitors!(nodes[1], 1);
8082                 let responses = nodes[1].node.get_and_clear_pending_msg_events();
8083                 assert_eq!(responses.len(), 2);
8084
8085                 match responses[0] {
8086                         MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
8087                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8088                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
8089                                 check_added_monitors!(nodes[0], 1);
8090                         },
8091                         _ => panic!("Unexpected event"),
8092                 }
8093                 match responses[1] {
8094                         MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
8095                                 assert!(updates.update_add_htlcs.is_empty());
8096                                 assert!(updates.update_fulfill_htlcs.is_empty());
8097                                 assert!(updates.update_fail_htlcs.is_empty());
8098                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8099                                 assert!(updates.update_fee.is_none());
8100                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8101
8102                                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8103                                 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() {
8104                                         assert_eq!(err, "Failed to update ChannelMonitor");
8105                                 } else { panic!(); }
8106                                 check_added_monitors!(nodes[0], 1);
8107                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8108                         },
8109                         _ => panic!("Unexpected event"),
8110                 }
8111
8112                 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
8113                 nodes[0].node.test_restore_channel_monitor();
8114                 check_added_monitors!(nodes[0], 1);
8115
8116                 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
8117                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
8118                 check_added_monitors!(nodes[1], 1);
8119
8120                 let mut events = nodes[1].node.get_and_clear_pending_events();
8121                 assert_eq!(events.len(), 1);
8122                 match events[0] {
8123                         Event::PendingHTLCsForwardable { .. } => { },
8124                         _ => panic!("Unexpected event"),
8125                 };
8126                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8127                 nodes[1].node.process_pending_htlc_forwards();
8128
8129                 events = nodes[1].node.get_and_clear_pending_events();
8130                 assert_eq!(events.len(), 1);
8131                 match events[0] {
8132                         Event::PaymentReceived { payment_hash, amt } => {
8133                                 assert_eq!(payment_hash, our_payment_hash);
8134                                 assert_eq!(amt, 1000000);
8135                         },
8136                         _ => panic!("Unexpected event"),
8137                 };
8138
8139                 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
8140         }
8141
8142         fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
8143                 // Tests handling of a monitor update failure when processing an incoming RAA
8144                 let mut nodes = create_network(3);
8145                 create_announced_chan_between_nodes(&nodes, 0, 1);
8146                 create_announced_chan_between_nodes(&nodes, 1, 2);
8147
8148                 // Rebalance a bit so that we can send backwards from 2 to 1.
8149                 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
8150
8151                 // Route a first payment that we'll fail backwards
8152                 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
8153
8154                 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
8155                 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, PaymentFailReason::PreimageUnknown));
8156                 check_added_monitors!(nodes[2], 1);
8157
8158                 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8159                 assert!(updates.update_add_htlcs.is_empty());
8160                 assert!(updates.update_fulfill_htlcs.is_empty());
8161                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8162                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8163                 assert!(updates.update_fee.is_none());
8164                 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8165
8166                 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
8167                 check_added_monitors!(nodes[0], 0);
8168
8169                 // While the second channel is AwaitingRAA, forward a second payment to get it into the
8170                 // holding cell.
8171                 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
8172                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8173                 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
8174                 check_added_monitors!(nodes[0], 1);
8175
8176                 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8177                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8178                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
8179
8180                 let events_1 = nodes[1].node.get_and_clear_pending_events();
8181                 assert_eq!(events_1.len(), 1);
8182                 match events_1[0] {
8183                         Event::PendingHTLCsForwardable { .. } => { },
8184                         _ => panic!("Unexpected event"),
8185                 };
8186
8187                 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
8188                 nodes[1].node.process_pending_htlc_forwards();
8189                 check_added_monitors!(nodes[1], 0);
8190                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8191
8192                 // Now fail monitor updating.
8193                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
8194                 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() {
8195                         assert_eq!(err, "Failed to update ChannelMonitor");
8196                 } else { panic!(); }
8197                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8198                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8199                 check_added_monitors!(nodes[1], 1);
8200
8201                 // Attempt to forward a third payment but fail due to the second channel being unavailable
8202                 // for forwarding.
8203
8204                 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
8205                 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
8206                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
8207                 check_added_monitors!(nodes[0], 1);
8208
8209                 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
8210                 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
8211                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
8212                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
8213                 check_added_monitors!(nodes[1], 0);
8214
8215                 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8216                 assert_eq!(events_2.len(), 1);
8217                 match events_2.remove(0) {
8218                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
8219                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8220                                 assert!(updates.update_fulfill_htlcs.is_empty());
8221                                 assert_eq!(updates.update_fail_htlcs.len(), 1);
8222                                 assert!(updates.update_fail_malformed_htlcs.is_empty());
8223                                 assert!(updates.update_add_htlcs.is_empty());
8224                                 assert!(updates.update_fee.is_none());
8225
8226                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
8227                                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
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 }